Keep every row while comparing it with its window

Use partitions, deterministic order and explicit frames for ranking, running totals and per-group comparisons without collapsing rows. Windows, views and conditional aggregates · Databases.

Each report row may need its team average, rank, and running total. GROUP BY can collapse rows you still need to inspect; a window calculation adds context while keeping each row visible.

Keep rows while comparing a team

Read the steps as text

  1. team_scores(team,employee_id,employee,score,recorded_on,active) has six active rows in Platform and Support. account_transactions(account_id,transaction_id,posted_on,amount) adds three account-7 rows.
  2. The average is computed inside each team while the employee columns remain available. A grouped average would emit one row per team instead.
  3. Score DESC-only ranking keeps Asha and Ben as peers. Transactions 201/202 share 2026-10-05; 203 is 2026-10-06. The next step compares default RANGE over posted_on ASC with cumulative ROWS ordered by posted_on ASC, transaction_id ASC.
  4. The two 2026-10-05 transactions are peers under a date-only default RANGE order. An explicit ROWS frame ordered by date and transaction_id advances one row at a time.
  5. Date-only RANGE includes both first-date peers, producing 17, 17, 26. Date-and-id ROWS advances individually, producing 10, 17, 26.

The first frame uses team_scores(team, employee_id, employee, score, recorded_on, active) with six rows: Asha and Ben are in Platform with score 90 on the same day, Cora is in Platform with 80, and Dev, Ema and Faye are in Support with scores 95, 95 and 88; all six rows have active = true. Compare an average over a partition with a grouped average. The cards show the rows that survive WHERE active = true; no query result is hidden behind the visual.

SELECT employee, team, score,
       avg(score) OVER (PARTITION BY team) AS team_average
FROM team_scores
WHERE active = true;

The point is row preservation. The average repeats for each member of a team because it describes the comparison set while the employee columns remain present. A GROUP BY team query would answer a different question by returning one row per team.

Keep the row and define its comparison set

PARTITION BY divides the rows visible to the query into comparison sets. It does not remove rows. If the report has five employees in two departments, a window expression still has five output rows. Each employee sees only the rows in the same partition for that expression. Leaving out PARTITION BY makes the whole filtered result one partition, which can be correct for a company-wide comparison and surprising when a per-team answer was intended.

ORDER BY inside OVER defines the calculation and comparison order. It is independent of the final presentation order of the query. A final ORDER BY can make the report readable, but it does not change which rows a window function compares. Apply the ordinary WHERE predicate first: a row removed by WHERE is not available to the window. This is why a “top performers among active employees” question filters active employees before ranking them.

Rank ties deliberately

row_number() assigns positions within each partition. With a score-only window order, rank() gives score peers the same rank and leaves gaps after a tie. dense_rank() also gives score peers the same rank but does not leave gaps. Peers are rows in the same partition tied on every expression in the window ORDER BY. If the report asks for “third place” and ties should share a place, rank and dense_rank express that policy; row_number is a different policy.

A unique tie-breaker matters when the requirement is one deterministic row at each position. Keep the score-only ORDER BY score DESC for rank() and dense_rank() when ties are meaningful; use ORDER BY score DESC, employee_id separately for row_number() when employee_id is unique and a deterministic position is required. Without the tie-breaker, PostgreSQL can still number tied rows, but the assignment among peers is not a meaningful business distinction. Do not quietly turn a tie into a winner merely because a function returns a number.

The same scene now ranks the score within each team. Under score-only ordering, Asha and Ben share rank 1; Cora follows at rank 3 with rank() and rank 2 with dense_rank(). Dev and Ema share rank 1 in Support. A separate row_number() ordering by score and employee id assigns distinct positions to each tie. Name the tie policy before reading the number.

Make a running boundary visible

An ordered aggregate such as sum(amount) OVER (PARTITION BY account_id ORDER BY posted_on) has a frame. In PostgreSQL, the default with ORDER BY is a RANGE frame from the partition start through the current row, and it includes following peers whose ordering values equal the current row. If two transactions share the same posted_on, the default running total can advance across both transactions at the same date. That is a peer-group boundary, not a row-by-row boundary.

When the requested meaning is “include this row and all earlier rows in a deterministic sequence,” write the frame explicitly:

sum(amount) OVER (
  PARTITION BY account_id
  ORDER BY posted_on, transaction_id
  ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
)

The unique transaction_id makes the sequence visible, while ROWS makes the frame count individual rows in the specified window order. If the business meaning is “all transactions through this date,” the peer-inclusive behavior may be exactly right; the frame should match that sentence instead of being left to a default the reader has to remember.

The frame step introduces account_transactions(account_id, transaction_id, posted_on, amount): account 7 has transaction 201 for 10 on 2026-10-05, transaction 202 for 7 on the same date, and transaction 203 for 9 on 2026-10-06. The date-only default produces 17 for both same-day rows, then 26. The explicit date-and-id ROWS frame produces 10, 17, then 26.

Filter after the window

Window functions are evaluated after WHERE, GROUP BY and HAVING, and PostgreSQL permits them in the SELECT list and ORDER BY, not in the same query level's WHERE. To keep the top two employees per team, compute row_number() in a derived table, then filter its alias outside:

SELECT employee, team, score
FROM (
  SELECT employee, team, score,
         row_number() OVER (
           PARTITION BY team ORDER BY score DESC, employee_id
         ) AS position
  FROM team_scores
  WHERE active = true
) ranked
WHERE position <= 2;

The inner query defines the eligible population and the calculation order. The outer query consumes the labeled result. This is the subquery boundary from the prerequisite lesson applied to a window result; it is not a promise about a particular execution plan.

Rank events inside each account

Read the steps as text

  1. The source schema is account_events(account_id, event_id, occurred_on, amount). Account 7 has events 701 and 702 on the same date, then 703 on the next date. Account 8 has events 801 and 802. Event id supplies a stable tie-breaker.
  2. The calculation orders each account by occurred_on ASC,event_id ASC; the running frame is ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. The duplicate date is resolved by the visible id.
  3. With an explicit ROWS frame, the first account-7 event contributes 10 and the next event adds 4. The ranked derived result exposes a position alias for an outer WHERE position <= 2.
  4. The position alias is created in the derived result, so the outer query can keep positions at most two.
  5. Each account has a deterministic event order, a row-preserving position and an outer boundary for selecting the first two.

The faded scenario uses account_events(account_id, event_id, occurred_on, amount) with two accounts, duplicate timestamps, and a stable event id. Follow the first two events per account and the explicit running balance. For the balance, use ORDER BY occurred_on, event_id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW; the balance after the first account-7 event is 10. The dataset changes the labels but preserves the reasoning: comparison set, tie policy, frame boundary, then outer filter.

Recap

  • A window expression adds context to each surviving row while GROUP BY changes the result shape.
  • PARTITION BY, ordered peers and an explicit ROWS frame make comparison and accumulation boundaries visible.
  • Compute window positions before filtering them in an outer query, and state the tie policy.
Go deeper

PostgreSQL 18 documents lag, lead, first_value, last_value, nth_value, ordered aggregates and named WINDOW clauses. They belong after the row-preserving model is clear. Null ordering, exclusion frames, and performance plans need separate lessons; this lesson does not promise that a window query has a particular physical plan.

Next Views and materialized views: carry a derived result into a named query boundary, then decide whether that boundary stays live or serves a refreshed snapshot. For a DSA connection, Heap Fundamentals models repeatedly selecting the best score from a group; keep SQL's tie policy explicit.