Watermark Incremental Sync Query

Pull only rows past a stored watermark with an incremental sync query, then advance the watermark so repeated runs move forward without reprocessing.

SqlData Fetching

Code

snippet
-- Incremental extraction: each run takes only rows whose updated_at is past the stored watermark
-- The watermark lives in a table, so the job resumes after an application restart
CREATE TABLE sync_state (
    job text PRIMARY KEY,
    watermark timestamptz NOT NULL DEFAULT '-infinity'
);

CREATE TABLE orders (
    id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
    updated_at timestamptz NOT NULL DEFAULT now()
);

INSERT INTO sync_state (job) VALUES ('orders-to-crm');

-- 1) Pull the delta: strictly greater than the watermark, so boundary rows are never fetched twice
SELECT o.id, o.updated_at
FROM orders o, sync_state s
WHERE s.job = 'orders-to-crm'
  AND o.updated_at > s.watermark
ORDER BY o.updated_at;

-- 2) Advance the watermark after the pull: GREATEST skips the NULL from an empty table and never moves backward
UPDATE sync_state
SET watermark = GREATEST(watermark, (SELECT max(updated_at) FROM orders))
WHERE job = 'orders-to-crm';

-- Assumption: updated_at is monotonic; rows committed between the pull and the watermark update are picked up next run, and downstream stays idempotent

What the code does

SELECT / INSERT / UPDATE / CREATE statements share the script, touching sync_state and orders.

Mechanically, the statements are built from: a WHERE clause that keeps only the rows a statement is meant to touch; MAX aggregation; 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.

Applying it

The sync_state table is the working surface here.

Statements that matter

UPDATE sync_state
SET watermark = GREATEST(watermark, (SELECT max(updated_at) FROM orders))
WHERE job = 'orders-to-crm';
SELECT o.id, o.updated_at
FROM orders o, sync_state s
WHERE s.job = 'orders-to-crm'
  AND o.updated_at > s.watermark
ORDER BY o.updated_at;
CREATE TABLE orders (
    id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
    updated_at timestamptz NOT NULL DEFAULT now()
);

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
`sync_state`, `orders`.