No ORDER BY Frames Whole Partition

Without ORDER BY every row in the partition is a peer and the default frame is the whole partition, so aggregates report totals instead of running sums.

SqlData Integrity

Code

snippet
-- 没写 ORDER BY 时窗口内所有行互为 peers,默认 frame 是整个分区(whole partition):
-- 聚合给出全分区总计;写了 ORDER BY 默认帧才变成“起点到当前行”的累计
CREATE TEMP TABLE shots (
    player text NOT NULL,
    points int NOT NULL
);

INSERT INTO shots VALUES
    ('ada', 2), ('ada', 3), ('ada', 5),
    ('lin', 1), ('lin', 4);

SELECT
    player,
    points,
    -- 无 ORDER BY:默认帧 = 整个分区,sum 是全队总分
    sum(points) OVER (PARTITION BY player) AS team_total,
    -- 有 ORDER BY:默认帧 = UNBOUNDED PRECEDING 到当前行,变成累计
    sum(points) OVER (PARTITION BY player ORDER BY points) AS running_total,
    -- rank 不看帧,两种写法结果一致(全为 peers 时都是 1)
    rank() OVER (PARTITION BY player) AS rank_no_order
FROM shots
ORDER BY player, points;

The structure at work

The file runs SELECT / INSERT / CREATE statements, touching shots.

shots gets created within this file as a session-bound temp table — nothing before it, nothing after the session.

Mechanically, the statements are built from: SUM aggregation; a window function (OVER (…)) aggregating across the partition while every row stays in place; 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 (shots) come from the file’s statements — run the entire file against a disposable database.

Key statements

SELECT
    player,
    points,
    sum(points) OVER (PARTITION BY player) AS team_total,
    sum(points) OVER (PARTITION BY player ORDER BY points) AS running_total,
    rank() OVER (PARTITION BY player) AS rank_no_order
FROM shots
ORDER BY player, points;
INSERT INTO shots VALUES
    ('ada', 2), ('ada', 3), ('ada', 5),
    ('lin', 1), ('lin', 4);
CREATE TEMP TABLE shots (
    player text NOT NULL,
    points int NOT NULL
);

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
The references are `shots`.