Start learning free

LESSON 46 OF 66 · SQL: INTERVIEW QUESTIONS

Cancellation Rate per Month in Python

Practice

An interviewer asks: "What share of each month's orders were cancelled?" A rate is an average of 0s and 1s. Give each order a 1 if it was cancelled and a 0 if not, and the average is the share of cancelled orders. Times 100, it is a percent.

Here is the same idea on another question, the share of products that cost under 10:

SELECT ROUND(AVG(CASE WHEN price < 10 THEN 1.0 ELSE 0 END) * 100, 1) AS cheap_share
FROM products

Keep the ELSE 0. Without it, the CASE gives NULL for the other rows and AVG skips NULLs, so every month with a cancelled order would show 100. The 1.0 keeps the average a decimal in every database, and ROUND(…, 1) keeps one decimal.

The hidden setup adds four June orders to the shop, so there are four months to compare:

id | customer_id | ordered    | status
8  | 1           | 2026-06-02 | paid
9  | 4           | 2026-06-09 | cancelled
10 | 3           | 2026-06-16 | paid
11 | 2           | 2026-06-24 | shipped

Your query must print:

month | orders | cancel_rate
2026-03 | 2 | 0
2026-04 | 2 | 0
2026-05 | 3 | 33.3
2026-06 | 4 | 25
(4 rows)

Your task: in query, select each order's month with strftime('%Y-%m', ordered), COUNT(*) named orders, and the cancellation rate as a percent rounded to 1 decimal, named cancel_rate. Read them FROM orders and make one group per month.


Assignment
Follow the Coding Tutorial to build the query one clause per line: the month and the count, the rate, FROM and GROUP BY.


Hint
The average of 0, 1, 0, 0 is 0.25: one cancelled order out of four. Multiply by 100, then round to 1 decimal.


STEP 1 OF 4
    Ctrl + Enter to check

    Sqlq Cancel Rate in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free