Round Robin Sharding With Row Number
Assign queue rows to worker slots by taking ROW_NUMBER modulo the worker count, with a partitioned variant that balances within each region.
Code
-- 把待处理行轮转分给 4 个 worker:全局 ROW_NUMBER 取模,
-- 分配确定、不重不漏,重跑结果一致
WITH numbered AS (
SELECT
id,
payload,
ROW_NUMBER() OVER (ORDER BY id) AS rn
FROM import_queue
)
SELECT
id,
payload,
rn % 4 AS worker_slot -- 槽位 0..3
FROM numbered
ORDER BY rn;
-- 分组内轮转:每个 region 各自从 0 起编号,各自均匀分派
WITH numbered AS (
SELECT
id,
region,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY id) AS rn
FROM import_queue
)
SELECT region, rn % 3 AS worker_slot, count(*) AS assigned
FROM numbered
GROUP BY region, rn % 3
ORDER BY region, worker_slot;How it works
Several statements share this file — SELECT, with import_queue and numbered among the objects involved.
Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; COUNT aggregation; a GROUP BY that collapses matching rows into one output row per group; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.
What to watch for
- Remember the evaluation order:
WHEREfirst, window functions later — filtering on the latter needs another query level.
Applying it
The import_queue table is the working surface here.
Statements that matter
WITH numbered AS (
SELECT
id,
region,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY id) AS rn
FROM import_queue
)
SELECT region, rn % 3 AS worker_slot, count(*) AS assigned
FROM numbered
GROUP BY region, rn % 3
ORDER BY region, worker_slot;
WITH numbered AS (
SELECT
id,
payload,
ROW_NUMBER() OVER (ORDER BY id) AS rn
FROM import_queue
)
SELECT
id,
payload,
rn % 4 AS worker_slot -- 槽位 0..3
FROM numbered
ORDER BY rn;
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.
FAQ
- What objects does the SQL involve?
- The references are `import_queue`, `numbered`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.