8.2.4 SQL DDL: Alter Tables and Define Foreign Keys
ALTER TABLE changes an existing table definition. A foreign-key constraint names the field and the referenced primary key.
By the end of this page, you should be able to:
- define and use the key terms accurately;
- explain how the idea works using a new example;
- apply the idea to a database design or SQL task.
1. Change a table definition
ALTER TABLE changes a tableβs structure. It can add a field or a constraint. For example, an existing Appointment table may need a RoomID field after the system begins recording room allocations.
2. Name the referencing and referenced fields
The referencing table contains the foreign key. The referenced table contains the primary key. When defining the constraint, identify both sides carefully and make their data types compatible.
3. Use REFERENCES to identify the target
A foreign-key definition names the local field, then uses REFERENCES to identify the target table and field. The DBMS can then check new or updated values against the target key.
4. Keep links valid
If a non-NULL foreign-key value has no matching primary-key value, the constraint rejects the change. A DBMS can also apply defined rules when a referenced record is changed or removed. Do not assume a particular cascade rule unless one is specified.
Worked example
Room(RoomID INTEGER primary key) already exists. To connect Reservation to Room, add Reservation.RoomID and define it to reference Room.RoomID. A value such as 6 is accepted only if RoomID 6 exists, unless the relationship is left empty and NULL is permitted.
Common mistake to avoid
In the phrase FOREIGN KEY (RoomID) REFERENCES Room(RoomID), the first RoomID belongs to the table being altered; the Room.RoomID inside REFERENCES is the target key.
Interactive check
Choose an answer, read the explanation, and continue to the next example.
Independent practice
Try this original question before opening the suggested response.
Assume Studio(StudioID) already exists. Write statements to add StudioID as an INTEGER field to Booking and make it a foreign key referencing Studio(StudioID). (4)
Suggested response
ALTER TABLE Booking ADD StudioID INTEGER;
ALTER TABLE Booking ADD FOREIGN KEY (StudioID) REFERENCES Studio(StudioID);
Check the exact syntax expected by the chosen DBMS; the constraint must link Booking.StudioID to Studio.StudioID.Answering clearly
Use the technical term, state what it does, and connect your explanation to the details in the question.