Sub topic 11
When a change is rejected: constraint errors
This chapter assumes you can write basic INSERT, UPDATE, and DELETE statements and know what primary keys, foreign keys, NOT NULL, UNIQUE, and DEFAULT do. Here you learn to read the error when the database refuses a change, find the row or value responsible, and choose a fix. The examples use PostgreSQL error text, and the dialect differences are listed afterward.
What a rejection means
A constraint is a rule the database checks every time a statement changes data. If any row breaks a rule, the database raises an error and the whole statement has no effect. Nothing is half-applied.
Use this setup to follow along. It is the schema from earlier in the tutorial plus a few rows.
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE,
status VARCHAR(20) NOT NULL DEFAULT 'active'
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (id),
total NUMERIC(10, 2) NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'new'
);
INSERT INTO customers (id, name, email)
VALUES
(1, 'Ada Lovelace', '[email protected]'),
(2, 'Grace Hopper', '[email protected]'),
(3, 'Alan Turing', NULL);
INSERT INTO orders (id, customer_id, total)
VALUES (100, 1, 50.00);In SQLite, run PRAGMA foreign_keys = ON; first. Foreign key checking is off by default there, so the foreign key errors below will not appear without it.
The four common violations
| Constraint | Typical cause | PostgreSQL message (shortened) |
|---|---|---|
| NOT NULL | Omitting a column with no default, or setting it to NULL | `null value in column "name" ... violates not-null constraint` |
| PRIMARY KEY or UNIQUE | Inserting or updating to a value that already exists | `duplicate key value violates unique constraint "customers_email_key"` |
| FOREIGN KEY (child side) | Inserting or updating a child row whose parent does not exist | `insert or update on table "orders" violates foreign key constraint "orders_customer_id_fkey"` |
| FOREIGN KEY (parent side) | Deleting or re-keying a parent row that children still reference | `update or delete on table "customers" violates foreign key constraint ... on table "orders"` |
The message names the constraint, and often the table, column, and offending value. Read it before changing anything.
NOT NULL
INSERT INTO customers (id, email)
VALUES (4, '[email protected]');
-- ERROR: null value in column "name" of relation "customers" violates not-null constraintname has no default, so omitting it stores NULL, which the constraint forbids. status also has NOT NULL, but its default fills it in, so it never causes this error unless you explicitly insert NULL into it. The fix is to supply a value.
UNIQUE and PRIMARY KEY
INSERT INTO customers (id, name, email)
VALUES (4, 'Ada Duplicate', '[email protected]');
-- ERROR: duplicate key value violates unique constraint "customers_email_key"
-- DETAIL: Key (email)=([email protected]) already exists.Reusing id = 1 gives the same error against customers_pkey. The constraint name tells you which column or columns collided. To find the existing row, query for it:
SELECT id, name, email FROM customers WHERE email = '[email protected]';Then decide whether the new data is a mistake, an update to the existing row, or a case for an upsert (covered in a later chapter).
FOREIGN KEY on insert
INSERT INTO orders (id, customer_id, total)
VALUES (101, 999, 25.00);
-- ERROR: insert or update on table "orders" violates foreign key constraint "orders_customer_id_fkey"
-- DETAIL: Key (customer_id)=(999) is not present in table "customers".The same error appears when an UPDATE sets customer_id to a value with no matching parent. Check that the parent exists with SELECT id FROM customers WHERE id = 999;. Then either insert the parent first or correct the value.
FOREIGN KEY on delete
DELETE FROM customers WHERE id = 1;
-- ERROR: update or delete on table "customers" violates foreign key constraint
-- "orders_customer_id_fkey" on table "orders"Customer 1 still has order 100. An UPDATE customers SET id = 10 WHERE id = 1 fails the same way, because it would orphan the order. Your options are to delete or reassign the child rows first, or to define the foreign key with an action such as ON DELETE CASCADE. The next chapter covers those actions.
One bad row cancels the whole statement
A multi-row statement is all or nothing:
INSERT INTO customers (id, name, email)
VALUES
(4, 'Edsger Dijkstra', '[email protected]'),
(5, 'Duplicate Grace', '[email protected]');
-- ERROR: duplicate key value violates unique constraint "customers_email_key"
SELECT COUNT(*) FROM customers WHERE id IN (4, 5);
-- 0: the valid first row was not kept eitherThe same applies to UPDATE and DELETE. This update sets every email to one value, so the second matched row collides with the first. The statement fails and no email changes.
UPDATE customers SET email = '[email protected]';
-- ERROR: duplicate key value violates unique constraint "customers_email_key"That example also shows why a missing WHERE clause can show up as a constraint error. Here the constraint saved you. On a column without UNIQUE, the same statement would have succeeded and overwritten every row.
Errors inside a transaction
When a statement fails inside an explicit transaction, what happens to the transaction depends on the dialect.
- PostgreSQL marks the whole transaction as aborted. Every later statement fails with
current transaction is aborted, commands ignored until end of transaction blockuntil you runROLLBACK. ASAVEPOINTlets you roll back to a point before the failure and continue. - MySQL, SQLite, and SQL Server undo only the failed statement by default and leave the transaction open. You can continue and then
COMMIT, which keeps the earlier successful statements. SQL Server changes this whenSET XACT_ABORT ONis set, as the whole transaction is then rolled back.
BEGIN;
INSERT INTO customers (id, name, email)
VALUES (4, 'Edsger Dijkstra', '[email protected]');
INSERT INTO orders (id, customer_id, total)
VALUES (101, 999, 25.00); -- fails: no customer 999
ROLLBACK; -- safe in every dialect; undoes customer 4 as wellDo not rely on a transaction continuing after an error. Treat any error as a signal to inspect, then roll back or fix and retry.
Dialect differences in reporting
| Dialect | Duplicate key | NULL in NOT NULL column | Foreign key |
|---|---|---|---|
| PostgreSQL | SQLSTATE 23505 | 23502 | 23503 |
| MySQL | Error 1062 `Duplicate entry` | 1048 `cannot be null` | 1452 (child), 1451 (parent) |
| SQL Server | Error 2627 (constraint) or 2601 (index) | 515 | 547 |
| SQLite | `UNIQUE constraint failed: customers.email` | `NOT NULL constraint failed: customers.name` | `FOREIGN KEY constraint failed` |
Application code should test the error code or SQLSTATE, not the message text. SQLite's foreign key message names neither the constraint nor the value, so you have to work out the cause from the statement.
Edge cases
- NULLs in UNIQUE columns: PostgreSQL, MySQL, and SQLite allow many NULLs in a
UNIQUEcolumn, because NULL is not equal to NULL. SQL Server'sUNIQUEconstraint allows only one. - Case and whitespace:
'[email protected]'and'[email protected]'are different values in PostgreSQL, but MySQL's default collation treats them as equal and rejects the second. - Foreign key columns can be NULL if declared nullable. Here
orders.customer_idisNOT NULL, so every order needs a parent. - Failed inserts can still consume sequence or auto-increment values in some systems, so gaps in ids after errors are normal.
A diagnosis routine
- Read the constraint name and the DETAIL line. They identify the rule and often the value.
- Query the table involved for the conflicting row or missing parent.
- Decide whether the statement is wrong, the existing data is wrong, or the intended behavior is an update or skip (upsert).
- Change the statement, not the schema, and rerun inside a transaction.
Exercise
Using the setup data, the statement UPDATE customers SET id = 2 WHERE id = 3; fails. Which constraint is violated, and how would you confirm the cause with a query?
Show answer
It violates the primary key (customers_pkey), because customer 2 already has id 2. Confirm with SELECT * FROM customers WHERE id = 2;, which returns Grace Hopper. The statement changes nothing, so Alan Turing keeps id 3.
Exercise
A single statement inserts three customers, and only the third has a duplicate email. How many of the three rows exist afterward, and why?
Show answer
None. A statement is applied completely or not at all, so the error on the third row undoes the first two. Fix the third row and rerun the statement.