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.
Code
-- 源表带主键与 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables does the SQL touch?
- The references are `readings`, `readings_copy`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.