Clone Table Shape With LIKE INCLUDING

CREATE TABLE LIKE with INCLUDING ALL copies defaults, constraints, and indexes, giving staging tables the parent guarantees.

SqlData Integrity

Code

snippet
-- LIKE 默认只复制列定义;INCLUDING ALL 才把默认值、约束、索引进来
CREATE TABLE orders (
    id          bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    customer_id bigint      NOT NULL,
    total_cents integer     NOT NULL CHECK (total_cents >= 0),
    created_at  timestamptz NOT NULL DEFAULT now()
);

-- staging 表继承全部保障:主键、CHECK、默认值一应俱全
CREATE TABLE orders_staging (LIKE orders INCLUDING ALL);

-- 只想要列形状、不要约束时:省略选项即可
CREATE TABLE orders_flat (LIKE orders);

SELECT conrelid::regclass AS tbl, count(*) AS constraints
FROM pg_constraint
WHERE conrelid IN ('orders_staging'::regclass, 'orders_flat'::regclass)
GROUP BY 1
ORDER BY 1;

-- orders_staging 带 2 条约束(pk + check);orders_flat 一条都没有

What LIKE copies by default

CREATE TABLE orders_flat (LIKE orders) copies only column definitions — no defaults, no constraints, no indexes. It is a shape clone, nothing more.

What INCLUDING ALL adds

orders_staging inherits the identity primary key, the CHECK (total_cents >= 0), the NOT NULLs, and the DEFAULT now(). The pg_constraint query proves the gap: staging carries 2 constraints while flat carries none.

Choosing the level

Staging tables that must uphold the same guarantees as their parent want INCLUDING ALL; throwaway shape-only tables (ETL intermediates) stay cheap with bare LIKE.

Interactive Tools for This Topic

FAQ

What does bare LIKE omit?
Defaults, constraints, and indexes — it copies column definitions only, which is why orders_flat ends with zero constraints.
How does the demo verify the constraint gap?
A query over pg_constraint for both tables counts 2 constraints on orders_staging and none on orders_flat.