Subqueries, CTEs and window functions
These are what make long questions readable. The tables here hold a small shop: customers, products and orders.
● A real database, running in your browser. Nothing you type leaves this page.
Exercise 1 of 6
A query inside a query
A subquery in brackets runs first, and its result is used by the outer query.
Your task
Show the name and price of the products that cost more than the average price.
Tables and columns
or Ctrl+Enter
What you'll practice
- A query inside a query. A subquery in brackets runs first, and its result is used by the outer query.
- IN a subquery. A subquery can give a list, for use with
IN. - Value of an order. You can calculate inside
SUM. Here each line is worth itsquantitytimes itsunit_price. - Name a step with WITH.
WITHgives a subquery a name, known as a CTE. A long query then reads from top to bottom, one step at a time. - Label with CASE.
CASEchooses a value by condition, as an "if" inside a query. - Rank inside a group. A window function calculates across rows, and keeps them all, unlike
GROUP BY.ROW_NUMBER() OVER (PARTITION BY … ORDER BY …)numbers the rows inside each group.