GimmeJob
Sign in
Databases, SQL & BI · SQL · Chapter 09 / 17

SQL learning path

Window functions

Window functions calculate across related rows without collapsing them into one row per group. That makes them ideal for ranking, latest-row selection, running balances, comparisons with previous events, and analytics.

OVER and PARTITION BY

SQL
SQLite · sample DB · browser sandbox
Result
Run the query to see the result.

Every employee remains visible while the department average is repeated for the relevant partition.

ROW_NUMBER, RANK, and DENSE_RANK

ROW_NUMBER gives a unique sequence. RANK leaves gaps after ties. DENSE_RANK does not leave gaps.

SQL
SQLite · sample DB · browser sandbox
Result
Run the query to see the result.

Choose based on the business meaning of ties.

Top N per group

A classic SQL task is “top two employees in each department.” Calculate a row number inside each department, then filter in an outer query.

SQL
SQLite · sample DB · browser sandbox
Result
Run the query to see the result.

LAG and LEAD

LAG accesses a previous row in window order; LEAD accesses a following row. This is useful for event transitions and detecting gaps.

SQL
SQLite · sample DB · browser sandbox
Result
Run the query to see the result.

Running totals

SQL
SQLite · sample DB · browser sandbox
Result
Run the query to see the result.

Specify the frame explicitly when cumulative semantics matter; default frames can surprise you when ordering values tie.

Latest row per entity

Window functions are one of the cleanest solutions to “latest event per entity.” Rank each entity's rows by timestamp descending and keep rn = 1.

Execution-order implication

Window functions are evaluated after WHERE/GROUP BY/HAVING. You normally cannot filter directly on a window alias in WHERE; use a subquery or CTE, as shown in the top-N example.

Practice: return the latest status for each entity from events, resolving equal timestamps by the highest id.

Source registry

3 chapter references · Under review
PostgreSQL 18 — Window Functions

Primary reference for OVER, PARTITION BY, window ordering, ranking, running calculations, and the difference between windows and aggregation.

PostgreSQL Global Development Group · official documentation
Source ↗
PostgreSQL 18 — Queries

Detailed reference for FROM/WHERE/GROUP BY/HAVING, set operations, sorting, LIMIT/OFFSET, CTEs, recursive queries, and query processing.

PostgreSQL Global Development Group · official documentation
Source ↗
SQLite — SELECT

Runtime-aligned reference for SELECT grammar and behavior in the in-browser SQLite practice environment.

SQLite · official documentation
Source ↗