SQL practice: generate_series and LATERAL: Rows From Nothing
Chapter 39 · 9 questions · included in full access
Question 1 · easy
Solve it in your browserProduce the numbers 1 to 12 in a column named month_number.
Question 2 · easy
Solve it in your browserProduce the first day of every month from January 2024 to June 2024 inclusive, in a column named month.
Question 3 · medium
Solve it in your browserCount orders in every month from January to June 2024, including months with none. Show month formatted as YYYY-MM and a count named orders, ordered by month.
Question 4 · medium
Solve it in your browserFor every branch, show its two most recent orders. Return branch_name, order_id and order_date, ordered by branch_name then order_date descending. Use LATERAL.
Question 5 · medium
Solve it in your browserDo the same again, but keep branches that have no orders at all, showing NULLs for them. Return branch_name, order_id and order_date, ordered by branch_name then order_date descending.
Question 6 · medium
Solve it in your browserFor every branch show its name and the value of its single largest order line, computed by a LATERAL subquery. Name the column biggest_line, ordered by branch_name. Branches with no orders should not appear.
Question 7 · medium
Solve it in your browserExpand order 1 so that each item appears once per unit ordered — 50 sheets become 50 rows. Return order_id and product_id only, ordered by product_id. Use generate_series.
Question 8 · hard
Solve it in your browserWhy does a plain (non-LATERAL) subquery in FROM fail when it references a column from a table listed beside it?
Question 9 · hard
Solve it in your browserFind each customer's streaks of consecutive active months using the gaps-and-islands technique. First, find distinct customer_id and month numbers (1 to 12) from orders. In a second CTE, calculate an island group by subtracting ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY mo) from the month number. Return customer_id, start_month (minimum month of the streak), end_month (maximum month of the streak), and streak_length (count of months in the streak). Order by customer_id, start_month.
These questions are part of full access.
The first chapters of every track are free. Full access is a one-time payment.
See pricing