Lookahead Frame With ROWS FOLLOWING

A frame bounded by ROWS ... FOLLOWING looks only at rows after the current one, turning window aggregates into backlog and next-job lookahead.

SqlData Fetching

Code

snippet
-- ROWS BETWEEN n FOLLOWING AND m FOLLOWING:帧只含身后的行(不含当前行),
-- 适合“未来 n 行预报”型的前瞻(lookahead)汇总
CREATE TEMP TABLE queue_times (
    job    text NOT NULL,
    est_ms int NOT NULL
);

INSERT INTO queue_times VALUES
    ('render', 120),
    ('transcode', 800),
    ('thumbnail', 90),
    ('upload', 45);

SELECT
    job,
    est_ms,
    -- 后 3 行的预估总和:排在当前任务之后的积压;队尾行帧为空,结果为 NULL
    sum(est_ms) OVER (
        ORDER BY job
        ROWS BETWEEN 1 FOLLOWING AND 3 FOLLOWING
    ) AS backlog_after,
    -- 后续第一行的任务名:下一个要跑什么
    first_value(job) OVER (
        ORDER BY job
        ROWS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING
    ) AS next_job
FROM queue_times
ORDER BY job;

How it works

What runs here is SELECT / INSERT / CREATE — queue_times are the objects involved.

queue_times is created in this same file as session-local temp tables — nothing needs to exist beforehand, and it goes away at session end.

In terms of clauses, the statements use: SUM aggregation; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.

Watch out for

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Using it

It carries its own setup: the session-local tables in play (queue_times) come from the file’s statements — run the entire file against a disposable database.

Key statements

SELECT
    job,
    est_ms,
    sum(est_ms) OVER (
        ORDER BY job
        ROWS BETWEEN 1 FOLLOWING AND 3 FOLLOWING
    ) AS backlog_after,
    first_value(job) OVER (
        ORDER BY job
        ROWS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING
    ) AS next_job
FROM queue_times
ORDER BY job;
INSERT INTO queue_times VALUES
    ('render', 120),
    ('transcode', 800),
    ('thumbnail', 90),
    ('upload', 45);
CREATE TEMP TABLE queue_times (
    job    text NOT NULL,
    est_ms int NOT NULL
);

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
The references are `queue_times`.