Sub topic 11
What depends on a table
This chapter assumes you can write CREATE TABLE, define primary and foreign keys, and have run ALTER TABLE and DROP TABLE on a test database. The examples use PostgreSQL. Where MySQL, SQL Server or SQLite behave differently, the text says so.
Why dependencies matter
A table is rarely used alone. Other database objects are built on top of it and refer to it by name or by column. If you drop or change the table, those objects lose what they rely on. Each database system decides what to do about that: refuse the change, remove the dependent objects, or let them break.
You need to know what depends on a table before you run a destructive statement. The database will not always stop you.
Kinds of dependent objects
| Object | What it relies on | Typical effect on `DROP TABLE` |
|---|---|---|
| Foreign key on another table | The referenced table's primary or unique key | Blocks the drop in most systems |
| View | The tables and columns in its query | Blocks the drop in PostgreSQL. Other systems may leave a broken view |
| Index, trigger, and check constraint on the table | The table itself | Dropped with the table |
| Sequence owned by a column | A column of the table | Dropped with the table in PostgreSQL if the column owns it |
| Function or stored procedure | Names inside its body | Usually not tracked. Fails later, when it is called |
The first two rows are the ones that can stop you. Objects that live inside the table, such as its own indexes and triggers, go away with it and cause no conflict.
Seeing a dependency fail
Create 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;Now try to drop the parent:
DROP TABLE customers;PostgreSQL refuses and lists every dependent object:
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 is a report of what you would damage. Read the DETAIL lines before you reach for CASCADE, which the next chapter covers.
The same rules apply to ALTER TABLE
Dependencies also restrict ALTER TABLE. In PostgreSQL, a column that a view or foreign key uses cannot be dropped or have its type changed freely:
ALTER TABLE customers DROP COLUMN name;This fails because customer_names selects name. Changing the type of customers.id is blocked in a different way. The foreign key column orders.customer_id must stay type-compatible with it.
Renames behave differently. If you rename customers.name to full_name, PostgreSQL rewrites the stored view definition to follow the new name. Dependency tracking can therefore help you as well as stop you.
Finding dependents before you act
Do not rely on memory. Ask the catalog, which is the database's own record of its objects.
PostgreSQL: foreign keys that point at customers:
SELECT conname,
conrelid::regclass AS referencing_table
FROM pg_constraint
WHERE contype = 'f'
AND confrelid = 'customers'::regclass;PostgreSQL: views that read from customers:
SELECT view_schema, view_name
FROM information_schema.view_table_usage
WHERE table_name = 'customers';information_schema.view_table_usage only shows views owned by the current user. For a complete picture, a superuser can query pg_depend and pg_rewrite, or you can try the DROP inside a transaction (see the end of this chapter).
MySQL: foreign keys that reference the table:
SELECT table_name, constraint_name
FROM information_schema.referential_constraints
WHERE constraint_schema = DATABASE()
AND referenced_table_name = 'customers';SQL Server: foreign keys, then other referencing objects:
SELECT name AS fk_name,
OBJECT_NAME(parent_object_id) AS referencing_table
FROM sys.foreign_keys
WHERE referenced_object_id = OBJECT_ID('customers');
SELECT OBJECT_NAME(referencing_id) AS referencing_object
FROM sys.sql_expression_dependencies
WHERE referenced_id = OBJECT_ID('customers');How databases differ
| System | Foreign key references the table | View selects from the table |
|---|---|---|
| PostgreSQL | Drop fails | Drop fails |
| MySQL | Drop fails (unless foreign key checks are off) | Drop succeeds, the view breaks |
| SQL Server | Drop fails | Drop succeeds, unless the view uses `SCHEMABINDING` |
| SQLite | Fails only if foreign keys are enabled and rows would be orphaned | Drop succeeds, the view breaks |
The table summarizes the default behavior of recent versions. Test it on your own system.
A view that survives a drop is a hidden failure. The DROP reports success, and the error appears later, when someone queries the view. Check for views and stored code yourself on systems that do not block you.
A pre-drop checklist
- List foreign keys that reference the table, and decide whether the child tables go first or stay.
- List views and, where the system allows it, routines that use the table.
- Search application code and reports for the table name. The database cannot see those users.
- Take a backup or confirm one exists.
- Run the change in a transaction where your database supports transactional DDL.
PostgreSQL lets you rehearse a risky change and then undo it:
BEGIN;
DROP TABLE customers; -- read the error or confirm what it would remove
ROLLBACK;MySQL commits DDL implicitly, so the same rehearsal does not work there.
Exercise
In PostgreSQL, orders.customer_id has a foreign key to customers.id, and a view customer_names selects from customers. You run DROP TABLE orders;. Does it succeed, and does DROP TABLE customers; succeed afterwards?
Show answer
Dropping orders succeeds, because nothing depends on orders, and it removes the foreign key constraint with it. The following DROP TABLE customers; still fails because the view customer_names depends on customers. You must drop the view first, or use CASCADE (covered in the next chapter).
Exercise
Why is a successful DROP TABLE in MySQL not proof that nothing else was affected?
Show answer
MySQL does not block a drop because a view selects from the table. The view stays in the schema and fails when someone queries it. You must check for views and other referencing code before dropping the table.