Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

SQL Foreign Key Command: How to Use It

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

A foreign key is created with a FOREIGN KEY constraint inside a CREATE TABLE or ALTER TABLE statement. The shortest working example is: CREATE TABLE orders (id INT PRIMARY KEY, customer_id INT, FOREIGN KEY (customer_id) REFERENCES customers(id));. That single line tells the database that every customer_id in orders must already exist in customers.id. The sections below walk through the full command, the options that control what happens on delete or update, and the errors you are most likely to hit.

What You'll Need

  • A relational database that supports foreign keys: MySQL or MariaDB with the InnoDB engine, PostgreSQL, SQL Server, Oracle, or SQLite (with PRAGMA foreign_keys = ON;).
  • Two tables: a parent table with a primary key or unique constraint, and a child table that will hold the reference.
  • Permission to create or alter tables in the database.
  • Matching data types between the child column and the parent key column (for example, both INT or both BIGINT).

Step-by-Step

  1. Create the parent table first. The referenced table must exist before you can point a foreign key at it. For example: CREATE TABLE customers (id INT PRIMARY KEY, name VARCHAR(100) NOT NULL);. The referenced column must be a primary key or have a unique index.
  2. Create the child table with the foreign key inline. Add the constraint in the same CREATE TABLE statement: CREATE TABLE orders (id INT PRIMARY KEY, customer_id INT NOT NULL, order_date DATE, FOREIGN KEY (customer_id) REFERENCES customers(id));. This is the most common form and works in MySQL, PostgreSQL, SQL Server, and Oracle.
  3. Or add the foreign key to an existing table. Use ALTER TABLE: ALTER TABLE orders ADD CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers(id);. Naming the constraint (fk_orders_customer) makes it easier to drop or debug later. Without a name, the database generates one that can be hard to find.
  4. Choose what happens on delete and update. Append an action after the REFERENCES clause. ON DELETE CASCADE deletes child rows when the parent is deleted; ON DELETE SET NULL sets the child column to NULL (the column must allow NULL); ON DELETE RESTRICT or NO ACTION blocks the parent delete if child rows exist. The same options apply to ON UPDATE. Example: FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE ON UPDATE CASCADE.
  5. Verify the constraint exists. In MySQL, run SHOW CREATE TABLE orders; and look for the CONSTRAINT line. In PostgreSQL, use \d orders in psql or query information_schema.table_constraints. In SQL Server, use sp_help 'orders' or check sys.foreign_keys. In SQLite, run PRAGMA foreign_key_list(orders);.
  6. Test the rule. Insert a child row that references a missing parent: INSERT INTO orders (id, customer_id) VALUES (1, 999);. The database should reject it with a foreign key violation error. Then insert a valid parent and retry the child insert; it should succeed.
  7. Drop the foreign key when you need to change it. In MySQL: ALTER TABLE orders DROP FOREIGN KEY fk_orders_customer;. In PostgreSQL: ALTER TABLE orders DROP CONSTRAINT fk_orders_customer;. In SQL Server: ALTER TABLE orders DROP CONSTRAINT fk_orders_customer;. SQLite does not support dropping a constraint directly; you must recreate the table.

Common Mistakes

  • Type mismatch. A child column declared INT referencing a parent BIGINT will fail on some databases or silently behave oddly on others. Keep the types identical.
  • Referencing a non-unique column. The parent column must be a primary key or have a unique index. Referencing a plain column returns an error such as "there is no unique constraint matching given keys".
  • Forgetting the constraint name. Unnamed constraints get generated names that differ by database, which makes later DROP statements guesswork. Always name them.
  • Using ON DELETE CASCADE by accident. Cascading deletes can wipe large amounts of child data. Use RESTRICT or NO ACTION unless you are certain you want the cascade.
  • SQLite foreign keys off by default. SQLite does not enforce foreign keys unless you run PRAGMA foreign_keys = ON; in each connection. The constraint can exist and still be ignored.
  • Inserting child rows before parent rows. The parent must exist first. Load parent data before child data in bulk imports, or disable checks temporarily and re-enable them after loading.

Tips

  • Index the child column. Most databases do not create an index on the foreign key column automatically, and joins and cascades will be slow without one. Add CREATE INDEX idx_orders_customer ON orders(customer_id);.
  • Use consistent naming such as fk_child_parent so constraints are easy to find in error messages and schema dumps.
  • Prefer ON UPDATE CASCADE only when the parent key can actually change; with surrogate integer keys it rarely does, and the extra rule adds complexity.
  • When copying a schema, check that the dump includes foreign keys. Some export tools omit constraints unless you enable them.
  • In MySQL, confirm the table engine is InnoDB. MyISAM parses foreign key syntax but does not enforce it.

Troubleshooting

Error: cannot add or update a child row. The value you are inserting does not exist in the parent table. Insert the parent row first, or correct the value. Check for trailing spaces or case differences in string keys.

Error: cannot delete or update a parent row. Child rows still reference the parent. Delete or reassign the children first, or change the constraint to ON DELETE CASCADE if that is the intended behavior.

Error: foreign key constraint is incorrectly formed (MySQL). The column types, signedness, or character sets do not match between parent and child. Compare SHOW CREATE TABLE output for both tables.

Constraint seems ignored. In SQLite, enable PRAGMA foreign_keys = ON;. In MySQL, check the storage engine. In some tools, a failed ALTER TABLE leaves the table unchanged; re-run and read the full error.

Bulk load fails. Load parents before children, or wrap the load in a transaction and disable checks where the database allows it (for example SET FOREIGN_KEY_CHECKS = 0; in MySQL), then re-enable and validate the data before committing.

Frequently Asked Questions

Can a table have more than one foreign key?

Yes. A child table can reference several parent tables, each with its own FOREIGN KEY clause.

Does a foreign key automatically create an index?

Not in MySQL or PostgreSQL. SQL Server does not create one either. Add an index on the child column yourself for performance.

Can a foreign key reference a column that is not the primary key?

Yes, as long as that column has a unique constraint or unique index.

What is the difference between RESTRICT and NO ACTION?

They behave the same in most databases for immediate constraints. NO ACTION can be deferred in databases that support deferred constraints; RESTRICT is checked immediately.

Can I disable foreign key checks temporarily?

MySQL allows SET FOREIGN_KEY_CHECKS = 0; per session. PostgreSQL and SQL Server require dropping or disabling the constraint, which needs table ownership or elevated rights. Re-enable checks and validate data afterward.

Do foreign keys work across databases?

No. A foreign key references a table in the same database. Cross-database referential integrity must be enforced in application code.