Window Functions · Lesson 57 of 64

SQL Window Functions: OVER

What you will learn

  • What a window function is and what OVER does
  • How to show a total or average beside every row
  • How to compute a share and a difference
  • How it differs from GROUP BY

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Run the cells from top to bottom. Window functions need SQLite 3.25 or later (2018); the browser's SQLite is newer.

1. GROUP BY collapses rows

GROUP BY turns many rows into one row per group (lesson 3.2). Sometimes you want the summary and the original rows:

SELECT COUNT(*) AS products, ROUND(AVG(price), 2) AS avg_price FROM products;
products  avg_price
--------  ---------
      45      29.16
(1 row)
SELECT COUNT(*) AS accounts, CAST(AVG(balance_cents) AS INTEGER) AS avg_balance FROM accounts;
accounts  avg_balance
--------  -----------
     450       138220
(1 row)
SELECT COUNT(*) AS courses, ROUND(AVG(credits), 2) AS avg_credits FROM courses;
courses  avg_credits
-------  -----------
     19         3.11
(1 row)

One row. To see each product next to the average you needed a subquery (lesson 7.1). A window function does it directly.

2. OVER: a window of rows

Add OVER () after an aggregate and it is computed over a window of rows, but the rows are kept. An empty OVER () means "all rows":

SELECT name, price,
       ROUND(AVG(price) OVER (), 2) AS avg_price,
       ROUND(price - AVG(price) OVER (), 2) AS above_average
FROM products
ORDER BY product_id
LIMIT 5;
name              price  avg_price  above_average
----------------  -----  ---------  -------------
Steel pan           6.6      29.16         -22.56
Ceramic mug        44.1      29.16          14.94
Wooden spoon set   29.5      29.16           0.34
Glass jar           5.4      29.16         -23.76
Chopping board     26.4      29.16          -2.76
(5 rows)
SELECT account_id, balance_cents,
       CAST(AVG(balance_cents) OVER () AS INTEGER) AS avg_balance,
       balance_cents - CAST(AVG(balance_cents) OVER () AS INTEGER) AS above_average
FROM accounts
ORDER BY account_id
LIMIT 5;
account_id  balance_cents  avg_balance  above_average
----------  -------------  -----------  -------------
         1         192400       138220          54180
         2          52078       138220         -86142
         3          62780       138220         -75440
         4          99900       138220         -38320
         5         153100       138220          14880
(5 rows)
SELECT code, credits,
       ROUND(AVG(credits) OVER (), 2) AS avg_credits,
       ROUND(credits - AVG(credits) OVER (), 2) AS above_average
FROM courses
ORDER BY course_id
LIMIT 5;
code     credits  avg_credits  above_average
-------  -------  -----------  -------------
MATH101        4         3.11           0.89
MATH201        3         3.11          -0.11
MATH301        4         3.11           0.89
SCI101         4         3.11           0.89
SCI201         4         3.11           0.89
(5 rows)

Every row keeps its own values and also shows the average of all rows. The LIMIT shows five rows, but the average was computed over the whole table first.

3. Share of the total

A window SUM gives each row's share:

SELECT name, stock,
       SUM(stock) OVER () AS total_stock,
       ROUND(100.0 * stock / SUM(stock) OVER (), 1) AS percent_of_stock
FROM products
ORDER BY stock DESC, product_id
LIMIT 5;
name            stock  total_stock  percent_of_stock
--------------  -----  -----------  ----------------
Ceramic mug       150         2469               6.1
Watering can      150         2469               6.1
Plant pot         150         2469               6.1
Seed tray         150         2469               6.1
Pruning shears    150         2469               6.1
(5 rows)
SELECT account_id, balance_cents,
       SUM(balance_cents) OVER () AS total_balance,
       ROUND(100.0 * balance_cents / SUM(balance_cents) OVER (), 2) AS percent_of_total
