CREATE TABLE AS Copies Data Not Rules

CREATE TABLE AS clones column types and rows but carries no primary keys, defaults, or indexes; LIKE ... INCLUDING ALL is the full-structure clone.

SqlData Integrity

Code

snippet
-- 源表带主键与 NOT NULL
CREATE TABLE readings (
    sensor_id int PRIMARY KEY,
    taken_at  timestamptz NOT NULL,
    celsius   numeric(5,2)
);

-- CREATE TABLE AS 只复制数据与列类型:约束、默认值、索引一律不带
CREATE TABLE readings_copy AS
SELECT * FROM readings;

-- 副本可以插入重复 sensor_id(没有主键约束)
INSERT INTO readings_copy VALUES (1, now(), 21.5), (1, now(), 22.0);
SELECT count(*) AS copied_rows FROM readings_copy;  -- 2 行,与约束无关

-- 要结构规则一并复制:LIKE ... INCLUDING ALL 才带上约束与索引
CREATE TABLE readings_full (LIKE readings INCLUDING ALL);

Inside the snippet

What runs here is SELECT / INSERT / CREATE — readings and readings_copy are the objects involved.

Breaking the statements into their working parts: COUNT aggregation; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Using it

Point it at the readings table.

The statements that matter here

CREATE TABLE readings_copy AS
SELECT * FROM readings;
CREATE TABLE readings (
    sensor_id int PRIMARY KEY,
    taken_at  timestamptz NOT NULL,
    celsius   numeric(5,2)
);
INSERT INTO readings_copy VALUES (1, now(), 21.5), (1, now(), 22.0);

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
The references are `readings`, `readings_copy`.