β¨ Programming
Easy
SQL Aggregates
Loyal Customers With 3+ Orders
Question
Find customers who have placed 3 or more orders. Return their full name, email, and order count.
Join customers and orders, then use HAVING.
Solution
SELECT
c.first_name || ' ' || c.last_name AS customer_name,
c.email,
COUNT(o.order_id) AS order_count
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.first_name, c.last_name, c.email
HAVING COUNT(o.order_id) >= 3
ORDER BY order_count DESC;
Explanation: JOIN customers to orders, GROUP BY customer, COUNT their orders. HAVING filters to those with 3 or more.