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

Development Tools

Adding a constraint foreign key to existing column

Hello,

I've been playing around with what I have learned in the database foundations. In the video, we are showed how to add a constraint with foreign key referencing another table when adding a new column.

ALTER TABLE table_name ADD COLUMN column_name INTEGER, ADD CONSTRAINT FOREIGN KEY (column_name) REFERENCES table_name(column_name);

What if the column already exists and there are several thousand of results in it?

I have tried a few things, example:

Used these 3 beginnings: ALTER TABLE table_name1 MODIFY COLUMN column_name1 ALTER TABLE table_name1 ALTER COLUMN column_name1

Followed it with: BIGINT(20) NOT NULL, ADD CONSTRAINT FOREIGN KEY (column_name1) REFERENCES table_name2(column_name2);

BIGINT(20), ADD CONSTRAINT FOREIGN KEY (column_name1) REFERENCES table_name2(column_name2);

ADD CONSTRAINT FOREIGN KEY (column_name1) REFERENCES table_name2(column_name2);

Nothing seems to work. The latest test I did was : ALTER TABLE xtable ADD CONSTRAINT FOREIGN KEY (xcolumn) REFERENCES ytable(ycolumn);

I get this error:

1452 - Cannot add or update a child row: a foreign key constraint fails (dbname.#sql-62d4_390709, CONSTRAINT #sql-62d4_390709_ibfk_1 FOREIGN KEY (xcolumn) REFERENCES ytable (ycolumn))

Can anyone enlighten me on what I'm doing wrong?

thanks