Window Functions

Updated · 9 min read
hardPostgreSQL 18sqlwindow-functionsoverpartition-byanalyticsinterview

A window function in SQL is a function that calculates a value from a set of rows related to the current row, and returns that value on every row, without collapsing the rows into groups. It is used to put a summary next to the detail: each payment beside its student's total, each fee beside the average fee, each score beside its rank. GROUP BY answers "what is each student's total?" with one row per student; a window function answers it while keeping all seven payment rows. In this lesson, we will learn the OVER clause step by step, PARTITION BY, aggregate functions used as window functions, and how window functions differ from GROUP BY.

In One Minute

  • A window function is followed by OVER (...), which says which rows it looks at.
  • OVER () uses every row; OVER (PARTITION BY col) uses the rows with the same col.
  • Every row stays in the result; the function's answer is written beside each one.
  • sum, avg, count, min and max all work as window functions.
  • Window functions run after WHERE and GROUP BY, so they can't be used in WHERE.

Syntax

SQL
function_name(expression) OVER (
  [PARTITION BY column, ...]
  [ORDER BY column, ...]
  [frame]
)
PartMeaning
OVER ()The window is every row of the result
PARTITION BYSplit the rows into groups; each row's window is its own group
ORDER BYOrder the rows inside each window (needed for rankings and running totals)
frameNarrow the window to nearby rows; covered in Running Totals, LAG and LEAD

Step 1: OVER () Writes One Total on Every Row

The following query shows each payment, and beside it the total of all payments:

SQL▶ Try it
SELECT payment_id, student_id, amount_usd,
       sum(amount_usd) OVER () AS all_payments
FROM payments
ORDER BY payment_id;
Output
 payment_id | student_id | amount_usd | all_payments
------------+------------+------------+--------------
          1 |        101 |     450.00 |      2150.00
          2 |        101 |     250.00 |      2150.00
          3 |        101 |     250.00 |      2150.00
          4 |        101 |     550.00 |      2150.00
          5 |        101 |     200.00 |      2150.00
          6 |        103 |     225.00 |      2150.00
          7 |        103 |     225.00 |      2150.00
(7 rows)

Explanation: sum(amount_usd) OVER () adds up the amount over the window, and the empty parentheses make the window every row. All seven rows are kept, and each one carries the same total, $2,150.00. With plain sum(amount_usd) and no OVER, the seven rows would collapse into one.

Step 2: PARTITION BY Gives Each Row Its Own Group

PARTITION BY student_id makes each row's window the rows of the same student. Each payment, with its student's total and its share of that total:

SQL▶ Try it
SELECT payment_id, student_id, amount_usd,
       sum(amount_usd) OVER (PARTITION BY student_id) AS student_total,
       round(100 * amount_usd / sum(amount_usd) OVER (PARTITION BY student_id), 1) AS pct_of_student
FROM payments
ORDER BY payment_id;
Output
 payment_id | student_id | amount_usd | student_total | pct_of_student
------------+------------+------------+---------------+----------------
          1 |        101 |     450.00 |       1700.00 |           26.5
          2 |        101 |     250.00 |       1700.00 |           14.7
          3 |        101 |     250.00 |       1700.00 |           14.7
          4 |        101 |     550.00 |       1700.00 |           32.4
          5 |        101 |     200.00 |       1700.00 |           11.8
          6 |        103 |     225.00 |        450.00 |           50.0
          7 |        103 |     225.00 |        450.00 |           50.0
(7 rows)

Explanation: Srihitha's five payments form one partition, with a total of $1,700.00, and Navika's two form another, with $450.00. Each row shows its own partition's total. Because the detail and the total are on the same row, we can compute a percentage directly: payment 4 is 32.4% of everything Srihitha has paid.

Every row is kept: OVER () writes 2150.00 on all of them; PARTITION BY writes each student's own total

Aggregates as Window Functions

Any aggregate function becomes a window function when it is followed by OVER.

FunctionOver the window, returns
sum(x) OVER (...)The total
avg(x) OVER (...)The average
count(*) OVER (...)The number of rows
min(x) OVER (...), max(x) OVER (...)The smallest and largest

The following query shows several of them on each payment:

SQL▶ Try it
SELECT payment_id, student_id, amount_usd,
       count(*) OVER (PARTITION BY student_id) AS student_payments,
       round(avg(amount_usd) OVER (PARTITION BY student_id), 2) AS student_avg,
       max(amount_usd) OVER (PARTITION BY student_id) AS student_max
FROM payments
ORDER BY payment_id;
Output
 payment_id | student_id | amount_usd | student_payments | student_avg | student_max
