Sub topic 9
Removing a table with DROP TABLE
This chapter covers what DROP TABLE removes, what it needs to run, and how to use it without losing data you still need. It assumes you can write CREATE TABLE, know what a primary key and foreign key are, and have a test database (PostgreSQL, MySQL, SQL Server or SQLite) where you can experiment.
Later chapters cover IF EXISTS, dependent objects, CASCADE and RESTRICT, and the comparison with TRUNCATE and DELETE. Here we cover the core statement.
What DROP TABLE does
DROP TABLE is a DDL (data definition language) statement. It deletes the table itself, not just its rows. After it succeeds, the table name no longer exists in the database catalog.
The statement removes:
- the table definition, meaning its columns and data types
- every row stored in the table
- the indexes built on the table
- the table's own constraints (primary key, unique, check, and the foreign keys defined on this table)
- triggers attached to the table
- privileges granted on the table
In most systems the storage the table used is released as well. PostgreSQL also drops sequences owned by the table's serial or identity columns.
Basic syntax
The minimal form names one table:
DROP TABLE import_staging;You can qualify the name with a schema when the table is not in your default schema:
DROP TABLE reporting.import_staging;PostgreSQL, MySQL and SQL Server (2016 and later) accept several tables in one statement:
DROP TABLE import_staging, import_errors;SQLite and Oracle accept only one table per DROP TABLE, so use one statement per table there.
A worked example
This script runs on PostgreSQL, MySQL, SQL Server and SQLite. It creates a throwaway table, fills it, drops it, and then shows what a later query sees.
CREATE TABLE import_staging (
id INTEGER PRIMARY KEY,
raw_line VARCHAR(200)
);
INSERT INTO import_staging (id, raw_line) VALUES (1, 'a,b,c');
INSERT INTO import_staging (id, raw_line) VALUES (2, 'd,e,f');
SELECT COUNT(*) FROM import_staging; -- returns 2
DROP TABLE import_staging;
SELECT COUNT(*) FROM import_staging; -- fails: the table is goneThe last query raises an error because the name no longer exists. Each system words the error differently:
| Database | Error text (abbreviated) |
|---|---|
| PostgreSQL | `relation "import_staging" does not exist` |
| MySQL | `Table 'mydb.import_staging' doesn't exist` |
| SQL Server | `Invalid object name 'import_staging'` |
| SQLite | `no such table: import_staging` |
The same error appears if you run DROP TABLE import_staging; a second time. Scripts that must tolerate that situation use IF EXISTS, covered in the next chapter.
DROP TABLE is not undoable by default
A dropped table does not go to a recycle bin in most systems. Once the statement commits, the data is recoverable only from a backup or a point-in-time restore.
There are exceptions and caveats:
- Oracle moves a dropped table to a recycle bin unless you write
DROP TABLE name PURGE. You can bring it back withFLASHBACK TABLE name TO BEFORE DROP. - PostgreSQL lets you roll back a
DROP TABLEif it is still inside an open transaction. AfterCOMMITit is final. - MySQL commits implicitly around DDL, so there is no rollback window at all.
Chapter 14 returns to transactions and DDL. For now, treat every drop as permanent.
Permissions
You need the right to drop the specific table:
- PostgreSQL: you must own the table (or be a superuser or member of the owning role). The
DROPprivilege does not exist as a separate grant on tables. - MySQL: the
DROPprivilege on that table or its database. - SQL Server:
ALTERpermission on the table's schema, orCONTROLon the table. - Oracle: ownership, or the
DROP ANY TABLEsystem privilege.
If the statement fails with a permission error, do not work around it by using an administrator account. Ask the table's owner, because the restriction is often deliberate.
When the drop is refused
A drop can fail for reasons other than permissions.
- Another table has a foreign key to it. PostgreSQL, MySQL and SQL Server all refuse by default. Dropping the child table first, or removing the foreign key, fixes this.
- A view or other object depends on it. PostgreSQL refuses unless you add
CASCADE. MySQL and SQL Server allow the drop, but the view then fails when queried. - Another session holds a lock on it. The drop waits for open transactions that use the table. On a busy system, a forgotten open transaction can make a
DROP TABLEhang.
Reasons 1 and 2 belong to the next chapters on dependencies. For the third, remember that DROP TABLE needs an exclusive lock. In PostgreSQL it takes an ACCESS EXCLUSIVE lock, which blocks all other reads and writes on the table until the drop finishes.
Dropping in the right order
When tables reference each other, drop the table that holds the foreign key (the child) before the table it points to (the parent). Creation runs in the opposite order, parent first.
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)
);
DROP TABLE orders; -- child first
DROP TABLE customers; -- then parentIf you reverse these two drops, the customers drop fails while orders still exists. This is the most common DROP TABLE error in teardown scripts, and a fixed order is the simplest cure.
Temporary tables and name collisions
A temporary table lives only for your session (or transaction) and can share a name with a permanent table. In that case an unqualified DROP TABLE in PostgreSQL drops the temporary one, because the temporary schema is searched first. MySQL provides a safer form:
-- MySQL
DROP TEMPORARY TABLE scratch_results;With TEMPORARY, MySQL refuses to touch a permanent table of the same name. Use it whenever you mean only the temporary one.
Check before you drop
A short routine prevents most accidents.
- Confirm which database you are connected to (
SELECT current_database();in PostgreSQL,SELECT DATABASE();in MySQL,SELECT DB_NAME();in SQL Server). - Look at what the table holds, for example
SELECT COUNT(*) FROM old_orders;. - Find what references it. In PostgreSQL, this query lists foreign keys that point at
customers:
SELECT conname, conrelid::regclass AS referencing_table
FROM pg_constraint
WHERE contype = 'f'
AND confrelid = 'customers'::regclass;- Keep a copy if the data might matter. A quick one is:
CREATE TABLE customers_backup AS
SELECT * FROM customers;SQL Server writes this as SELECT * INTO customers_backup FROM customers;. A copy made this way keeps the rows but not indexes, constraints or defaults, so for anything important use pg_dump, mysqldump or your platform's backup tool instead.
Common mistakes
- Running a script against production instead of the test database because the connection string was not checked.
- Assuming
DROP TABLEcan be filtered. It has noWHEREclause. To remove some rows, useDELETE. - Dropping a table to "empty it" and then losing its indexes, constraints and grants, which must all be recreated.
- Forgetting that other applications, reports or scheduled jobs may still query the table.
Exercise
A teardown script drops customers and then orders, where orders.customer_id has a foreign key to customers.id. In PostgreSQL the first statement fails. Why does it fail, and what is the simplest fix that does not use CASCADE?
Show answer
The foreign key on orders depends on customers, so PostgreSQL refuses to drop the parent table while the child table still exists. Swap the order: run DROP TABLE orders; first, then DROP TABLE customers;.
Exercise
Name three things that are removed along with a table's rows when you run DROP TABLE, and one thing you should do beforehand if the data might be needed again.
Show answer
Any three of: the table definition, its indexes, its triggers, its own constraints, its privileges. Beforehand, make a backup or copy of the data (for example with a dump tool or CREATE TABLE ... AS SELECT), because a committed drop usually cannot be undone.