Sub topic 12
CASCADE and RESTRICT
This chapter assumes you can write CREATE TABLE with primary and foreign keys, and that you have met DROP TABLE and IF EXISTS in earlier chapters. The examples use PostgreSQL, because it implements both keywords fully. The dialect section shows how other systems differ.
What the two keywords decide
A table is rarely alone. Foreign keys in other tables point to it, and views select from it. DROP TABLE has to decide what happens to those dependent objects. Two keywords answer that:
RESTRICTrefuses to drop the table if anything depends on it.CASCADEdrops the table and also drops the dependent objects.
In PostgreSQL, RESTRICT is the default. DROP TABLE customers and DROP TABLE customers RESTRICT behave identically. The standard behavior is therefore the safe one, and you have to ask explicitly for the destructive one.
A worked setup
The following script creates a parent table, a child table with a named foreign key, and a view.
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (id)
);
CREATE VIEW customer_names AS
SELECT id, name FROM customers;
INSERT INTO customers (id, name) VALUES (1, 'Ada');
INSERT INTO orders (id, customer_id) VALUES (10, 1);Two objects now depend on customers: the constraint fk_orders_customer and the view customer_names.
RESTRICT in action
DROP TABLE customers;PostgreSQL rejects this statement with an error like the one below. The table, the constraint, the view and all data are unchanged.
ERROR: cannot drop table customers because other objects depend on it
DETAIL: constraint fk_orders_customer on table orders depends on table customers
view customer_names depends on table customers
HINT: Use DROP ... CASCADE to drop the dependent objects too.The error message is useful. It lists every dependent object, so a failed RESTRICT drop works as a dependency report.
CASCADE in action
DROP TABLE customers CASCADE;This succeeds. PostgreSQL drops customers, the constraint fk_orders_customer and the view customer_names. It reports this with a notice such as drop cascades to 2 other objects.
CASCADE removes the dependent objects, not the tables that contain them. After the statement:
- The
orderstable still exists, and the row with id 10 is still there. - The foreign key is gone, so
orders.customer_idis now an ordinary integer column. The value 1 no longer refers to anything, and nothing prevents bad values from being inserted later. - The view is gone, and any application query that used
customer_namesnow fails.
The dangerous part is that the damage is quiet. The database enforces nothing about the relationship anymore, and no error tells you so.
Previewing a cascade safely
Do not run CASCADE to find out what it removes. Use one of these two methods instead.
First, list the foreign keys that point at the table:
SELECT conrelid::regclass AS referencing_table,
conname AS constraint_name
FROM pg_constraint
WHERE contype = 'f'
AND confrelid = 'customers'::regclass;Second, because PostgreSQL supports transactional DDL, run the cascade inside a transaction and roll it back. The notice tells you what would have been dropped.
BEGIN;
DROP TABLE customers CASCADE;
ROLLBACK;After the ROLLBACK, every object is back. This trick works only in databases whose DDL is transactional. MySQL commits DDL implicitly, so the same pattern there would not undo anything.
Combining with IF EXISTS
The two clauses can be used together. The order is IF EXISTS before the table name, and the behavior keyword at the end.
DROP TABLE IF EXISTS customers RESTRICT;
DROP TABLE IF EXISTS customers CASCADE;IF EXISTS only suppresses the error for a missing table. It does not suppress the error for a blocked RESTRICT drop. A re-runnable script that uses RESTRICT can therefore still fail on the second run if a new dependent object has appeared.
Do not confuse this with ON DELETE CASCADE
ON DELETE CASCADE is a different feature. It belongs to a foreign key definition and controls what happens to child rows when a parent row is deleted.
| Feature | Acts on | Triggered by | Effect |
|---|---|---|---|
| `DROP TABLE ... CASCADE` | Schema objects | Dropping a table | Drops dependent constraints and views |
| `ON DELETE CASCADE` | Rows | Deleting a parent row | Deletes the matching child rows |
Neither one implies the other. A foreign key declared with ON DELETE CASCADE still blocks a plain DROP TABLE on the parent. And DROP TABLE ... CASCADE never deletes rows from the child table.
CASCADE elsewhere in ALTER TABLE
PostgreSQL accepts the same keywords in other schema changes. DROP COLUMN and DROP CONSTRAINT both take CASCADE or RESTRICT.
ALTER TABLE customers DROP COLUMN name RESTRICT;
ALTER TABLE customers DROP COLUMN name CASCADE;The first form fails here because the view customer_names uses the column. The second form drops that view. The same reasoning applies: read the dependency list first.
Dialect differences
The keywords are part of the SQL standard, but systems implement them unevenly. Check the target database before you run a script.
| Database | Behavior of DROP TABLE with dependents |
|---|---|
| PostgreSQL | `RESTRICT` by default. `CASCADE` drops foreign keys and views that depend on the table. |
| MySQL | The keywords are parsed but ignored. A table referenced by a foreign key cannot be dropped. Drop the foreign key or the child table first. |
| SQL Server | No `CASCADE` option. Dropping a table referenced by a foreign key fails. Views are not dropped and become invalid, and they fail when queried. |
| Oracle | `CASCADE CONSTRAINTS` drops the foreign keys that reference the table. Views are kept and marked invalid. |
| SQLite | No `CASCADE` option. With foreign key enforcement on, dropping a parent table performs an implicit delete of its rows first, which can fail or cascade according to the constraint actions. Views are kept. |
Two consequences follow. A script written for PostgreSQL that relies on CASCADE will not run unchanged on SQL Server. And MySQL silently accepting CASCADE can give a false sense that dependents were handled, when the keyword had no effect.
Decision criteria
Use RESTRICT, which is usually just the default, when you do not yet know the dependencies. It turns a surprise into an error.
Use CASCADE only when you have read the dependency list and accept every item on it. Good cases are tearing down a throwaway test schema, or replacing a table and its dependent views in one migration where you recreate the views right afterward.
In production migrations, prefer explicit statements: drop the foreign key by name, drop or recreate the view, and then drop the table. The script is longer. Every removal is visible in code review, and the same script works on databases that have no CASCADE.
Exercise
Using the setup from this chapter, you run DROP TABLE customers CASCADE in PostgreSQL. State what happens to the orders table, its rows, and the foreign key on orders.customer_id. Then name one risk this leaves behind.
Show answer
The orders table and its rows stay. The foreign key fkorderscustomer is dropped, together with the view customernames. orders.customerid becomes an unconstrained integer column. The risk is orphaned data: values such as 1 now point to a customer that no longer exists, and the database will not stop you from inserting other invalid customer ids.
Exercise
A teammate's migration contains DROP TABLE IF EXISTS customers CASCADE; and it must run on both PostgreSQL and SQL Server. Explain why it is a problem for SQL Server, and describe a portable way to write the change.
Show answer
SQL Server has no CASCADE option for DROP TABLE, so the statement is a syntax error. It also fails if a foreign key still references the table. A portable approach is to drop each dependent object explicitly and in order: ALTER TABLE orders DROP CONSTRAINT fkorderscustomer; then drop or recreate any views, then DROP TABLE customers. Use IF EXISTS only where the target database supports it for the object type.