Sub topic 5
Dropping a column
This chapter assumes you can write CREATE TABLE and basic SELECT, INSERT, UPDATE and DELETE statements. It also assumes you know what primary keys, foreign keys and views are. Run the examples on a throwaway database, because a dropped column cannot be recovered with SQL alone.
What DROP COLUMN does
ALTER TABLE ... DROP COLUMN removes a column from a table definition and discards the values stored in it for every row. The other columns and rows stay as they were.
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255)
);
ALTER TABLE customers DROP COLUMN email;After this statement, SELECT email FROM customers fails with an "unknown column" error. So does every INSERT that names email. The database does not warn you about application code, reports or scripts that still use the column. Only objects stored inside the database, such as views, indexes and constraints, are checked.
Most databases treat the change as a metadata update plus eventual cleanup. PostgreSQL, for example, marks the column as dropped and does not rewrite the table. The disk space comes back later, when rows are rewritten by VACUUM FULL or similar. MySQL 8.0.29 and later can often drop a column with ALGORITHM=INSTANT. Older versions rebuild the whole table. Do not assume a drop is cheap or expensive without checking your version's documentation.
What blocks a drop
A column is rarely alone. Other objects can depend on it, and each database reacts differently.
| Dependent object | PostgreSQL | MySQL | SQL Server | SQLite |
|---|---|---|---|---|
| View that uses the column | Fails, unless `CASCADE` drops the view | Drop succeeds, view breaks when used | Fails if the view is schema-bound, otherwise the view breaks | Fails |
| Index containing the column | Index is dropped automatically | Column is removed from the index; the index is dropped if no columns remain | Fails until the index is dropped | Fails |
| Foreign key on the column | Constraint is dropped automatically | Fails until the foreign key is dropped | Fails until the constraint is dropped | Fails |
| Default constraint | Dropped automatically | Dropped automatically | Fails until the named default is dropped | Fails |
| Primary key or unique constraint | Dropped automatically, but a foreign key in another table that needs it blocks the drop | Column removed from key | Fails until the constraint is dropped | Fails |
Treat this table as a starting point, because behavior changes between versions. The reliable habit is to look up what depends on the column before you drop it. The next section shows how to do that.
Finding dependencies first
The system catalogs list dependent objects. In PostgreSQL, you can find views that mention a column through information_schema.view_column_usage:
SELECT view_schema, view_name
FROM information_schema.view_column_usage
WHERE table_name = 'customers'
AND column_name = 'email';information_schema.key_column_usage lists key columns, including foreign keys. For indexes, use pg_indexes in PostgreSQL, SHOW INDEX FROM customers in MySQL, or sys.indexes in SQL Server. The commands differ, but the question is always the same: which stored objects mention this column?
RESTRICT and CASCADE for columns
PostgreSQL accepts RESTRICT (the default) and CASCADE after the column name. With RESTRICT, the statement fails if another object depends on the column. With CASCADE, PostgreSQL also drops those dependent objects.
-- PostgreSQL
CREATE VIEW customer_emails AS
SELECT id, email FROM customers;
ALTER TABLE customers DROP COLUMN email;
-- ERROR: cannot drop column email of table customers because
-- other objects depend on it
ALTER TABLE customers DROP COLUMN email CASCADE;
-- also drops the view customer_emailsCASCADE removes the whole view, not just the reference to email. If an application queries that view, it breaks. Run the plain statement first and read the error, which names the dependent objects. Add CASCADE only once you have decided each of those objects should go.
MySQL, SQL Server and SQLite do not accept CASCADE on DROP COLUMN. In those systems you drop the blocking objects yourself, in the right order.
Dropping a column in SQL Server
SQL Server treats a column default as a separate constraint object. If the default has an auto-generated name, you must look the name up before you can drop the column. Naming defaults when you create them avoids this:
-- SQL Server
ALTER TABLE customers
ADD status VARCHAR(20) NOT NULL
CONSTRAINT df_customers_status DEFAULT 'active';
ALTER TABLE customers DROP CONSTRAINT df_customers_status;
ALTER TABLE customers DROP COLUMN status;Running only the last statement fails, because df_customers_status still depends on status. SQL Server also lets you list several columns in one statement: ALTER TABLE customers DROP COLUMN a, b;.
Dropping several columns, and IF EXISTS
PostgreSQL and MySQL take several DROP COLUMN clauses separated by commas, and the whole statement succeeds or fails together:
ALTER TABLE customers
DROP COLUMN phone,
DROP COLUMN fax;PostgreSQL also supports DROP COLUMN IF EXISTS, which does nothing instead of raising an error when the column is missing. This makes a migration script safe to run twice:
-- PostgreSQL, MariaDB, SQL Server 2016 and later
ALTER TABLE customers DROP COLUMN IF EXISTS email;Oracle MySQL does not support IF EXISTS in this position, although MariaDB does. SQLite does not support it either. In those systems, check the catalog first or let the script fail and handle the error.
SQLite restrictions
SQLite added DROP COLUMN in version 3.35.0 (2021). Before that, the only way was to create a new table, copy the data, drop the old table and rename the new one. Even now, SQLite refuses to drop a column if it:
- is a
PRIMARY KEYor has aUNIQUEconstraint, - is indexed,
- is used in a
CHECK, a foreign key, a generated column, a trigger or a view.
Check SELECT sqlite_version(); before you rely on the statement.
A safe sequence
A drop is destructive, so a careful process matters more than the syntax. The flow below is a reasonable default.
A simple backup copies the key and the column into a new table before the drop:
-- PostgreSQL, MySQL, SQLite
CREATE TABLE customers_email_backup AS
SELECT id, email FROM customers;
ALTER TABLE customers DROP COLUMN email;SQL Server uses SELECT id, email INTO customers_email_backup FROM customers; instead. If you later need the data back, you can ADD COLUMN email and fill it with an UPDATE that joins on id. That only works if you kept the key.
In PostgreSQL you can wrap the drop in a transaction and inspect the result before you commit:
BEGIN;
ALTER TABLE customers DROP COLUMN email;
SELECT * FROM customers LIMIT 5;
ROLLBACK; -- use COMMIT when satisfiedMySQL commits DDL implicitly, so ROLLBACK does nothing there. Test on a copy.
Common errors
- Dependent object error. The message names a view, constraint or index. Drop it or use
CASCADEin PostgreSQL, but only after confirming it is safe. - Column does not exist. The script was run twice, or the column name has a typo. Use
IF EXISTSwhere supported. - Lock waits.
ALTER TABLEoften needs an exclusive lock. A long-running transaction on the table can make the drop wait, and other queries queue up behind it. Set a lock timeout where your database supports one. - Missing a generated or computed column. A column that is computed from the one you are dropping blocks the drop in most systems.
Exercise
In PostgreSQL, a view customer_emails selects id and email from customers. You run ALTER TABLE customers DROP COLUMN email; and get an error. What are two ways to proceed, and which would you try first?
Show answer
First, run DROP VIEW customer_emails; (or recreate it without email) and then drop the column. Alternatively, run ALTER TABLE customers DROP COLUMN email CASCADE;, which drops the view as a side effect. Try the first option, or at least read the error and check what else depends on the column, because CASCADE silently removes every dependent object, and other code may rely on that view.