Windows I — ranking & offsets
Concept  ·  SQL & Querying

DISTINCT applies after window functions compute — surprising duplicates or collapses result.

Logical order, third verse: windows run with SELECT (after WHERE and GROUP BY, before DISTINCT and ORDER BY) — the same sequence that made QUALIFY necessary. Consequences run both ways: any per-row window defeats DISTINCT silently; and 'DISTINCT then window' can't be one flat query (the window would see pre-dedup rows) — it needs subquery staging. The tell: 'DISTINCT stopped working when I added a column' — the column was a window.

See it break
p
color
teal
teal
The trap
SELECT DISTINCT
  color,
  ROW_NUMBER() OVER () AS rn
FROM
  p
  ORDER BY
  rn;
The fix
SELECT
  color,
  ROW_NUMBER() OVER () AS rn
FROM
  (
    SELECT DISTINCT
      color
    FROM
      p
  )
ORDER BY
  rn;
The trap
teal1
teal2
The fix
teal1

Adding ROW_NUMBER kept both identical 'teal' rows — windows compute before DISTINCT, so the row number made the duplicates unique and DISTINCT found nothing to collapse; staging the dedup first fixes it.

The rule

Stage it — a subquery for whichever runs first by intent; never DISTINCT across a per-row window and expect collapse.

Shows up elsewhere
Top-N per groupDISTINCT vs GROUP BY vs DISTINCT ON vs QUALIFY
Try one →Prove it in practice →