Generate DROP TABLE statements
Dropping thirty tables by hand invites typos and missed ones. Generate the statements from the metadata, review the script, then run it.
The task
A scratch schema holds dozens of tables that all have to go, and the removal should be scripted from the metadata rather than typed out.
The snippet
Written for MySQL. Versions for SQL Server, PostgreSQL and SQLite are under Variations.
SELECT CONCAT('DROP TABLE IF EXISTS `', table_schema, '`.`', table_name, '`;') AS drop_statement
FROM information_schema.tables
WHERE table_schema = 'mydb'
AND table_type = 'BASE TABLE'
ORDER BY table_name;
Como funciona
The query turns each table row into a complete DROP statement for you to review and then run. IF EXISTS keeps the script re-runnable, and the backtick quoting survives table names that are reserved words (a name containing a backtick would still break it). Foreign keys decide whether it works: on MySQL, run SET FOREIGN_KEY_CHECKS = 0 in the same session first, or drop children before parents. SQL Server refuses to drop a table that a foreign key still references, so drop those constraints first or order the list with the table-dependency-order recipe.
Variations
PostgreSQL
PostgreSQLSELECT string_agg(
format('DROP TABLE IF EXISTS %I.%I CASCADE;', table_schema, table_name),
E'\n' ORDER BY table_name)
FROM information_schema.tables
WHERE table_schema = 'public' AND table_type = 'BASE TABLE';
-- one statement that drops in any order thanks to CASCADE
SQL Server
SQL ServerSELECT 'DROP TABLE IF EXISTS ' + QUOTENAME(SCHEMA_NAME(schema_id))
+ '.' + QUOTENAME(name) + ';'
FROM sys.tables
ORDER BY name;
SQLite
SQLiteSELECT 'DROP TABLE IF EXISTS "' || replace(name, '"', '""') || '";'
FROM sqlite_master
WHERE type = 'table' AND name NOT LIKE 'sqlite_%';
Questions that come up
Is DROP ... CASCADE dangerous here?
It drops more than the table. On PostgreSQL, CASCADE also drops views that read the table and the foreign key constraints on other tables that point at it (the other tables survive). That is what makes the script order-independent. Run it inside BEGIN and read the NOTICE lines listing what else it dropped before you COMMIT.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.