// SQL snippet

Rename a table safely

Renaming a table is instant at the database level. The risk is everything outside the database that spells the old name: views, foreign keys, application code and dashboards.

Main statement
PostgreSQL
同時涵蓋
SQL Server MySQL SQLite

The task

The table needs a new name to match a reworked domain model, and nothing in the database or the application should break when the rename lands.

The snippet

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

PostgreSQL
ALTER TABLE users RENAME TO users_archive;
-- catalog-only change; views and foreign keys reference the
-- table by OID, so they follow it to the new name

它的運作方式

The rename is a catalog update, so its duration does not depend on table size, but it needs an ACCESS EXCLUSIVE lock: it waits for running queries on the table and blocks new ones while waiting, so set lock_timeout on a busy system. On PostgreSQL, views and foreign keys follow the table. Function bodies, dynamic SQL, scripts and application code that use the old name now fail. Search them for the name before renaming.

Variations

MySQL

MySQL
RENAME TABLE users TO users_archive;
-- foreign keys follow the table, but views store the name
-- and fail until recreated against users_archive

SQL Server

SQL Server
EXEC sp_rename 'dbo.Users', 'Users_Archive';
-- sp_rename does NOT update referencing objects; check
-- sys.sql_modules for stale definitions afterwards

SQLite

SQLite
ALTER TABLE users RENAME TO users_archive;
-- views and triggers are rewritten to the new name since
-- 3.25, FKs in other tables since 3.26, unless
-- legacy_alter_table is on (macOS's bundled sqlite3 sets it)

Questions that come up

Will my foreign keys still work after a rename?

Yes. On every engine here, foreign keys stay attached to the renamed table and keep enforcing (SQLite rewrites the REFERENCES clause unless legacy_alter_table is on). Views are where engines differ: PostgreSQL and SQLite update them, MySQL and SQL Server views keep the old name and fail until you recreate them. Code and dynamic SQL that spell the old name break everywhere.

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.