Skip to content
Advertisement

Joining table which may not exist with where clause

I have two tables. Let’s say they are:

table customers: id, name
table orders: id, customer_id, is_finished(boolean), order_sum 

I’d like to make a join to get customer name, number of orders which he/she has finished and sum of money which he/she has spent in total

So I’m making this SQL query:

SELECT c.name,
       coalesce(count(o.id), 0)      AS orders_count,
       coalesce(sum(o.order_sum ), 0) AS total_spent
FROM customers c
         LEFT OUTER JOIN orders o on c.id = o.user_id
WHERE c.id = customer_id
  AND o.is_finished = true
GROUP BY c.name;

If a customer has any finished orders then it will get everything right.

|'John'|3|150|

But if there are no orders or there are orders which are not finished it will not output anything. But my desired output is the following:

|'John'|0|0|

So what is the right way to make such a query so that I’m able to get a result even if a customer has no orders?

I’m using postgreSQL btw

Advertisement

Answer

Just move the condition on the LEFT JOINed table from the WHERE clause to the ON clause of the LEFT JOIN – otherwise it becomes mandatory, and filters out customers that have no matching orders:

SELECT c.name,
    count(o.id)                    AS orders_count,
    coalesce(sum(o.order_sum ), 0) AS total_spent
FROM customers c
LEFT OUTER JOIN orders o ON c.id = o.user_id AND o.is_finished = true
WHERE c.id = customer_id
GROUP BY c.id, c.name;
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement