Write a query to find all customers who placed orders in every month of 2025.

Answer

Find customers whose count of distinct order months in 2025 equals 12 - meaning they have at least one order in every calendar month.

Solution

SELECT customer_id
FROM Orders
WHERE YEAR(order_date) = 2025
GROUP BY customer_id
HAVING COUNT(DISTINCT MONTH(order_date)) = 12;

Step by Step

  1. Filter to only orders placed during 2025 with WHERE YEAR(order_date) = 2025.
  2. Group the remaining rows by customer_id.
  3. COUNT(DISTINCT MONTH(order_date)) counts how many unique calendar months each customer ordered in.
  4. HAVING keeps only customers whose distinct month count is exactly 12 - every month covered.

Alternative Method: Using a Calendar Table

SELECT o.customer_id
FROM Orders o
JOIN (SELECT DISTINCT MONTH(order_date) AS mth FROM Orders WHERE YEAR(order_date) = 2025) all_months
  ON MONTH(o.order_date) = all_months.mth
WHERE YEAR(o.order_date) = 2025
GROUP BY o.customer_id
HAVING COUNT(DISTINCT all_months.mth) = (SELECT COUNT(DISTINCT mth) FROM (SELECT DISTINCT MONTH(order_date) AS mth FROM Orders WHERE YEAR(order_date) = 2025) x);

This variant is useful when the requirement is "every month that had any order activity across all customers," rather than a hardcoded 12 - a more defensive pattern if the data might not actually span a full calendar year.

Key Exam Traps

  • COUNT vs COUNT(DISTINCT): Using plain COUNT(MONTH(order_date)) instead of COUNT(DISTINCT ...) would count repeat orders in the same month multiple times, inflating the count past 12 incorrectly - though since 12 is a ceiling here, this specific bug would actually make it harder, not easier, to reach exactly 12, so watch for it producing under-counts if used with a wrong comparison operator.
  • Hardcoding 12 silently breaks if the business only has, say, 10 months of data available - always sanity-check what "every month" means against the actual data range.
  • Time zones: If order_date is stored as a timestamp, orders near midnight can shift months depending on the server's time zone - worth clarifying in a real interview.
Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.