Search⌘ K

Joins with Aggregate Functions

Explore how to use SQL joins combined with aggregate functions to accurately count unique customers who have placed orders. Learn to apply count with distinct and understand efficient query design by reducing costly joins.

Let’s start answering some more complex queries.

How many customers do we have with orders?

Suppose that we had a lot of customers with lots of orders. Some customers are referred to as leads because they haven’t yet placed an order. So, we have customers that have orders and customers that don’t have an order.

How can we count the customers that have orders?

We tried the following query earlier:

mysql> select * from customers join orders on orders.customer_id = customers.id;
+----+-----------+----------+----+--------------+---------------------+-------------+
| id | name      | identity | id | order_number | ordered_at          | customer_id |
+----+-----------+----------+----+--------------+---------------------+-------------+
|  4 | John Woo  | JW001    |  2 | ABC001       | 2016-09-12 21:36:56 |           4 |
|  5 | Maria
...