Can someone please help me understand the following behavior that occurs when I add a WHERE clause to a query that has a LEFT JOIN with COUNT (*)?
I have two tables:
TABLE 1: customers customer_id | name ------------------ 1 | Bob 2 | James 3 | Fred TABLE 2: orders order_id | customer_id | order_timestamp ---------------------------------------- 1000 | 1 | 2011-01-01 00:00 1001 | 1 | 2011-01-05 00:00 1002 | 2 | 2011-01-10 00:00
Now the following request tells me how many orders each customer placed:
select c.customer_id, count(o.order_id) from customers c left join orders o using (customer_id) group by 1 customer_id | count
This works fine, but if I add a WHERE clause to the query, the query no longer displays the number of zeros for customers who did not place any orders, even if I do LEFT JOIN:
select c.customer_id, count(o.order_id) from customers c left join orders o using (customer_id) where o.order_timestamp >= '2011-01-05' group by 1 customer_id | count
Now, if I move the WHERE clause as part of the LEFT JOIN, as shown below, I will return my zero counter for customers who did not place orders:
select c.customer_id, count(o.order_id) from customers c left join orders o on (c.customer_id = o.customer_id) and (o.order_timestamp >= '2011-01-05') group by 1
I am confused by why the second request does not work, but the third does? Can someone please give me an explanation? Also not sure if that matters, but I'm using postgres. Thanks!
Deadmonkey
source share