COPY FROM STDIN CSV Bulk Load

Load CSV in one atomic statement with COPY, choosing server-side file reads or the client-side \copy equivalent and skipping row-by-row inserts.

SqlCli Tooling

Code

snippet
-- COPY 是批量装载的最快路径:一批数据一个语句一个事务
CREATE TABLE measurements (
    sensor_id int            NOT NULL,
    taken_at  timestamptz    NOT NULL,
    value     numeric(10, 3) NOT NULL
);

-- 服务端 COPY:路径由服务器进程读取,需要 pg_read_server_files 角色
COPY measurements (sensor_id, taken_at, value)
FROM '/data/exports/measurements.csv'
WITH (FORMAT csv, HEADER true);

-- 客户端等价写法:psql 的 \copy 由客户端读文件再经 STDIN 发送
-- \copy measurements from 'measurements.csv' with (format csv, header true)

-- 数据行示例(HEADER true 时首行是列名):
--   sensor_id,taken_at,value
--   1,2026-11-14T08:00:00Z,23.500

-- COPY 是单语句原子操作:任一行违反约束则整体失败,不留下部分数据
SELECT count(*) FROM measurements;

Inside the snippet

What runs here is SELECT / CREATE — measurements are the objects involved.

Breaking the statements into their working parts: COUNT aggregation; NOT NULL qualifiers on the required columns.

Using it

The measurements table is the working surface here.

Key statements

CREATE TABLE measurements (
    sensor_id int            NOT NULL,
    taken_at  timestamptz    NOT NULL,
    value     numeric(10, 3) NOT NULL
);
COPY measurements (sensor_id, taken_at, value)
FROM '/data/exports/measurements.csv'
WITH (FORMAT csv, HEADER true);
SELECT count(*) FROM measurements;

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
The references are `measurements`.