Windows II — frames & running
Concept  ·  SQL & Querying

A WINDOW clause names a window definition once — every OVER can reuse it, so clones can't silently disagree.

Windowed reports repeat the same OVER four times, and repetition is where definitions drift — one clone loses the ORDER BY (silently switching frame semantics), another partitions by one fewer column. Naming the window makes the definition single-sourced: WINDOW w AS (PARTITION … ORDER …), then OVER w everywhere — and variations are declared variations (OVER (w ROWS …)).

See it break
runs
gdx
m110
m220
m35
The trap
SELECT
  d,
  SUM(x) OVER (
    PARTITION BY
      g
    ORDER BY
      d
  ) AS run_sum,
  COUNT(*) OVER (
    PARTITION BY
      g
    ) AS run_cnt
FROM
  runs
ORDER BY
  d;
The fix
SELECT
  d,
  SUM(x) OVER w AS run_sum,
  COUNT(*) OVER w AS run_cnt
FROM
  runs
WINDOW
  w AS (
    PARTITION BY
      g
    ORDER BY
      d
  )
ORDER BY
  d;
INPUTYour queryThe fix
11031
23032
33533

The copy-pasted running count quietly lost its ORDER BY, so run_cnt read the grand total 3 on every row instead of 1, 2, 3 — a named WINDOW defines the window once, so the two columns can't disagree.

The rule

WINDOW clause for any query with ≥2 same-window columns; extend the named base for frame variants.

Standard SQL, in DuckDB/Postgres/MySQL 8; absent in some engines — the discipline degrades to a checked copy-paste block with a comment.

Shows up elsewhere
Default frame includes peer tiesRunning total resets by PARTITION BY
Try one →Prove it in practice →