r/SQL • • 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

5 comments sorted by

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_basket already has a constraint called something like FK_user_id or fk_user and you give tbl_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:

SELECT CONSTRAINT_NAME, TABLE_NAME
FROM information_schema.REFERENTIAL_CONSTRAINTS
WHERE CONSTRAINT_SCHEMA = DATABASE();

Then give the new one a unique name:

ALTER TABLE tbl_order
  ADD CONSTRAINT fk_order_user
  FOREIGN KEY (user_id) REFERENCES tbl_user (user_id);

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_id must have exactly the same type as tbl_user.user_id, including signed/unsigned (INT vs INT UNSIGNED is a common one).
  • Both tables must be InnoDB.
  • Any existing user_id values in tbl_order must already exist in tbl_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?