TExcelTAD
Home › SQL › SQL DROP TABLE

SQL DROP TABLE

DROP TABLE deletes a table completely — its rows, its structure, its indexes and triggers. There is no undo outside a transaction, so treat it with care.

sql
DROP TABLE table_name;

Dropping a table

sql · try it yourself
CREATE TABLE temp_report AS SELECT status, COUNT(*) AS n FROM orders GROUP BY status;
SELECT name FROM sqlite_schema WHERE type = 'table' AND name LIKE 'temp%';

DROP TABLE temp_report;
SELECT name FROM sqlite_schema WHERE type = 'table' AND name LIKE 'temp%';

SELECT * FROM temp_report;
name
-----------
temp_report
(1 row)

name
----
(0 rows)

Error: no such table: temp_report

After the drop, the table is gone from the schema and querying it is an error.

DROP TABLE IF EXISTS

Dropping a table that does not exist is an error. IF EXISTS makes scripts safe to rerun:

sql · try it yourself
DROP TABLE IF EXISTS no_such_table;
SELECT 'still running' AS message;

DROP TABLE no_such_table;
message
-------------
still running
(1 row)

Error: no such table: no_such_table

A common pattern at the top of setup scripts:

sql
DROP TABLE IF EXISTS reviews;
CREATE TABLE reviews ( ... );

DROP vs DELETE vs TRUNCATE

Statement Rows Structure Typical use
DELETE FROM t WHERE … some removed kept remove specific rows
DELETE FROM t all removed kept empty a table (SQLite)
TRUNCATE TABLE t all removed kept fast emptying (MySQL, PostgreSQL, SQL Server)
DROP TABLE t gone gone remove the table itself
sql · try it yourself
DELETE FROM order_items;
SELECT COUNT(*) AS items FROM order_items;   -- table still exists, 0 rows

DROP TABLE order_items;
SELECT name FROM sqlite_schema
WHERE type = 'table'
ORDER BY name;
98 rows affected.

items
-----
0
(1 row)

name
----------
categories
customers
employees
orders
products
suppliers
(6 rows)

Dropping tables that others depend on

When foreign keys are enforced, you cannot drop (or empty) a table whose rows are still referenced by another table's foreign key. Drop the "child" table first (order_items before orders), or remove the referencing rows. PostgreSQL offers DROP TABLE … CASCADE to remove dependent objects too.

Dropping a whole database

On server databases, DROP DATABASE name; deletes an entire database with all its tables. In SQLite you simply delete the database file.

Tip: Before dropping anything in production, make a backup — for example CREATE TABLE t_backup AS SELECT * FROM t; — or run the drop inside a transaction so you can still ROLLBACK.

Test yourself

What remains after DROP TABLE reviews;?

  1. The empty table
  2. The table structure without indexes
  3. Nothing — table and data are gone
  4. Only the primary key

How do you avoid an error when the table might not exist?

  1. DROP TABLE t IF EXISTS
  2. DROP TABLE IF EXISTS t
  3. DROP IF t
  4. TRY DROP TABLE t