Setting a default value on NULL columns from LEFT JOIN and filtering using WHERE Setting a default value on NULL columns from LEFT JOIN and filtering using WHERE sql sql

Setting a default value on NULL columns from LEFT JOIN and filtering using WHERE


Aliases don't generally apply in the WHERE clause - try COALESCE(purchases_count,0) AS purchases_count_2 with where purchases_count_2 < 10 to see what I mean.

where COALESCE(purchases_count,0) < 10 should work.


Instead of counting the purchases in a separate query, just group the main query instead. To filter on the count, put that in a having caluse:

select i.name, coalesce(sum(s.unit_sales), 0) as purchases_countfrom items ileft join sales s on s.item_name = i.uidgroup by i.namehaving purchases_count < 10


How about:

WHERE (purchases_count < 10) OR (purchases_count IS NULL)

of course, you'd still be left with null values, but you can still try the COALESCE option to turn those nulls into zeroes for later usage.