Short answer
To add a foreign key in SQL, declare that a column in the child table must match a primary key or unique key in the parent table. PostgreSQL lets you write that with REFERENCES inside CREATE TABLE, or with ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY. MySQL uses FOREIGN KEY ... REFERENCES on InnoDB or NDB tables, including an ALTER TABLE form. The row is rejected when the parent value is missing.
Last verified against the sources listed below.
Key takeaways
- PostgreSQL's default ON DELETE action is NO ACTION. RESTRICT, CASCADE, SET NULL, and SET DEFAULT are the other actions on that page.
- MySQL's parser accepts SET DEFAULT, and both InnoDB and NDB reject a table that uses it.
- For InnoDB, NO ACTION and RESTRICT both reject the parent delete or update immediately.
- SQLite parses foreign keys and leaves enforcement off until you run PRAGMA foreign_keys = ON for that connection.
- PostgreSQL does not auto-index the referencing columns. MySQL creates an index on them if one is missing.
How to add foreign key in sql means telling the database that a value in one table must already exist in another. The same job is described as how to create foreign key in sql and how to make foreign key in sql. PostgreSQL calls this referential integrity. The orders table is the referencing table, and the products table is the referenced table.
A relational database stores those rows in tables. The foreign key is the rule that keeps an order from pointing at a product you already deleted.
Back end development is where the application sends the INSERT that this rule will accept or reject.
What do you need before the statement?
You need a parent key the database can look up, and a child column of a compatible type.
In PostgreSQL the referenced columns must be a primary key, a unique constraint, or columns from a non-partial unique index. If you omit the column list, the primary key is used. In MySQL 8.4 the parent and child must use the same storage engine. InnoDB and NDB enforce the check.
A snake_case converter is a reasonable place to turn a label such as “Product No” into product_no before you type it.
What you need on the desk:
- A parent table whose referenced columns are unique.
- A child column whose type matches those columns.
- A decision about what happens on delete: block it, cascade it, or clear the child value.
- A name for the constraint if you want to drop it later without guessing.
How do you add one in CREATE TABLE?
Put REFERENCES on the child column, or write FOREIGN KEY as a table constraint.
This PostgreSQL example is the products and orders pair from the constraints chapter. orders.product_no may be inserted only when that number already exists in products, unless the value is NULL.
CREATE TABLE products (
product_no integer PRIMARY KEY,
name text,
price numeric
);
CREATE TABLE orders (
order_id integer PRIMARY KEY,
product_no integer REFERENCES products (product_no),
quantity integer
);
You can shorten REFERENCES products (product_no) to REFERENCES products because the primary key is the default target. A group of columns has to be a table constraint. PostgreSQL’s form is FOREIGN KEY (b, c) REFERENCES other_table (c1, c2). The number of columns and their types must match.
MySQL’s manual uses a parent table and a child table, and it names the engine:
CREATE TABLE parent (
id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (
id INT,
parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE
) ENGINE=INNODB;
MySQL also accepts a leading constraint name: CONSTRAINT symbol, then FOREIGN KEY and REFERENCES. If you skip the symbol, the server generates one. That symbol has to be unique in the database.
A duplicate produces an error such as ERROR 1005 with errno 121.
How do you add one with ALTER TABLE?
Add the constraint to the table that already holds the child rows.
PostgreSQL’s ALTER TABLE page shows this form. The names are the manual’s example, not a new dialect:
ALTER TABLE distributors
ADD CONSTRAINT distfk
FOREIGN KEY (address) REFERENCES addresses (address);
MySQL’s form from the 8.4 reference is:
ALTER TABLE tbl_name
ADD CONSTRAINT fk_parent
FOREIGN KEY (parent_id) REFERENCES parent (id);
The MySQL page says to create an index on the referenced columns first when you add the key with ALTER TABLE. The foreign key may refer to the same table. Drop it with ALTER TABLE and DROP FOREIGN KEY plus the symbol.
If you never chose a name, read it from SHOW CREATE TABLE. The generated example on that page is child_ibfk_1.
PostgreSQL can add the constraint as NOT VALID, then run VALIDATE CONSTRAINT, so existing rows are checked after the command commits. New writes are checked immediately either way.
Which ON DELETE action should you pick?
Pick the action that matches whether the child row can exist without the parent.
PostgreSQL’s default is ON DELETE NO ACTION. The delete is attempted, and the constraint still has to be true, so you usually get an error. If the check is deferred, later commands in the transaction can fix the rows before the check runs.
RESTRICT does not allow that deferral. CASCADE deletes the referencing rows. SET NULL and SET DEFAULT write nulls or defaults into the child, and those values still have to satisfy every other constraint.
| Action | PostgreSQL, as documented | MySQL InnoDB, as documented |
|---|---|---|
| NO ACTION | Default. Check can be deferred | Default. Same as RESTRICT, checked immediately |
| RESTRICT | Blocks the delete, and cannot be deferred | Rejects the parent change. Same as omitting the clause |
| CASCADE | Deletes referencing rows | Deletes or updates matching child rows |
| SET NULL | Sets the child columns to null | Sets the child columns to NULL. Columns must allow NULL |
| SET DEFAULT | Sets the child columns to their defaults | Parser accepts it. InnoDB and NDB reject the table |
PostgreSQL also has ON UPDATE with the same action list. For an update, CASCADE copies the new parent values into the child rows. MySQL supports ON UPDATE CASCADE and ON UPDATE SET NULL as well.
ON DELETE CASCADE in MySQL does not activate triggers. SQL Server’s list, from Microsoft’s documentation, is NO ACTION, CASCADE, SET NULL, and SET DEFAULT.
SQLite accepts the same five names and defaults to NO ACTION. Enforcement is off until the connection runs PRAGMA foreign_keys = ON. A library built without foreign key support will not enforce the clause even after that pragma.
A worked delete: an order_items row that references orders with ON DELETE CASCADE disappears when that order is deleted. The same row referencing products with ON DELETE RESTRICT stops you from deleting a product that an item still names. PostgreSQL’s chapter uses that pair because an item is part of an order, and a product is a separate thing.
What fails when the rows do not match?
The insert fails when the parent row is missing, and the delete fails when a child row still points at it.
| Symptom | Likely cause | What to check |
|---|---|---|
| INSERT into the child is rejected | No parent row has that key, and the child value is not NULL | Insert the parent first, or use a key that exists |
| DELETE on the parent is rejected | ON DELETE is NO ACTION or RESTRICT, and a child still matches | Delete or reassign the child rows, or choose CASCADE |
| SET NULL fails | The child column is NOT NULL, or another constraint rejects null | Allow NULL only if the relationship is optional |
| MySQL reports Error 150 | The latest InnoDB foreign key error has more detail | Read SHOW ENGINE INNODB STATUS |
| SQLite accepts an orphan row | Foreign keys are off for this connection | Run PRAGMA foreign_keys = ON, then retry |
| ALTER TABLE in PostgreSQL locks writers for a long time | The new key is validating every existing row | Add it NOT VALID, then VALIDATE CONSTRAINT |
NULL is the other escape. In PostgreSQL and in SQLite’s documented example, a NULL referencing column does not have to match a parent row. Declare the column NOT NULL when every child row must point at a real parent.
MATCH FULL in PostgreSQL changes a multi-column key so a mix of null and non-null values fails. All null, or all filled in, is what remains.
Name the constraint, index the child columns when the manual says the engine will not, and test one delete before you load production data.
Frequently asked questions
Does PostgreSQL index the child column for you?
PostgreSQL says a foreign key must reference a primary key, a unique constraint, or columns of a non-partial unique index, so the parent side already has an index. It does not create an index on the referencing columns, because that index is not always wanted. Add one yourself when child lookups are common. MySQL requires an index on the child with the foreign key columns first, and it creates that index when one is missing. The two manuals make the opposite default for the child side.
Why does MySQL reject ON DELETE SET DEFAULT?
The MySQL 8.4 foreign-key page says the parser recognizes SET DEFAULT, and that both InnoDB and NDB reject tables that contain ON DELETE SET DEFAULT or ON UPDATE SET DEFAULT. PostgreSQL does implement SET DEFAULT. It writes the column defaults into the child, and the statement still fails if that default would break the foreign key. For both engines, pick RESTRICT, CASCADE, or SET NULL. Confirm the child column allows NULL before you choose SET NULL.
What does NOT VALID change in PostgreSQL?
ALTER TABLE can add a foreign key with NOT VALID. PostgreSQL then skips the scan of existing rows and can commit immediately. The lock for ADD FOREIGN KEY is SHARE ROW EXCLUSIVE, including a lock on the referenced table. Follow it with VALIDATE CONSTRAINT, which checks rows already stored under SHARE UPDATE EXCLUSIVE, plus a ROW SHARE lock on the parent. New writes are checked the whole time. NOT VALID is a PostgreSQL extension. The SQL-standard form of ADD table_constraint omits it.
How many tables can a SQL Server foreign key point at?
Microsoft's SQL Server documentation says a table can reference at most 253 other tables and columns as outgoing foreign keys. SQL Server 2016 and later raises incoming references from 253 to 10,000 when compatibility level is at least 130. Above 253, only DELETE is supported. UPDATE and MERGE are not, and a self-reference stays capped at 253. Creating the foreign key still does not create an index on those columns. The cascading actions on that page are NO ACTION, CASCADE, SET NULL, and SET DEFAULT.
What privilege does MySQL require on the parent table?
Creating the constraint requires the REFERENCES privilege on the parent table. Parent and child must use the same storage engine, and neither table can be temporary. The size and sign of integer and decimal columns must match. String columns need the same character set and collation, while the length may differ. InnoDB does not support foreign keys on tables that use user-defined partitioning, for either the parent or the child. A foreign key also cannot reference a virtual generated column. Those checks fail before ON DELETE behavior matters.
Sources
- Constraints · PostgreSQL, 2026
- ALTER TABLE · PostgreSQL, 2026
- FOREIGN KEY Constraints · MySQL, 2026
- SQLite Foreign Key Support · SQLite, 2026
- Primary and foreign key constraints · Microsoft Learn, 2026