I wanted to ALTER an existing table and add a new column with a foreign key constraint .
I looked at Chat GPT and also some youtube videos which showed the same syntax so I used the follwoing SQL
ALTER TABLE comments ADD COLUMN Userid INT NOT NULL;
ALTER TABLE comments ADD CONSTRAINT adding_fk FOREIGN KEY(Userid) REFERENCES Users(ID);An error message is being shown when altering a table to add a column with foreign key
#1452 – Cannot add or update a child row: a foreign key constraint fails (facebook
.#sql-2c80_8ad
, CONSTRAINT adding_fk
FOREIGN KEY (Userid
) REFERENCES users
(ID
)).
Why isn’t it working?
New contributor