Beruflich Dokumente
Kultur Dokumente
Using SQL, create a table called university_building, including all relevant constraints, using the
following specification:
a) A column named “code” of type varchar, with a maximum size of 2, which will be the primary
key
b) A column named “status” of type varchar, with a maximum size of 20
c) Status must not be NULL
2. Using SQL, create a table called building_room, including all relevant constraints, using the
following specification:
a) A column named “building_code” of type varchar, with a maximum size of 2
b) A column named “room_number” of type integer
c) A column named “capacity” of type integer
d) Both building_code and room_number form the composite primary key.
e) Capacity must be greater than 0
3. Try to insert the following data using SQL. Explain if there was any error, and why.
a) A building with code “TI” and status “active”
INSERT INTO university_building VALUES ('TI', 'active');
b) Find out in the pgAdmin interface the corresponding SQL code for the constraint.
ALTER TABLE building_room
ADD CONSTRAING fk_room_building
FOREIGN KEY (building_code)
REFERENCES university_building(code);
c) Insert a new room in building “TD”, with room number 1005, and capacity 60. Do you get an
error? Why?
INSERT INTO building_room VALUES ('TD', 1005, 60);
We get an error because the building with code ‘TD’ is not present in the university_building
table.
5. Using SQL, create a new table courses in which to represent courses taught at a university.
Define at least three columns for the table. One of these columns must store the room in which
the course is taught. The definition must include a primary key, a foreign key and a check
constraint.
CREATE TABLE courses(
course_code varchar(7),
student_number integer,
room integer,
CONSTRAINT pk_courses PRIMARY KEY(course_code),
CONSTRAINT fk_courses FOREIGN KEY(room) REFERENCES
building_room(room_number),
CONSTRAINT check_student_number CHECK(student_number > 0));
6. (Optional) Try the following queries. Refer to the theory materials if necessary.
a) What is the total capacity of all rooms?
SELECT SUM(capacity)
FROM building_room;
The total capacity of all rooms is 121.
c) List all the rooms with capacity greater than 50, ordering by capacity.
SELECT room_number, capacity
FROM building_room
WHERE capacity > 50
ORDER BY capacity DESC;