INSERT SELECT Aligns Columns By Position

INSERT ... SELECT maps the select list onto the target column list by position, so column names need not match but the order must.

SqlData Integrity

Code

snippet
-- INSERT ... SELECT 按列的"位置"对齐:SELECT 的第 1 列进第 1 个目标列
CREATE TABLE customers (
    id    integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email text    NOT NULL,
    plan  text    NOT NULL DEFAULT 'free'
);

CREATE TABLE staging (
    email       text,
    plan        text,
    imported_at date
);

INSERT INTO staging (email, plan, imported_at) VALUES
    ('[email protected]', 'pro',  DATE '2026-11-01'),
    ('[email protected]', 'free', DATE '2026-11-02');

-- 显式列清单 + 按位对齐:源列名不需要与目标一致,顺序必须一一对应
INSERT INTO customers (email, plan)
SELECT email, plan
FROM staging
WHERE imported_at >= DATE '2026-11-01';

-- SELECT 只给一列时,plan 落到目标表的 DEFAULT
INSERT INTO customers (email)
SELECT 'new-' || email FROM staging WHERE plan = 'free';

SELECT id, email, plan FROM customers ORDER BY id;

Inside the snippet

What runs here is SELECT / INSERT / CREATE — staging and customers are the objects involved.

What the statements actually assemble: a WHERE clause that keeps only the rows a statement is meant to touch; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Putting it to use

The staging table is the working surface here.

Core lines

INSERT INTO customers (email, plan)
SELECT email, plan
FROM staging
WHERE imported_at >= DATE '2026-11-01';
INSERT INTO customers (email)
SELECT 'new-' || email FROM staging WHERE plan = 'free';
CREATE TABLE customers (
    id    integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email text    NOT NULL,
    plan  text    NOT NULL DEFAULT 'free'
);

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
The references are `staging`, `customers`.