Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAlan Guevara
7,247 PointsWhy do we have to add a constraint when adding a FOREIGN KEY but not when adding a PRIMARY KEY?
When he adds the column with the RIMARY KEY he does this:
ALTER table t_movies ADD COLUMN pk_id INTEGER AUTO_INCREMENT PRIMARY KEY FIRST;
But when adding a column with a foreign key he does the following:
ALTER TABLE t_movies ADD COLUMN fk_genre_id INTEGER NULL, ADD CONSTRAINT FOREIGN KEY (fk_genre_id) REFERENCES t_genres(pk_id);
Which does not seem very consistant to me. Why couldnt we added the foreign key column without the ADD CONSTRAINT? something like this:
ALTER TABLE t_movies ADD COLUMN fk_genre_id INTEGER NULL FOREIGN KEY (fk_genre_id) REFERENCES t_genres(pk_id);
1 Answer
Iain Diamond
29,379 PointsA primary key is a unique key in a table which is used by the database to identify table entries. Each table needs a primary key, which is independent of other tables.
On the other hand, a foreign key describes a dependency between tables, i.e. it is used to form a connection between two tables. In SQL terminology, creating a foreign key requires adding a foreign key constraint which references another table.
JoJo KoKo
4,712 PointsJoJo KoKo
4,712 PointsForeign key constraint is placed to ensure that the data from one table matches the value in another table.
Primary key constraint is used for NOT NULL + UNIQUE.