Start learning free

LESSON 32 OF 66 · SQL: INTERVIEW QUESTIONS

Customers Who Came Back in Python

Practice

An interviewer asks: which customers came back? Here it means they have orders in at least two different months. Counting orders isn't enough: two orders in the same month are not a comeback. You count the different months of each customer's orders.

Months and DISTINCT: strftime('%Y-%m', ordered) turns a date into its year and month, so '2026-05-07' becomes '2026-05'. COUNT(DISTINCT …) counts each value once. The count belongs to a group, so the test goes in HAVING, which can repeat the same COUNT(DISTINCT …). Here is the idea on another question, the products bought in at least two different orders:

SELECT product_id, COUNT(DISTINCT order_id) AS orders
FROM order_items
GROUP BY product_id
HAVING COUNT(DISTINCT order_id) >= 2

For this lesson the shop has one more order, added before your code runs: order 8, Dan Weber, 2026-05-25, paid. Dan now has two orders, but both are in May. Ben Ortiz ordered in March and in May, but his May order was cancelled, so it doesn't count. Your script must print:

name | order_count | months
Ana Pop | 2 | 2
Chloe Ng | 2 | 2
(2 rows)

Your task: the starter's query is empty. Write it one clause per line: select the name, COUNT(*) as order_count and the number of different months as months; read FROM orders joined with customers; leave out the cancelled orders; group by customers.id; and keep the customers with orders in 2 or more different months.


Assignment
Follow the Coding Tutorial to write the query one clause per step, from the SELECT to the HAVING.


Hint
Cancelled orders go in WHERE, before the groups form. The month test goes in HAVING, after them: >= 2 on the same COUNT(DISTINCT strftime('%Y-%m', ordered)) as the months column.


STEP 1 OF 6
    Ctrl + Enter to check

    Sqlq Repeat Customers 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