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 trial

Databases Creating and Modifying Database Tables Creating and Modifying Database Tables Making Changes to a Database

Adding foreign key not working

Hi,

I have been stuck in this challenge for some time now. They asked me to create a table and add a foreign key reference to the ID column in the table ROCKS.

I have the below statement, which I have tried in workspaces and works, but the challenge won't accept it.

CREATE TABLE MEMBERS (ID PRIMARY KEY, FIRST_NAME, LAST_NAME, FAVORITE_ROCK_ID, FOREIGN KEY(FAVORITE_ROCK_ID) REFERENCES ROCKS(ID));

The error I am getting is:

Bummer: Don't forget to add the foreign key constraint to the FAVORITE_ROCK_ID column.

Do you know how I can fix this?

Thanks!

Alejandro

2 Answers

Steven Parker
Steven Parker
231,184 Points

You'd only need the FOREIGN KEY statement when creating an association in an existing table.
When creating a new table, you can just name the column and what it refers to:

CREATE TABLE MEMBERS (ID PRIMARY KEY, FIRST_NAME, LAST_NAME, FAVORITE_ROCK_ID REFERENCES ROCKS(ID));

Thanks Steven, that is indeed the correct answer.

Just to note, when going into the sqlite documentation page (referred in the teacher notes), the first example on how to add a Foreign Key is:

CREATE TABLE track( trackid INTEGER, trackname TEXT, trackartist INTEGER, FOREIGN KEY(trackartist) REFERENCES artist(artistid) );

So I would image this method of adding a Foreign Key should be a valid answer.

Reading further though, they do mention the method you mentioned above.

Cheers,

Alejandro