// SQL snippet

Create an empty table like another table

Rotating tables (orders becomes orders_2026_11) needs a new table with the old one's constraints, defaults and indexes but none of its rows.

Main statement
PostgreSQL
다음도 지원
SQL Server MySQL

The task

Next month's shard of a rotating table must exist before rows arrive, and a hand-written CREATE TABLE drifts from the original within a release or two.

The snippet

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

PostgreSQL
CREATE TABLE orders_next (LIKE orders INCLUDING ALL);
-- columns, defaults, CHECK and NOT NULL constraints, indexes,
-- identity, storage and comments; no rows and no foreign keys

작동 방식

INCLUDING ALL turns on every INCLUDING option: comments, compression, constraints, defaults, generated columns, identity, indexes, statistics and storage. Without them, LIKE copies only column names, types and NOT NULL. Even INCLUDING ALL leaves out foreign keys, triggers, grants, ownership and row-level security policies, and an identity column gets its own new sequence that starts from the beginning, not where the original's left off.

Variations

MySQL

MySQL
CREATE TABLE orders_next LIKE orders;
-- LIKE copies columns, indexes and defaults; FKs are skipped

SQL Server

SQL Server
-- script the table (SMO, or SSMS 'Script Table as CREATE'),
-- then execute the DDL with a new name
SELECT TOP 0 * INTO dbo.Orders_Next FROM dbo.Orders; -- types only

PostgreSQL: verify what was cloned

PostgreSQL
SELECT indexname, indexdef FROM pg_indexes
WHERE tablename = 'orders_next';
SELECT conname, pg_get_constraintdef(oid)
FROM pg_constraint WHERE conrelid = 'orders_next'::regclass;

Questions that come up

Why are my foreign keys missing from the clone?

CREATE TABLE ... LIKE never copies foreign keys on PostgreSQL or MySQL; the INCLUDING CONSTRAINTS option covers CHECK and NOT NULL only. Add them with ALTER TABLE orders_next ADD CONSTRAINT ... FOREIGN KEY, using the definitions from pg_get_constraintdef on the original table.

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.