AI Hints
Home›PostgreSQL Tutorial›Window Functions
PostgreSQL · Lesson 31 of 120

Window Functions

Calculations across rows.

⏱ 2 min read▶ Video at 26:57🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Group by squashes rows into one per group. But sometimes you want to keep every row, and still see a group number next to it, like each book's price beside its genre's average. That's a window function.

  • Keep every row
  • Plus a group number
  • OVER

Price vs genre average

Avg price over partition by genre averages the price within each book's genre, without squashing the rows. Then we subtract to see how far each book is from the average. Run it. Every cooking and tech book, next to its genre average.

query.sqlsql
SELECT title, genre, price,
       round(avg(price) OVER (PARTITION BY genre), 2) AS genre_avg,
       price - round(avg(price) OVER (PARTITION BY genre), 2) AS diff
FROM books
WHERE genre IN ('Cooking', 'Technology')
ORDER BY genre, price DESC;
Output
          title           |   genre    | price | genre_avg | diff
--------------------------+------------+-------+-----------+-------
 Spice Roads              | Cooking    | 27.99 |     24.82 |  3.17
 The Quiet Kitchen        | Cooking    | 24.99 |     24.82 |  0.17
 One Pan Dinners          | Cooking    | 21.49 |     24.82 | -3.33
 Python for Curious Minds | Technology | 34.99 |     32.32 |  2.67
 Data for Everyone        | Technology | 31.99 |     32.32 | -0.33
 SQL in a Weekend         | Technology | 29.99 |     32.32 | -2.33
(6 rows)

The OVER clause

Over turns an aggregate into a window function. Partition by splits rows into groups. Order by inside over sets an order, for running totals and ranks. And an empty over uses every row.

keyvalue
OVER ()all rows
PARTITION BYgroups
ORDER BYrunning order
Rows keptno squashing

Summary

Window functions calculate across related rows, but keep every row. Next, ranking within groups.

Key takeaways
  • OVER
  • PARTITION BY
  • Keep rows
Next up: Top N per Group — ranks inside groups