// SQL snippet

Truncate all tables in safe order

Resetting a test database means emptying every table, and foreign keys make hand-written TRUNCATE lists fail halfway. This recipe handles the FK problem per engine.

Main statement
PostgreSQL
Couvre également
SQL Server MySQL

The task

One TRUNCATE against a referenced table aborts the whole cleanup, so emptying a schema means either dependency order or a per-engine trick that sidesteps it.

The snippet

Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.

PostgreSQL
-- one statement, all tables: PostgreSQL checks FKs against the
-- combined truncate and only requires CASCADE for outside references
TRUNCATE TABLE
    public.users,
    public.orders,
    public.order_items,
    public.products
RESTART IDENTITY CASCADE;

Fonctionnement

PostgreSQL lets one TRUNCATE name many tables and validates foreign keys across the whole set at once, so parents and children truncate together and order does not matter. CASCADE extends the operation to tables that reference the listed ones from outside, and RESTART IDENTITY resets sequences. To avoid typing the list, the first variant builds the same single statement from information_schema inside a DO block.

Variations

PostgreSQL: generated, whole schema

PostgreSQL
DO $$
DECLARE stmt text;
BEGIN
  SELECT 'TRUNCATE TABLE '
         || string_agg(format('%I.%I', table_schema, table_name), ', ')
         || ' RESTART IDENTITY CASCADE'
    INTO stmt
  FROM information_schema.tables
  WHERE table_schema = 'public' AND table_type = 'BASE TABLE';
  IF stmt IS NOT NULL THEN
    EXECUTE stmt;
  END IF;
END $$;

MySQL

MySQL
-- TRUNCATE of a referenced table fails (error 1701) unless
-- checks are off in the same session
SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE TABLE order_items;
TRUNCATE TABLE orders;
TRUNCATE TABLE users;
SET FOREIGN_KEY_CHECKS = 1;
-- generate the list with
-- SELECT CONCAT('TRUNCATE TABLE `', table_name, '`;')
-- FROM information_schema.tables WHERE table_schema = 'mydb'
-- AND table_type = 'BASE TABLE';

SQL Server

SQL Server
-- TRUNCATE is refused on any table a foreign key references,
-- even an empty one (error 4712). Disable the FKs and DELETE:
EXEC sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL';
EXEC sp_MSforeachtable 'DELETE FROM ?';
EXEC sp_MSforeachtable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL';
-- sp_MSforeachtable is undocumented and covers every table in
-- the database; DELETE does not reset IDENTITY (use DBCC CHECKIDENT)

Questions that come up

Why TRUNCATE instead of DELETE for resets?

TRUNCATE deallocates the table's storage instead of removing rows one at a time, so it takes about the same time for ten rows or ten million, and it skips ON DELETE triggers. It can be rolled back on PostgreSQL and SQL Server, but on MySQL it commits implicitly. DELETE is slower on big tables but fires delete triggers and works through foreign keys, so use it when you rely on those triggers.

Keep reading

// snippets are better with a schema brain

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.