r/SQL • u/TGonReddit03 • May 06 '26
MySQL Help with HeidiSQL foreign keys
So I’m making an e-commerce site for school and I have a table named tbl_user with a primary key of “user_id”
This appears as a foreign key in tbl_basket but when I go to make the foreign key in tbl_order it says “SQL Error (1022) can’t write, duplicate key in table something”
Any help would be greatly appreciated
0
Upvotes
2
u/kiltannen May 06 '26
Maybe it's identifying you have a duplicate value inn the field you are trying to make a foreign key?
This would cause an error
1
u/navicat-gu 28d ago
Error 1022 when adding a foreign key is almost always a duplicate constraint name, not duplicate data. In MySQL/MariaDB (InnoDB), foreign key names must be unique across the whole database, not just within one table. If
tbl_basketalready has a constraint called something likeFK_user_idorfk_userand you givetbl_order's new key the same name, you get "Can't write; duplicate key in table". HeidiSQL's default names can collide this way too.To check, run:
Then give the new one a unique name:
In HeidiSQL, you can rename the key on the table's "Foreign keys" tab before saving. A naming pattern like
fk_<table>_<referenced table>avoids this for good.If you get a different error after that, check these:
tbl_order.user_idmust have exactly the same type astbl_user.user_id, including signed/unsigned (INT vs INT UNSIGNED is a common one).user_idvalues intbl_ordermust already exist intbl_user(error 1452 otherwise).Disclosure: I'm RC, Director of Digital Strategy @ Navicat. The fix above works in any client. If you try other GUIs for your project, Navicat 18 has a visual table designer that shows FKs clearly, and Navicat Premium Lite is free to try.
1
u/G_Thorne May 06 '26
How are you defining your FK constraint in tbl_basket? FOREIGN KEY (user_id) REFERENCES tbl_user (user_id)...? Same type on the columns?