views:

3052

answers:

5

Hi

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? Karl

+2  A: 

Look at IsNull in SQL Server and Sybase. Use NVL in Oracle.

RichardOD
-1 Better look at count() instead
Andomar
@Andomar. As Karl hasn't described how he is doing the count (using a count function) or even what database is used, making the assumption that count is the correct answer is wrong. Presumably Karl is not using count as others have correctly pointed out in SQL Server at least this will return 0.
RichardOD
For example- Karl could be selecting a column NumberOfItems. If however Karl is using Count, then the question is incorrect.
RichardOD
A: 

Use:

ISNULL(count(*), 0)
ck
This would be valid if count(*) returned NULL for no records. However count(*) returns 0. So count(*) and ISNULL(count(*),0) are effectively the same.
Rashmi Pandit
+1  A: 

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 ?

streetpc
COALESCE also works for SQL Server
HLGEM
+2  A: 

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
Rashmi Pandit
That's a good point. In my answer I didn't make any assumptions as to how this count was done.
RichardOD
A: 

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.

GaZ
That's true, but there are usually better ways to abstract out DB difference that by writing non DB specific SQL.
RichardOD