How would you add a foreign key constraint on the dept_no column in the EMP table, referring to the id column in the DEPT table?
Question
How would you add a foreign key constraint on the dept_no column in the EMP table, referring to the id column in the DEPT table?
Solution
To add a foreign key constraint on the dept_no column in the EMP table, referring to the id column in the DEPT table, you would use the ALTER TABLE statement in SQL. Here are the steps:
- First, ensure that the
DEPTtable has a primary key on theidcolumn. If it doesn't, you can add it using the following command:
ALTER TABLE DEPT
ADD PRIMARY KEY (id);
- Next, add the foreign key constraint to the
EMPtable. Thedept_nocolumn in theEMPtable will reference theidcolumn in theDEPTtable. Use the following command:
ALTER TABLE EMP
ADD FOREIGN KEY (dept_no) REFERENCES DEPT(id);
This command adds a foreign key constraint to the dept_no column in the EMP table, which references the id column in the DEPT table. If a row in the EMP table has a dept_no that does not exist in the DEPT table's id column, the database will return an error and reject the change.
Similar Questions
Which of the following is NOT a type of SQL constraint? UNIQUEPRIMARY KEYALTERNATE KEYFOREIGN KEY
.8 Identify the foreign keys in this schema. Explain how the entity and referential integrity rules apply to these relations.
Attributes of an entity become ________ in a table.1 pointrowscolumnsconstraintskeys
A ________ key establishes a relationship between tables by referencing the primary key of another tablea.Noneb.Foreign Keyc.Composite Keyd.Primary Key
After creating the tables, Angela needs to:Add a new foreign key constraint WorkoutID_FK on the Exercises table for WorkoutID to ensure proper referencing.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.