Sub topic 14
Changing constraints with ALTER TABLE
This chapter assumes you can write CREATE TABLE with the main constraint types (NOT NULL, PRIMARY KEY, UNIQUE, FOREIGN KEY, CHECK). It also assumes you know why constraints should have names. The examples use the customers and orders tables from earlier chapters and PostgreSQL syntax unless a note says otherwise.
Why constraints change after creation
Schemas change. A new business rule appears, a status value is added, or a column that used to be optional becomes required. You can't edit a constraint in place. You add a new one, drop an old one, or do both. ALTER TABLE is the statement for all three.
Changing a constraint on a table that already holds data carries a risk that CREATE TABLE does not: the existing rows may break the new rule. The database checks every current row when you add the constraint, and it refuses the change if any row fails.
Adding a constraint
The general form is ALTER TABLE table_name ADD CONSTRAINT constraint_name definition. The definition is the same text you would write at table level in CREATE TABLE.
ALTER TABLE customers ADD COLUMN phone VARCHAR(30);
ALTER TABLE customers
ADD CONSTRAINT uq_customers_phone UNIQUE (phone);
ALTER TABLE orders
ADD CONSTRAINT ck_orders_total_limit CHECK (total_amount <= 1000000);A foreign key and a primary key are added the same way:
ALTER TABLE order_items
ADD CONSTRAINT fk_items_product
FOREIGN KEY (product_id) REFERENCES products (product_id)
ON DELETE RESTRICT;Always supply the name. If you omit it, the database invents one such as orders_total_amount_check. You then have to look that name up before you can drop the constraint.
A table can have only one primary key. Adding a second one fails unless you drop the first.
What happens to existing rows
When you add a constraint, the database validates all current rows:
- CHECK: every row is evaluated against the expression.
- UNIQUE and PRIMARY KEY: the database builds a supporting index, and duplicates make the build fail. A primary key also requires that no value is NULL.
- FOREIGN KEY: every non-NULL value in the child column must match a row in the parent table.
If one row fails, the whole statement fails and the table stays unchanged. The error names the constraint and often a sample row. That is another reason to name constraints.
Find the offending rows before you add the constraint:
-- Duplicate phone numbers that would break uq_customers_phone
SELECT phone, COUNT(*) AS copies
FROM customers
WHERE phone IS NOT NULL
GROUP BY phone
HAVING COUNT(*) > 1;
-- Orders that would break ck_orders_total_limit
SELECT order_id, total_amount
FROM orders
WHERE total_amount > 1000000;
-- Orders that would break a foreign key to customers
SELECT o.order_id, o.customer_id
FROM orders o
LEFT JOIN customers c ON c.customer_id = o.customer_id
WHERE c.customer_id IS NULL;Fix the data first, by correcting the rows, merging duplicates, or deleting orphans. Then add the constraint.
A safe workflow
Adding a rule without checking old rows (PostgreSQL)
On a large live table, a full validation can hold a heavy lock for a long time. PostgreSQL lets you split the work. NOT VALID skips the check of existing rows but enforces the rule on every new or changed row. VALIDATE CONSTRAINT checks the old rows later, with a lighter lock.
ALTER TABLE orders
ADD CONSTRAINT ck_orders_total_limit
CHECK (total_amount <= 1000000) NOT VALID;
-- After cleaning up any old rows:
ALTER TABLE orders VALIDATE CONSTRAINT ck_orders_total_limit;NOT VALID works for CHECK and FOREIGN KEY constraints in PostgreSQL. MySQL and SQL Server have their own options for the same goal. SQL Server uses WITH NOCHECK, but it marks the constraint as untrusted, and the optimizer then ignores it.
Dropping a constraint
Use the name:
ALTER TABLE orders DROP CONSTRAINT ck_orders_total_limit;Dropping is quick and doesn't inspect rows. Two things can go wrong:
- Dependencies. You can't drop a primary key or unique constraint that a foreign key references. PostgreSQL reports the dependent constraint. Drop the foreign key first, or use
DROP CONSTRAINT ... CASCADE, which also removes the dependent foreign key. Make sure you want that. - Lost protection. Once the constraint is gone, bad data can enter. Anything that went in during the gap stays there, and re-adding the constraint later will fail on those rows.
The DROP syntax differs between systems:
| Constraint | PostgreSQL | MySQL 8 | SQL Server |
|---|---|---|---|
| CHECK, PRIMARY KEY, UNIQUE | `DROP CONSTRAINT name` | CHECK: `DROP CHECK name`. UNIQUE: `DROP INDEX name`. PRIMARY KEY: `DROP PRIMARY KEY`. | `DROP CONSTRAINT name` |
| FOREIGN KEY | `DROP CONSTRAINT name` | `DROP FOREIGN KEY name` | `DROP CONSTRAINT name` |
MySQL 8.0.19 and later also accept DROP CONSTRAINT name for the types above. Older versions do not, and MySQL before 8.0.16 parses CHECK constraints but does not enforce them.
Replacing a constraint
To change a rule, drop the old constraint and add a new one. Suppose the business adds a 'refunded' status. In PostgreSQL you can do both in one statement, so no row can sneak in between the two steps:
ALTER TABLE orders
DROP CONSTRAINT ck_orders_status,
ADD CONSTRAINT ck_orders_status
CHECK (status IN ('new', 'paid', 'shipped', 'cancelled', 'refunded'));PostgreSQL also runs DDL inside transactions, so you can wrap separate statements in BEGIN and COMMIT and roll back on a failure. MySQL commits DDL statements immediately and has no such safety net.
NOT NULL and DEFAULT are changed differently
NOT NULL and DEFAULT belong to the column definition, so most systems alter them with column commands rather than ADD CONSTRAINT:
-- PostgreSQL
ALTER TABLE customers ALTER COLUMN phone SET NOT NULL;
ALTER TABLE customers ALTER COLUMN phone DROP NOT NULL;
ALTER TABLE orders ALTER COLUMN status SET DEFAULT 'new';
ALTER TABLE orders ALTER COLUMN status DROP DEFAULT;Setting NOT NULL fails if any row has a NULL in that column. Backfill first:
UPDATE customers SET phone = 'unknown' WHERE phone IS NULL;
ALTER TABLE customers ALTER COLUMN phone SET NOT NULL;The same operations in other systems:
- MySQL: restate the whole column, for example
ALTER TABLE customers MODIFY phone VARCHAR(30) NOT NULL;. If you leave out part of the definition, such as a default, that part is lost. - SQL Server:
ALTER TABLE customers ALTER COLUMN phone VARCHAR(30) NOT NULL;. Defaults are named constraints, added withADD CONSTRAINT df_orders_status DEFAULT 'new' FOR status.
A new DEFAULT affects only rows inserted afterward. It does not change rows that already exist.
Common errors
- Dropping by a guessed name. The error
constraint "..." does not existusually means the constraint was unnamed and got a generated name. List the real names with\d ordersinpsql, or queryinformation_schema.table_constraints. - Adding a duplicate rule. Adding
uq_customers_emailto a column that already has an unnamedUNIQUEcreates a second unique constraint and a second index. Both do the same job, and you pay for both on every write. - Long locks. Validating a big table blocks writes on it in many systems. Plan the change for a quiet period, or use
NOT VALID. - Assuming the change reached all environments. Keep these statements in versioned migration scripts, not typed by hand in one database.
Exercise
The orders table has 2 million rows, and some rows have a customer_id that no longer exists in customers. You run ALTER TABLE orders ADD CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers (customer_id);. What happens, how do you find the cause, and what are two ways to proceed in PostgreSQL?
Show answer
The statement fails and the table is unchanged, because every existing row is validated and the orphaned rows violate the key. Find them with a LEFT JOIN from orders to customers where the customer side is NULL. Then either fix the data (reassign or delete the orphans) and re-run the statement, or add the constraint with NOT VALID so that new rows are checked immediately, clean up the old rows, and run ALTER TABLE orders VALIDATE CONSTRAINT fk_orders_customer;.
Exercise
Write the PostgreSQL statement that adds 'returned' to the allowed values of the status check constraint ck_orders_status, without a moment where the rule is missing.
Show answer
ALTER TABLE orders DROP CONSTRAINT ckordersstatus, ADD CONSTRAINT ckordersstatus CHECK (status IN ('new', 'paid', 'shipped', 'cancelled', 'returned')); Both actions run in one statement, so no row can be inserted between the drop and the add.