×

sql · level 3 · unit 3 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Windows run after WHERE, so filter them in an outer query.

You write SELECT first, but the database has its own : FROM and WHERE, then GROUP BY and HAVING, then window functions, then SELECT, ORDER BY and LIMIT.

So a WHERE cannot test a window's answer, because the window has not been worked out yet. Try it and SQLite stops with misuse of aliased window function.

The fix is a pattern you will use for ever. Number the rows inside a CTE, then filter in the main query. Here it finds each customer's biggest order.

WITH ranked AS (
  SELECT customer_id, id, total,
    ROW_NUMBER() OVER (
      PARTITION BY customer_id ORDER BY total DESC, id
    ) AS n
  FROM orders
)
SELECT customer_id, id, total
FROM ranked
WHERE n = 1
ORDER BY customer_id;

Change n = 1 to n <= 3 and you get the top three in every group.