------------+------------+------------+------------------+-------------+-------------
          1 |        101 |     450.00 |                5 |      340.00 |      550.00
          2 |        101 |     250.00 |                5 |      340.00 |      550.00
          3 |        101 |     250.00 |                5 |      340.00 |      550.00
          4 |        101 |     550.00 |                5 |      340.00 |      550.00
          5 |        101 |     200.00 |                5 |      340.00 |      550.00
          6 |        103 |     225.00 |                2 |      225.00 |      225.00
          7 |        103 |     225.00 |                2 |      225.00 |      225.00
(7 rows)

Explanation: Each row now carries facts about its whole partition: Srihitha has 5 payments averaging $340.00, with a largest of $550.00. Comparing a row with these numbers, such as "is this payment above the student's average?", needs no correlated subquery.

Window Functions vs GROUP BY

The same totals, by GROUP BY and by a window function:

SQL▶ Try it
SELECT student_id, sum(amount_usd) AS total
FROM payments
GROUP BY student_id
ORDER BY student_id;
Output
 student_id |  total
------------+---------
        101 | 1700.00
        103 |  450.00
(2 rows)
FeatureGROUP BYWindow function
Rows in the resultOne per groupEvery input row
Detail columns (like payment_id)Not allowed unless groupedAllowed
Typical useSummariesSummary beside detail, rankings, running totals
Where it runsBefore SELECTInside SELECT, after GROUP BY
GROUP BY turns seven payments into two rows; sum() OVER (PARTITION BY) keeps all seven with the total beside each

Where Window Functions Can Go

Window functions are calculated in the SELECT step, after WHERE, GROUP BY and HAVING. So they can't appear in WHERE:

SQL▶ Try it
SELECT payment_id, amount_usd
FROM payments
WHERE amount_usd > avg(amount_usd) OVER ();
Output
ERROR:  window functions are not allowed in WHERE

To filter on a window function's result, compute it in a subquery or CTE, then filter outside:

SQL▶ Try it
WITH with_avg AS (
  SELECT payment_id, amount_usd, avg(amount_usd) OVER () AS avg_all
  FROM payments
)
SELECT payment_id, amount_usd
FROM with_avg
WHERE amount_usd > avg_all
ORDER BY payment_id;
Output
 payment_id | amount_usd
------------+------------
          1 |     450.00
          4 |     550.00
(2 rows)

Explanation: The CTE writes the overall average on every row; the outer query can then compare each amount with it. Window functions are supported by PostgreSQL, MySQL 8.0 and later, SQL Server, Oracle and SQLite 3.25 and later.

FROM, WHERE, GROUP BY, HAVING, then window functions in SELECT, then ORDER BY

Common Mistakes

Expecting fewer rows. A window function keeps every row; use GROUP BY for one row per group.

Using a window function in WHERE or HAVING. It isn't computed yet. Filter in an outer query.

Forgetting PARTITION BY. OVER () is the whole result, not each student.

Leaving out ORDER BY in the outer query. OVER (ORDER BY ...) orders the window, not the result rows.

Interview Corner

What is a window function?

A function that computes a value over a set of rows related to the current row, defined by OVER (...), and returns it on every row without collapsing them.

What's the difference between GROUP BY and a window function?

GROUP BY returns one row per group. A window function returns every row, with the group's value beside each, so detail and summary appear together.

What does PARTITION BY do?

It divides the rows into groups for the window function; each row's window is the rows in its own group.

Practice

Challenge: For each course, show its title, technology, fee, and the average fee of its technology (rounded to cents), sorted by technology and title.

Show solution
SQL▶ Try it
SELECT title, technology, fee_usd,
       round(avg(fee_usd) OVER (PARTITION BY technology), 2) AS technology_avg
FROM courses
ORDER BY technology, title;
Output
       title       | technology | fee_usd | technology_avg
-------------------+------------+---------+----------------
 Git Basics        | Git        |  250.00 |         250.00
 Java Basics       | Java       |  450.00 |         500.00
 Java Collections  | Java       |  550.00 |         500.00
 Java OOP          | Java       |  500.00 |         500.00
 JavaScript Basics | JavaScript |  450.00 |         450.00
 SQL Basics        | SQL        |  400.00 |         400.00
(6 rows)

The three Java courses share a technology average of $500.00; every other technology has a single course, so its average is its own fee.

Quick check: Window functions

3 questions
1payments has 7 rows. How many rows does SELECT payment_id, sum(amount_usd) OVER () FROM payments return?
2What does PARTITION BY student_id do in sum(amount_usd) OVER (PARTITION BY student_id)?
3Why does WHERE amount_usd > avg(amount_usd) OVER () fail?

Key Takeaways

You want toWrite
A grand total on every rowsum(amount_usd) OVER ()
Each student's total on every rowsum(amount_usd) OVER (PARTITION BY student_id)
Share of the student's totalamount_usd / sum(amount_usd) OVER (PARTITION BY student_id)
Filter on itcompute in a CTE, then WHERE outside

Was this tutorial helpful?

Lesson 64 of 115