// dialect comparison

Drop a column from a table

Remove a column and its data: trivial in four engines, sometimes a rebuild in SQLite.

Filed under Tables & schema

The verdict

The one-liner works on all five current versions. For SQLite, check the version and the column's dependents first, and use the rebuild when it refuses.

Where they differ

Four engines drop a column with the same one-liner. SQLite added DROP COLUMN in 3.35 (2021) and still refuses when the column is a key, indexed, or used by a constraint, view or trigger. Those cases need the rebuild: create the new table, copy, drop, rename.

How each engine writes it

SQL Server

ALTER TABLE customers DROP COLUMN fax;

Drop several comma-separated columns in one statement. Any DEFAULT, CHECK or foreign key constraint and any index on the column must be dropped first.

PostgreSQL

ALTER TABLE customers DROP COLUMN fax;

Instant: the column is hidden and its space is reclaimed as rows are rewritten. Indexes on it go with it; views that use it block the drop unless you add CASCADE, which drops them too.

MySQL

ALTER TABLE customers DROP COLUMN fax;

DROP fax without COLUMN also works. The column is removed from any index that contains it, and an index left with no columns is dropped. 8.0.29+ can drop columns with ALGORITHM=INSTANT.

SQLite

ALTER TABLE customers DROP COLUMN fax;

3.35+, and only if the column isn't a PRIMARY KEY, UNIQUE, indexed, or used in a CHECK, foreign key, generated column, view or trigger. Otherwise rebuild the table.

Oracle

ALTER TABLE customers DROP COLUMN fax;

On big tables, SET UNUSED COLUMN fax hides the column at once and DROP UNUSED COLUMNS removes the data later; CHECKPOINT n limits undo during that pass.

Questions that come up

Is dropping a column recoverable?

Not with SQL: the data is gone once the statement commits, even where the space is reclaimed later. PostgreSQL and SQL Server can roll back the DROP inside an open transaction; otherwise you restore from a backup.

What is Oracle's SET UNUSED for?

It removes the column from the table definition immediately, without touching the rows, which matters on huge tables. A later ALTER TABLE customers DROP UNUSED COLUMNS rewrites the blocks and reclaims the space when convenient.

Why does SQLite reject my DROP COLUMN?

The column is a key, is indexed, or is used by a constraint, generated column, view or trigger. Drop the dependent index, view or trigger first, or rebuild the table (alter-column-type shows the pattern).

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.