SQL LEFT JOIN return 0 rather than NULL
Question
I want to join two tables, with the number of records for each type being counted. If there are no records of that type in the left table I want a 0 to be returned, not a null.
How can I do this?
Solution
Use:
ISNULL(count(*), 0)
OTHER TIPS
I am not sure if I have understood your exact problem, but in sqlserver on a left join, you will get a count as 0 if your query is something like this:
select t1.id, count(t2.id)
from table1 t1
left outer join table2 t2
on t1.id = t2.id
group by t1.id
ISNULL(nullable, value_if_null)
for MsSQL, COALESCE(nullable1, nullable2, ..., value_if_null)
for MySQL.
Edit:
As I'm told, COALESCE
works for both, so I'd choose that to replace NULL
columns.
Now I think that COUNT()
ing NULL
values returns 0
in MySQL too, so I agree with Rashmi. Could you show us the query and the wanted result ?
You can use "CASE"
SELECT T1.NAME, CASE WHEN T2.DATA IS NULL THEN 0 ELSE T2.DATA END
FROM T1 LEFT JOIN T2 ON T1.ID = T2.ID
COALESCE is more cross-compatible than ISNULL or NVL (it works on MSSQL, Oracle, MySQL, Derby, et al.). But I am not sure about the performance differences.
COALESCE(XXX, 0)
E.g.
SELECT branch1_id, branch1_name, COALESCE(devnum, 0) FROM
branch1 as S LEFT JOIN view_inner_zj_devnum as B ON S.branch1_id = B.bid1 GROUP BY branch1_id;
That works for me.