Querydrill

SQL CASE WHEN practice problems

CASE is the IF of SQL. It labels rows (small, medium, large), protects a division, and inside SUM or COUNT it turns one pass over the table into several columns, which is how a pivot is written.

The problems cover labels, conditional counts and sums, and the order of the WHEN branches, where the first match wins.

Try one here: Label with CASE

Try it yourself

Return each order id with a label: large when the amount is 150 or more, otherwise small.

orders (first 12 of 14 rows)

idcustomer_idorder_dateamountstatus
10112025-01-03120paid
10212025-01-2080.5paid
10322025-01-22200paid
10432025-02-0245refunded
10532025-02-15310paid
10642025-02-18150pending
10752025-03-0160paid
10862025-03-0995paid
10962025-03-30130paid
11062025-04-1175paid
11172025-04-12210paid
11212025-04-2540paid

Free, no account needed. PostgreSQL runs in your browser and your answer is checked again on changed data.

Basics

  • Label with CASEReturn each order id with a label: large when the amount is 150 or more, otherwise small.

Aggregation

  • Paid and refunded per customerFor each customer_id that has orders, return the customer_id, the number of paid orders and the number of refunded orders, in that order. A customer with no refunds shows 0.
  • Share of paid ordersWhat percentage of all orders have the status paid? Return a single number, rounded to 1 decimal.
  • Salary bandsPut every employee in a salary band: junior below 70,000, mid from 70,000 up to but not including 100,000, senior at 100,000 or more. Return each band name and how many employees are in it.

Interview classics

  • Pivot the statusesReturn one row with three columns: the number of paid orders, refunded orders and pending orders, in that order.
  • Repeat purchase rateOf all customers who placed at least one order, what percentage placed two or more orders, whatever the status? Return a single number rounded to 1 decimal.
  • Cohort retentionGroup customers by the month of their first order, like 2025-01, counting every order whatever the status. For each such month return the month, the number of customers who first ordered in it, and how many of those customers ordered again in a later month.
  • Merge bookings into occupied periodsFor each room, merge bookings that overlap or touch (one ends on the day the next starts) into one occupied period. Return the room, the first check_in and the last check_out of every period.

Case studies

Read first if you are stuck

Other practice sets

Your first 8 exercises are free, with no account. Every answer is checked on the rows you see and again on changed data.