Library

SQL that runs

Window functions you can write without looking anything up, and the habit of reading generated SQL for the bug before trusting it.

Practice questions

10
SQL window functions
  1. 1.In Denver, listings 21 and 22 both earn 200, behind listing 20 at 270. You rank with RANK() OVER (PARTITION BY city ORDER BY revenue DESC) and keep rank <= 2. What comes back for Denver?
  2. 2.Guest 2 has booking 3 on 2026-01-04 and booking 5 on 2026-01-02. The window orders by booking_id alone. What does the days-to-second-booking query return for guest 2?
  3. 3.You add AND days IS NOT NULL to the outer WHERE of the days-to-second-booking query. What changes?
  4. 4.Austin's daily counts are 1 on January 1, 1 on January 2, 3 on January 4 and 1 on January 9. What does SUM(n) OVER (ORDER BY julianday(booked_on) ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) give for January 9?
  5. 5.The window orders by julianday(booked_on). Which frame counts January 3 through January 9 for the row dated January 9?
Explain and fix AI-generated SQL
  1. 1.After joining orders to their item lines, a teammate patches the inflated numbers with COUNT(DISTINCT o.order_id) and SUM(DISTINCT o.total_cents). What's still wrong?
  2. 2.Every customer and their March order count, 0 for none. You move the date filter from WHERE into the LEFT JOIN's ON clause but keep COUNT(*). What does a customer with no orders get?
  3. 3.SELECT code FROM promos WHERE code NOT IN (SELECT promo FROM orders) returns nothing, though one code was never used. Why?
  4. 4.Two of five orders used a promo. In SQLite, what does SELECT COUNT(promo) / COUNT(*) * 1.0 FROM orders return?
  5. 5.placed_at holds text like '2026-03-31 20:30'. Which March orders does WHERE placed_at BETWEEN '2026-03-01' AND '2026-03-31' miss?