Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL LEFT JOIN return 0 rather than NULL

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?

like image 270
Karl Avatar asked Jun 24 '09 10:06

Karl


People also ask

Does LEFT join return NULL?

The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.

How do you change the NULL values in a join?

For Oracle you can use: NVL(columnName,deafultValue) :- NVL is used to convert a null value to a default value in the query output. eg. If you want to replace null values with 'NA' then use something like this.

What does a LEFT join return?

The LEFT JOIN command returns all rows from the left table, and the matching rows from the right table. The result is NULL from the right side, if there is no match.

Does join ignore NULL values?

Null values in tables or views being joined never match each other. Since bit columns do not permit null values, a value of 0 appears in an outer join when there is no match for a bit column in the inner table. The result of a join of null with any other value is null.


2 Answers

Use:

ISNULL(count(*), 0) 
like image 115
cjk Avatar answered Sep 24 '22 23:09

cjk


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 
like image 37
kaiyasit phanmakorn Avatar answered Sep 23 '22 23:09

kaiyasit phanmakorn