Window Functions

ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, running totals and moving averages: calculations across related rows that keep every row in the result.

Overview

A window function computes a value for each row from a set of related rows, called its window. Unlike GROUP BY, it does not collapse the rows: every input row stays in the result and gains a new column. That is why window functions answer questions like 'rank within each department', 'change since yesterday' and 'running total', which are among the most common SQL interview questions.

The sample tables

The examples use two small tables. There are six employees, with a salary tie in Eng, and five sales, with two on the same day and no sale on January 3. The tie and the gap are what make the functions below differ. All the SQL on this page runs on PostgreSQL.

Interview questions

  • What is the difference between ROW_NUMBER, RANK and DENSE_RANK?
  • How do you compute a running total and a 7-day moving average?
  • How do you find streaks of consecutive days?

Sign up free to read the full topic

More Databases & SQL topics

Start free on Cariara · Coding problems · System design studio