Batched Backfill Update In Chunks

Backfill large tables in chunks with UPDATE over a bounded id subquery, keeping each transaction short so locks and replication lag stay small.

SqlData Integrity

Code

snippet
-- 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;

How it works

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

What the statements actually assemble: a WHERE clause filtering the rows one statement applies to; COUNT aggregation; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Applying it

Run the statement against the customers table; the LIMIT keeps the probe cheap while you tune the predicates.

Statements that matter

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;

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
`customers`, `generate_series` — referenced directly, no join needed.