Skip to content
Advertisement

Joining table which may not exist with where clause

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

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:

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

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:

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:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement