Sub topic 5
Dropping a Column
What Dropping a Column Does
Assume you know basic SELECT, INSERT, UPDATE, and DELETE, can create tables, and understand primary and foreign keys.
A column is one named field in a table. Dropping a column removes the field and all values stored in it. This is a schema change, so it is a DDL operation, not a DML operation. DML changes rows. DDL changes the database structure.
Use ALTER TABLE with DROP COLUMN:
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255)
);
ALTER TABLE customers DROP COLUMN email;After the statement succeeds, customers contains only id and name. The email values are gone from the table. An UPDATE cannot restore them.
A column usually has dependencies. Application queries, views, indexes, generated columns, triggers, and constraints might refer to it. Some database systems reject the change when such dependencies exist. Other systems remove or invalidate dependent objects, depending on the object and the options used.
Check Before You Drop
Treat the operation as destructive. Before running it:
- Search application code, reports, and scheduled jobs for the column name.
- Inspect views, triggers, indexes, and constraints that may use the column.
- Confirm that the column is not needed for a rollback.
- Back up the table or database according to your recovery plan.
- Test the migration against a recent copy of the data.
- Deploy application changes that stop reading and writing the column first.
Some systems support IF EXISTS:
ALTER TABLE customers DROP COLUMN IF EXISTS email;This avoids an error when the column is already absent. It makes a script easier to run repeatedly, but it does not make the data loss reversible. Check whether your database supports this form before using it.
Dependencies and Constraints
A foreign key in another table normally references a key column, not an unrelated descriptive column. However, indexes, views, computed expressions, and triggers can still depend on a column. A database may refuse the drop until you remove or update those objects.
Do not assume that CASCADE is safe. In systems that support it, cascading can remove dependent objects or constraints. Review the database documentation and dependency list before choosing it.
Dialect and Operational Differences
The basic form is widely supported:
ALTER TABLE customers DROP COLUMN email;The exact behavior differs across PostgreSQL, MySQL, SQL Server, and SQLite. PostgreSQL can run many schema changes inside a transaction. MySQL may implicitly commit DDL, so a later ROLLBACK might not undo the change. Dropping a column can also acquire a table lock or rebuild the table, especially on a large table.
Exercise
Why is checking application code before ALTER TABLE ... DROP COLUMN necessary?
Show answer
The database may not know about every application dependency. A query or job that still names the column can fail after the column is removed.