SQL NTILE, FIRST_VALUE and Named Windows
What you will learn
- How
NTILEsplits rows into equal groups - How
FIRST_VALUE,LAST_VALUEandNTH_VALUEwork - Why
LAST_VALUEneeds an explicit frame - How to name a window with
WINDOW
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.
1. NTILE: equal groups
NTILE(n) splits the ordered rows into n groups of (nearly) equal size and returns the group number. With 4 it gives quartiles; with 10, deciles:
SELECT name, price,
NTILE(4) OVER (ORDER BY price, product_id) AS price_quartile
FROM products
ORDER BY price, product_id
LIMIT 6;
name price price_quartile
------------ ----- --------------
Day backpack 4.5 1
Footrest 4.95 1
Glass jar 5.4 1
Steel pan 6.6 1
Wall planner 6.6 1
Sticky notes 7.65 1
(6 rows)
SELECT account_id, balance_cents,
NTILE(4) OVER (ORDER BY balance_cents, account_id) AS balance_quartile
FROM accounts
ORDER BY balance_cents, account_id
LIMIT 6;
account_id balance_cents balance_quartile
---------- ------------- ----------------
330 1300 1
23 2700 1
405 4300 1
331 4800 1
370 5300 1
426 6900 1
(6 rows)
SELECT code, credits,
NTILE(4) OVER (ORDER BY credits, course_id) AS credit_quartile
FROM courses
ORDER BY credits, course_id
LIMIT 6;
code credits credit_quartile
------- ------- ---------------
LANG102 2 1
HUM301 2 1
ART101 2 1
ART201 2 1
ART202 2 1
MATH201 3 2
(6 rows)
Group 1 holds the lowest values. Count the groups to check that they are even:
WITH t AS (SELECT NTILE(4) OVER (ORDER BY price, product_id) AS quartile FROM products)
SELECT quartile, COUNT(*) AS products FROM t GROUP BY quartile ORDER BY quartile;
quartile products
-------- --------
1 12
2 11
3 11
4 11
(4 rows)
WITH t AS (SELECT NTILE(4) OVER (ORDER BY balance_cents, account_id) AS quartile FROM accounts)
SELECT quartile, COUNT(*) AS accounts FROM t GROUP BY quartile ORDER BY quartile;
quartile accounts
-------- --------
1 113
2 113
3 112
4 112
(4 rows)
WITH t AS (SELECT NTILE(4) OVER (ORDER BY credits, course_id) AS quartile FROM courses)
SELECT quartile, COUNT(*) AS courses FROM t GROUP BY quartile ORDER BY quartile;
quartile courses
-------- -------
1 5
2 5
3 5
4 4
(4 rows)
When the rows do not divide evenly, the first groups get one row more.
2. FIRST_VALUE and NTH_VALUE
FIRST_VALUE(x) returns x from the first row of the frame, NTH_VALUE(x, n) from the n-th. They show the leader beside every row:
SELECT category_id, name, price,
FIRST_VALUE(name) OVER (PARTITION BY category_id ORDER BY price DESC, product_id) AS most_expensive
FROM products
WHERE category_id = 2
ORDER BY price DESC, product_id
LIMIT 4;
category_id name price most_expensive
----------- ---------------- ----- --------------
2 Tea kettle 79.0 Tea kettle
2 Ceramic mug 44.1 Tea kettle
2 Wooden spoon set 29.5 Tea kettle
2 Lunch box 29.5 Tea kettle
(4 rows)
SELECT branch_id, account_id, balance_cents,
FIRST_VALUE(account_id) OVER (PARTITION BY branch_id ORDER BY balance_cents DESC, account_id) AS richest_account
FROM accounts
WHERE branch_id = 1
ORDER BY balance_cents DESC, account_id
LIMIT 4;
branch_id account_id balance_cents richest_account
--------- ---------- ------------- ---------------
1 243 432800 243
1 165 428004 243
1 418 337200 243
1 425 325400 243
(4 rows)
SELECT department_id, code, credits,
FIRST_VALUE(code) OVER (PARTITION BY department_id ORDER BY credits DESC, course_id) AS heaviest_course
FROM courses
WHERE department_id = 1
ORDER BY credits DESC, course_id
LIMIT 4;
department_id code credits heaviest_course
------------- ------- ------- ---------------
1 MATH101 4 MATH101
1 MATH301 4 MATH101
1 MATH201 3 MATH101
(3 rows)
3. The LAST_VALUE trap
With the default frame (up to the current row) LAST_VALUE simply returns the current row's own value, which is useless. The frame must reach the end:
CREATE TABLE lib_scores (player TEXT, score INTEGER);
INSERT INTO lib_scores VALUES ('Ana', 10), ('Ben', 20), ('Cy', 30);
SELECT player, score,
LAST_VALUE(score) OVER (ORDER BY score) AS default_frame,
LAST_VALUE(score) OVER (ORDER BY score ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS whole_frame
FROM lib_scores ORDER BY score;
player score default_frame whole_frame
------ ----- ------------- -----------
Ana 10 10 30
Ben 20 20 30
Cy 30 30 30
(3 rows)
CREATE TABLE lib_scores (player TEXT, score INTEGER);
INSERT INTO lib_scores VALUES ('Ana', 10), ('Ben', 20), ('Cy', 30);
SELECT player, score,
LAST_VALUE(score) OVER (ORDER BY score) AS default_frame,
LAST_VALUE(score) OVER (ORDER BY score ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS whole_frame
FROM lib_scores ORDER BY score;
player score default_frame whole_frame
------ ----- ------------- -----------
Ana 10 10 30
Ben 20 20 30
Cy 30 30 30
(3 rows)
CREATE TABLE lib_scores (player TEXT, score INTEGER);
INSERT INTO lib_scores VALUES ('Ana', 10), ('Ben', 20), ('Cy', 30);
SELECT player, score,
LAST_VALUE(score) OVER (ORDER BY score) AS default_frame,
LAST_VALUE(score) OVER (ORDER BY score ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS whole_frame
FROM lib_scores ORDER BY score;
player score default_frame whole_frame
------ ----- ------------- -----------
Ana 10 10 30
Ben 20 20 30
Cy 30 30 30
(3 rows)
default_frame just repeats each row's own score; whole_frame gives the real last value (30). Alternatively, reverse the order and use FIRST_VALUE.
4. FILTER on a window aggregate
According to the SQLite documentation, a FILTER (WHERE ...) clause can be added to an aggregate window function to include only some rows in it. Here each row shows how many rows in the whole table meet a condition:
SELECT name, price,
COUNT(*) FILTER (WHERE price > 50) OVER () AS products_over_50
FROM products
ORDER BY product_id
LIMIT 3;
name price products_over_50
---------------- ----- ----------------
Steel pan 6.6 5
Ceramic mug 44.1 5
Wooden spoon set 29.5 5
(3 rows)
SELECT account_id, status,
COUNT(*) FILTER (WHERE status = 'frozen') OVER () AS frozen_accounts
FROM accounts
ORDER BY account_id
LIMIT 3;
account_id status frozen_accounts
---------- ------ ---------------
1 open 16
2 open 16
3 open 16
(3 rows)
SELECT code, credits,
COUNT(*) FILTER (WHERE credits >= 4) OVER () AS heavy_courses
FROM courses
ORDER BY course_id
LIMIT 3;
code credits heavy_courses
------- ------- -------------
MATH101 4 7
MATH201 3 7
MATH301 4 7
(3 rows)
5. A named window
If several window functions share the same window, define it once with WINDOW name AS (...) after FROM and refer to it by name:
SELECT category_id, name, price,
ROW_NUMBER() OVER w AS n,
RANK() OVER w AS r,
ROUND(AVG(price) OVER (PARTITION BY category_id), 2) AS category_avg
FROM products
WHERE category_id = 2
WINDOW w AS (PARTITION BY category_id ORDER BY price DESC, product_id)
ORDER BY n
LIMIT 4;
category_id name price n r category_avg
----------- ---------------- ----- - - ------------
2 Tea kettle 79.0 1 1 31.5
2 Ceramic mug 44.1 2 2 31.5
2 Wooden spoon set 29.5 3 3 31.5
2 Lunch box 29.5 4 4 31.5
(4 rows)
SELECT branch_id, account_id, balance_cents,
ROW_NUMBER() OVER w AS n,
RANK() OVER w AS r,
CAST(AVG(balance_cents) OVER (PARTITION BY branch_id) AS INTEGER) AS branch_avg
FROM accounts
WHERE branch_id = 1
WINDOW w AS (PARTITION BY branch_id ORDER BY balance_cents DESC, account_id)
ORDER BY n
LIMIT 4;
branch_id account_id balance_cents n r branch_avg
--------- ---------- ------------- - - ----------
1 243 432800 1 1 130962
1 165 428004 2 2 130962
1 418 337200 3 3 130962
1 425 325400 4 4 130962
(4 rows)
SELECT department_id, code, credits,
ROW_NUMBER() OVER w AS n,
RANK() OVER w AS r,
ROUND(AVG(credits) OVER (PARTITION BY department_id), 2) AS department_avg
FROM courses
WHERE department_id = 1
WINDOW w AS (PARTITION BY department_id ORDER BY credits DESC, course_id)
ORDER BY n
LIMIT 4;
department_id code credits n r department_avg
------------- ------- ------- - - --------------
1 MATH101 4 1 1 3.67
1 MATH301 4 2 2 3.67
1 MATH201 3 3 3 3.67
(3 rows)
Notice that the first RANK() here uses the tie-breaker too, so it equals ROW_NUMBER; define separate windows when you need a different ORDER BY.
6. You finished SQL Basics
Over eight chapters you went from reading a table to writing queries that need several steps:
| Chapter | You can now |
|---|---|
| 1 | read a database and write your first queries |
| 2 | filter and sort, and handle NULL |
| 3 | summarise data with GROUP BY |
| 4 | join tables and find missing rows |
| 5 | change data safely, with transactions and upserts |
| 6 | create tables with keys, rules, indexes and views |
| 7 | break a problem into subqueries and CTEs |
| 8 | calculate across rows with window functions |
Next steps: use the same ideas on a database you care about, learn the details of one database system (the dialects differ in small ways), and read the lessons of Database Fundamentals about design, performance and safety.
Worked example: customer quartiles
| Step | Do |
|---|---|
| 1 | total spent per customer in a CTE |
| 2 | NTILE(4) OVER (ORDER BY spent, customer_id) as quartile |
| 3 | GROUP BY quartile for count, average and total spent |
| 4 | quartile 4 holds the top spenders; compare its share of the total with its share of customers |
This kind of analysis uses most of the course. The steps are made up from the Shop sample.
Common mistakes
LAST_VALUEwith the default frame.- Reading
NTILEgroups as equal-valued instead of equal-sized. - Ties split between
NTILEgroups by the tie-breaker. - Repeating the same long window instead of naming it.
Key takeaways
NTILE(n)splits ordered rows intongroups of equal size.FIRST_VALUE,LAST_VALUEandNTH_VALUEread a row of the frame;LAST_VALUEneeds a frame that reaches the end.FILTER (WHERE ...)limits an aggregate window;WINDOW name AS (...)reuses a definition.- You now have the full toolkit of everyday SQL.
Practice
1. What does NTILE(4) produce?
Show answer
A group number from 1 to 4, splitting the ordered rows into four groups of nearly equal size.
2. Why does LAST_VALUE(x) OVER (ORDER BY x) return each row's own value?
Show answer
The default frame ends at the current row, so the last row of the frame is the current row.
3. How do you fix it?
Show answer
Use ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, or reverse the order and use FIRST_VALUE.
4. What does FIRST_VALUE(name) OVER (PARTITION BY category_id ORDER BY price DESC) show?
Show answer
The name of the most expensive product of the row's category, on every row.
5. When do you use a WINDOW clause?
Show answer
When several window functions share the same window definition.
6. Name two window functions from this chapter that need an ORDER BY.
Show answer
For example ROW_NUMBER, RANK, LAG, LEAD, NTILE, and FIRST_VALUE.