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.

SqlData Integrity

Code

snippet
-- 把待处理行轮转分给 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: WHERE first, 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

FAQ

What objects does the SQL involve?
The references are `import_queue`, `numbered`.