Sub topic 16
Adding and Dropping Constraints on Existing Tables
Assume you know CREATE TABLE, INSERT, UPDATE, DELETE, column types, and NULL. This chapter shows how to change key constraints after tables already contain data. Examples use PostgreSQL syntax.
Why change a constraint?
A constraint is a database rule, such as “this value must be unique” or “this foreign key must reference an existing row.” You may add constraints when an existing table needs stronger protection. You may drop or replace one when the data model changes.
Before adding a constraint, check existing data. PostgreSQL rejects an ALTER TABLE statement if current rows violate the new rule.
SELECT customer_id, COUNT(*)
FROM customers
GROUP BY customer_id
HAVING COUNT(*) > 1;This query finds duplicate values that would prevent a unique constraint.
Add a named foreign key
Naming a constraint gives you a stable name for later changes. The following statement links existing orders to customers:
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id)
REFERENCES customers (customer_id);Every non-NULL orders.customer_id must now match a customers.customer_id. If orders already contains an invalid value, the statement fails and the constraint is not added.
You can also add a primary key or uniqueness rule:
ALTER TABLE customers
ADD CONSTRAINT uq_customers_email UNIQUE (email);The column must contain no duplicate non-NULL values. A primary key is stricter because it also disallows NULL.
| Change | Typical statement | Main requirement |
|---|---|---|
| Add a foreign key | `ADD CONSTRAINT ... FOREIGN KEY` | Every existing child value has a parent |
| Add uniqueness | `ADD CONSTRAINT ... UNIQUE` | Existing values are not duplicated |
| Add a primary key | `ADD CONSTRAINT ... PRIMARY KEY` | Values are unique and non-NULL |
Drop or replace a constraint
Use the constraint name when removing a rule:
ALTER TABLE orders
DROP CONSTRAINT fk_orders_customer;Dropping the foreign key does not delete rows. It only removes the database’s automatic enforcement, so application code could later create orphaned orders.
To change a foreign key’s delete behavior, drop the old constraint and add a new one:
ALTER TABLE orders
DROP CONSTRAINT fk_orders_customer;
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id)
REFERENCES customers (customer_id)
ON DELETE RESTRICT;RESTRICT prevents deleting a customer while orders reference that customer. CASCADE would delete those orders instead. Choose the action based on whether child rows are dependent records or valuable records that must remain.
Exercise
How do you replace a foreign key named fkorderscustomer with one that uses ON DELETE SET NULL?
Show answer
Drop fkorderscustomer, then add a foreign key with the same name and ON DELETE SET NULL. The column must allow NULL.