Module 3 · SQL: Getting Data Out of Databases · Lesson 11 of 51

Subqueries, CTEs, window functions and dates

Queries inside queries, readable WITH blocks, ranking and running totals with window functions, month-over-month growth, and the top-N-per-group interview classic.

In this lesson · about 45 minutes

  • Break a hard question into steps with a CTE (WITH)
  • Rank rows and compute running totals with window functions
  • Group by month with date functions

Subqueries

A query in brackets can feed another: SELECT * FROM orders WHERE total > (SELECT AVG(total) FROM orders) finds above-average orders.

CTEs

WITH monthly AS (
  SELECT branch, strftime('%Y-%m', date) AS month, SUM(total) AS revenue
  FROM orders
  GROUP BY branch, month
)
SELECT * FROM monthly WHERE revenue > 2000;

Dates: SQLite's strftime('%Y-%m', date) gives "2026-03"; PostgreSQL uses DATE_TRUNC('month', date), and SQL Server FORMAT or DATEPART. The idea is the same everywhere.

Window functions

An aggregate with OVER (…) keeps every row:

  • ROW_NUMBER() OVER (PARTITION BY branch ORDER BY total DESC): number the rows 1, 2, 3 within each branch, biggest first.
  • RANK() gives ties the same rank; DENSE_RANK() doesn't skip numbers after ties.
  • SUM(revenue) OVER (PARTITION BY branch ORDER BY month): a running total.
  • LAG(revenue) OVER (PARTITION BY branch ORDER BY month): last month's value on this month's row. LEAD looks ahead.

PARTITION BY is like GROUP BY for windows: it restarts the count for each group.

The interview classic: top N per group

WITH ranked AS (
  SELECT branch, item, SUM(total) AS revenue,
         ROW_NUMBER() OVER (PARTITION BY branch ORDER BY SUM(total) DESC) AS rn
  FROM orders GROUP BY branch, item
)
SELECT branch, item, revenue FROM ranked WHERE rn <= 2;

Month-over-month growth with LAG

Exercise

Best-selling item at each branch

For each branch, return the single item with the highest total revenue and that revenue (rounded to 2 decimals) as revenue. Return columns branch, item, revenue, sorted by branch. Use a CTE with ROW_NUMBER().

Code that runs before yours
import sqlite3
import pandas as pd
con = sqlite3.connect(":memory:")
pd.read_csv("kc_orders.csv").to_sql("orders", con, index=False)
q = lambda sql: pd.read_sql_query(sql, con)

Exercise

Running total for Riverside

For 'Riverside', return month (as 'YYYY-MM'), monthly revenue rounded to 2 decimals as revenue, and the running total of revenue so far as running (rounded to 2 decimals), in month order.

Code that runs before yours
import sqlite3
import pandas as pd
con = sqlite3.connect(":memory:")
pd.read_csv("kc_orders.csv").to_sql("orders", con, index=False)
q = lambda sql: pd.read_sql_query(sql, con)

Flashcards

Module 3 flashcards

0 of 9 known

Say the answer out loud, flip the card, then be honest: cards you miss come back at the end.

9 left in the deck

Practice exam

Module 3 checkpoint

10 questions, 12 minutes.

  • 10 questions · 12 minutes
  • No feedback until you submit. Flag questions to come back to them.
  • Aim for 85% or better before you move on. The real exam's 750 out of 900 is roughly 80–83%.

Exercises solved: 0 of 2

Tip: solve each exercise first. Press Check to test your code.

Written by Noviq Academy in its own words. Kettle & Crumb and all its data are made up for teaching; any resemblance to a real business is a coincidence. Python runs in your browser with Pyodide, so results can differ slightly from your own computer. Power BI, Tableau and other product names belong to their owners. Read-aloud uses your device's built-in voices.