SQL window functions

Window functions calculate across a set of rows related to the current row without collapsing them, unlike GROUP BY. You keep every row and add a column such as a rank, a running total or a group average.

The OVER clause defines the window: PARTITION BY splits rows into groups, ORDER BY sets the order inside each group.

Syntax

FUNCTION() OVER (
  PARTITION BY group_col
  ORDER BY order_col
)

Try it yourself

Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.

window-functions.sql · PostgreSQL
Loading editor…

Examples

1. Group total on every row

SELECT first_name, department_id, salary, SUM(salary) OVER (PARTITION BY department_id) AS dept_total FROM employees WHERE department_id IS NOT NULL;

Each employee alongside their department total.

2. Share of total

SELECT category, name, price, ROUND(100 * price / SUM(price) OVER (PARTITION BY category), 1) AS pct_of_category FROM products;

Each product's share of its category.

Common mistakes

  • Filtering on a window function in WHERE. Window functions run after WHERE; use a subquery or CTE.

Practice: test yourself

This challenge is from our interactive course. Write the query and press Check answer.

Challenge · 30 pts

For each employee with a department, return first_name, last_name, salary and the total salary of their department.

challenge.sql · PostgreSQL
Loading editor…

FAQ

Are window functions asked in interviews?

Very often. ROW_NUMBER, RANK, LAG and running totals are standard data-analyst interview topics.

Learn SQL step by step

65 hands-on exercises, streaks, a leaderboard and a certificate.

Start free →