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
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.
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.
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.
Run the query to see the result.
Running totals
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.