Sub topic 3
What depends on a table
This chapter assumes you know SELECT, INSERT, UPDATE and DELETE, CREATE TABLE, and primary and foreign keys. Examples use PostgreSQL unless noted.
What depends on a table
A table often has other objects that refer to it: foreign keys in other tables, views, indexes, and triggers. Before you change or drop a table, find out what points at it. Otherwise the database may refuse the change, or it may remove objects you still need.
CASCADE and RESTRICT
RESTRICT stops a DROP while dependent objects exist. CASCADE drops the dependent objects too. In PostgreSQL, RESTRICT is the default.
-- PostgreSQL
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (id)
);
DROP TABLE customers; -- fails: orders depends on customers
DROP TABLE customers CASCADE; -- drops the foreign key; the orders table remainsDROP, TRUNCATE and DELETE compared
| Statement | What it removes | Table definition kept? | Rollback in PostgreSQL? |
|---|---|---|---|
| DELETE FROM t WHERE ... | Matching rows | Yes | Yes |
| TRUNCATE TABLE t | All rows | Yes | Yes |
| DROP TABLE t | All rows and the table definition | No | Yes |
Running schema changes inside transactions
A transaction groups statements so they succeed or fail together. PostgreSQL and SQL Server can roll back ALTER TABLE inside a transaction. MySQL and Oracle commit DDL automatically, so a rollback will not undo it.
-- PostgreSQL
BEGIN;
ALTER TABLE customers ADD COLUMN phone VARCHAR(30);
ROLLBACK;Differences between database systems
Syntax varies by product. For example, changing a column's type looks like this:
| Database | Statement |
|---|---|
| PostgreSQL | ALTER TABLE customers ALTER COLUMN name TYPE VARCHAR(200); |
| MySQL | ALTER TABLE customers MODIFY COLUMN name VARCHAR(200) NOT NULL; |
| SQL Server | ALTER TABLE customers ALTER COLUMN name VARCHAR(200) NOT NULL; |
SQL Server also renames columns with the sp_rename procedure, not RENAME COLUMN.
Locking and large tables
Some ALTER TABLE changes rewrite every row or hold a lock that blocks reads or writes. On a large table, this can take a long time. Check your database version's documentation before you run a change in production.
Planning safe, reversible schema changes
- Back up the table or database.
- List dependents: foreign keys, views and triggers.
- Test the change on a copy of the data.
- Wrap the change in a transaction where the database supports it.
- Write the reverse statement before you run the forward one.
Exercise
On PostgreSQL, what happens to the orders table when you run DROP TABLE customers CASCADE?
Show answer
The foreign key constraint on orders is dropped. The orders table and its rows remain.