FROM accounts
ORDER BY balance_cents DESC, account_id
LIMIT 5;
account_id  balance_cents  total_balance  percent_of_total
----------  -------------  -------------  ----------------
       398         502080       62199130              0.81
       243         432800       62199130               0.7
       165         428004       62199130              0.69
       238         401600       62199130              0.65
       295         379900       62199130              0.61
(5 rows)
SELECT section_id, capacity,
       SUM(capacity) OVER () AS total_seats,
       ROUND(100.0 * capacity / SUM(capacity) OVER (), 1) AS percent_of_seats
FROM sections
ORDER BY capacity DESC, section_id
LIMIT 5;
section_id  capacity  total_seats  percent_of_seats
----------  --------  -----------  ----------------
         6        35         1210               2.9
        12        35         1210               2.9
        13        35         1210               2.9
        20        35         1210               2.9
        22        35         1210               2.9
(5 rows)

Window functions are calculated after WHERE and GROUP BY, and before ORDER BY and LIMIT. So the total above covers all rows that pass the WHERE, not just the five shown.

4. Where they may be used

Window functions may appear only in the SELECT list and in ORDER BY. To filter on a window result, put the query in a subquery or a CTE (lesson 7.5) and filter outside:

Products priced above the overall average, using a window function:

WITH priced AS (
    SELECT name, price, AVG(price) OVER () AS avg_price FROM products
)
SELECT name, price FROM priced WHERE price > avg_price ORDER BY price DESC LIMIT 3;
name          price
------------  -----
Water bottle   86.9
Tea kettle     79.0
Highlighters   79.0
(3 rows)

Accounts with a balance above the overall average, using a window function:

WITH balances AS (
    SELECT account_id, balance_cents, AVG(balance_cents) OVER () AS avg_balance FROM accounts
)
SELECT account_id, balance_cents FROM balances WHERE balance_cents > avg_balance ORDER BY balance_cents DESC, account_id LIMIT 3;
account_id  balance_cents
----------  -------------
       398         502080
       243         432800
       165         428004
(3 rows)

Courses with more credits than the overall average, using a window function:

WITH weights AS (
    SELECT code, credits, AVG(credits) OVER () AS avg_credits FROM courses
)
SELECT code, credits FROM weights WHERE credits > avg_credits ORDER BY credits DESC, code LIMIT 3;
code     credits
-------  -------
CS201          4
CS301          4
MATH101        4
(3 rows)

5. Window or GROUP BY

Need Use
one row per group GROUP BY
every row, plus a group value beside it window function
a filter on the group value HAVING or a CTE

Worked example: how far from the average

Step Do
1 keep each row: SELECT name, price
2 add the average beside it: AVG(price) OVER ()
3 subtract: price - AVG(price) OVER ()
4 to keep only the large gaps, wrap it in a CTE and filter outside

The next lessons add PARTITION BY (a window per group) and ORDER BY inside the window. The columns are from the Shop sample.

Common mistakes

  • Using a window function in WHERE.
  • Forgetting OVER, which turns it into a plain aggregate.
  • Expecting LIMIT to change the window. The window sees all rows first.
  • Integer division in a share: use 100.0 *.

Key takeaways

  • A window function calculates across rows but keeps every row.
  • aggregate(...) OVER () puts a total or average beside each row.
  • Windows are calculated after WHERE and GROUP BY, before ORDER BY and LIMIT.
  • To filter on a window result, use a CTE or subquery.

Practice

1. What does OVER () with nothing inside mean?

Show answer

The window is all the rows of the result.

2. Write the share of each price in the total price.

Show answer

100.0 * price / SUM(price) OVER ()

3. Where can a window function not be used?

Show answer

In WHERE (and GROUP BY/HAVING); use a CTE and filter outside.

4. How does a window function differ from GROUP BY?

Show answer

It keeps every row instead of collapsing each group to one row.

5. Does LIMIT 5 change the average from AVG(price) OVER ()?

Show answer

No. The window is calculated before LIMIT, over all the rows.

6. What turns AVG(price) into a window function?

Show answer

Adding OVER (...) after it.