Copy a table's structure only
Backups before risky work, staging twins of production tables, and test fixtures all start with an empty copy of a table's shape. Each engine has its own way.
The task
A destructive migration is scheduled and you want a scratch copy of the table's definition to test against first, without moving the data.
The snippet
Written for MySQL. Versions for SQL Server, PostgreSQL and SQLite are under Variations.
CREATE TABLE users_backup LIKE users;
-- columns, types, defaults, indexes and CHECK constraints are
-- copied; rows and foreign keys are not
工作原理
CREATE TABLE ... LIKE copies the column definitions, defaults, indexes and (from MySQL 8.0.16) CHECK constraints, and runs instantly because it reads no rows. Foreign keys are not copied, though the index that backed each one is, and the AUTO_INCREMENT counter starts again from 1. Triggers and grants stay with the original.
Variations
PostgreSQL
PostgreSQL-- column names, types and NOT NULL only
CREATE TABLE users_backup (LIKE users);
-- or, including defaults, constraints and indexes:
CREATE TABLE users_backup_full (LIKE users INCLUDING ALL);
SQL Server
SQL ServerSELECT TOP 0 * INTO dbo.Users_Backup FROM dbo.Users;
-- copies columns, nullability and the IDENTITY property;
-- no indexes, keys, defaults, checks or triggers
SQLite
SQLite-- via the schema text from sqlite_master:
SELECT sql FROM sqlite_master WHERE name = 'users';
-- rewrite the table name in that DDL and execute it
Questions that come up
Why is the copy missing my foreign keys?
None of these methods copies foreign keys: MySQL's LIKE, PostgreSQL's LIKE even with INCLUDING ALL, and SELECT INTO all leave them out. Add them to the copy with ALTER TABLE ... ADD CONSTRAINT if the copy needs to enforce them; list-foreign-keys-targets shows the definitions to reproduce.
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.