实现说明
实际执行的是 SELECT / INSERT / UPDATE / CREATE——customers、generate_series 是涉及的对象。
具体组合了这些手段:WHERE 决定这条语句会作用到哪些行;用 COUNT 做聚合;ORDER BY 固定了输出顺序;LIMIT 限制返回行数;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;自动算列值的 GENERATED ALWAYS/GENERATED BY 子句。
常见问题
这段 SQL 涉及哪些对象?
customers、generate_series——直接引用,无需连接。
核心语句
UPDATE customers
SET domain = split_part(email, '@', 2)
WHERE id IN (
SELECT id FROM customers
WHERE domain IS NULL
ORDER BY id
LIMIT 100
);
INSERT INTO customers (email)
SELECT 'user' || n || '@example.com'
FROM generate_series(1, 300) AS n;
SELECT count(*) AS remaining FROM customers WHERE domain IS NULL;
代码示例
-- A big backfill cannot run as one UPDATE: long transactions hold locks, stall vacuum, and build replication lag
-- Chunk by primary key, commit each chunk independently, and loop in the application until no rows remain
CREATE TABLE customers (
id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
email text NOT NULL,
domain text -- column being backfilled: the domain split out of email
);
INSERT INTO customers (email)
SELECT 'user' || n || '@example.com'
FROM generate_series(1, 300) AS n;
-- Each chunk handles 100 rows: the subquery selects the batch by primary key and the UPDATE rewrites exactly those rows
UPDATE customers
SET domain = split_part(email, '@', 2)
WHERE id IN (
SELECT id FROM customers
WHERE domain IS NULL
ORDER BY id
LIMIT 100
);
-- This chunk's size is the affected-row count; a remaining count of zero means the backfill is done
SELECT count(*) AS remaining FROM customers WHERE domain IS NULL;