The order the database runs a query in decides what each clause can see.
Predict
Can WHERE filter on a window function's result in the same SELECT?
The database runs the parts of a query in this order:
The order the database runs a query inInteractive
→
→
→
→
FROM orders.
Two things follow. First, a window can rank a GROUP BY result in the same SELECT. Here it ranks the users by how many orders they placed:
SELECT user_id, COUNT(*) AS orders, RANK() OVER (ORDER BY COUNT(*) DESC) AS orders_rankFROM ordersGROUP BY user_idORDER BY orders_rank, user_id;
user_id
orders
orders_rank
1
3
1
2
2
2
3
1
3
4
1
3
Users 3 and 4 both placed one order, so they share rank 3. The ranking chapter covers ties.
Second, WHERE runs before the window exists, so it can't filter on one. SQLite rejects this query with misuse of aliased window function rn:
SELECT order_id, ordered_on, ROW_NUMBER() OVER (ORDER BY ordered_on, order_id) AS rnFROM ordersWHERE rn <= 2;
Compute the window in a CTE or a subquery, and filter outside it. A CTE, short for common table expression, is a named subquery written first, as WITH name AS (...), that the main query reads like a table. The ranking chapter does exactly that.
Some warehouses add a QUALIFY clause that filters on a window's result directly. SQLite has none, and there it's a syntax error.
In the editor, write SPEND_RANK: the users ranked by total spend in one SELECT, the biggest spender first.
Pick an answer above to see the rest
Instructions
1
Write SPEND_RANK: one row per user with user_id, spend and spend_rank, 1 for the biggest spender. Order by spend_rank.
2
The window runs after GROUP BY, so it can order by SUM(amount).