// SQL snippet

Swap two table names

Blue-green table deployments end with a swap: the new table takes the old name and the old one steps aside. The trick is doing it without a moment where neither name exists.

Main statement
PostgreSQL
También cubre
SQL Server MySQL SQLite

The task

The rebuilt replacement table is loaded and verified, and it must now take over the live name with no gap in which queries cannot find the table.

The snippet

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

PostgreSQL
BEGIN;
ALTER TABLE products RENAME TO products_old;
ALTER TABLE products_new RENAME TO products;
COMMIT;
-- products_old now holds the previous data; inspect, then drop

Cómo funciona

Both renames commit together, so no query ever finds the products name missing; each rename takes an ACCESS EXCLUSIVE lock, so queries on either table wait until COMMIT. Only the names move. Views and foreign keys reference tables by OID, so after the swap they point at products_old, not the new products; recreate them, or use CREATE OR REPLACE VIEW, before dropping the old table. Sequences, indexes and constraints are whatever the new table was built with.

Variations

MySQL

MySQL
RENAME TABLE products TO products_old,
             products_new TO products;
-- atomic in one statement. Views look tables up by name and
-- use the new products; foreign keys follow products_old

SQL Server

SQL Server
BEGIN TRAN;
EXEC sp_rename 'dbo.Products', 'Products_old';
EXEC sp_rename 'dbo.Products_New', 'Products';
COMMIT;

SQLite

SQLite
-- with legacy_alter_table off (the default), SQLite rewrites
-- views, triggers and FKs to follow each rename, so they
-- end up on products_old, as on PostgreSQL
BEGIN;
ALTER TABLE products RENAME TO products_old;
ALTER TABLE products_new RENAME TO products;
COMMIT;

Questions that come up

Will foreign keys pointing at the old table follow the swap?

No. On PostgreSQL, MySQL and SQLite, a foreign key in another table follows the table it was created against, so after the swap it references products_old. SQL Server behaves the same, since foreign keys store the object ID. Drop and recreate those constraints against the new products, ideally in the same transaction as the swap, before you drop products_old.

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.