Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return 1 instead of 0 when Count(*) result is Null

My code from SQL Server:

SELECT ESTAGIO.SK_ESTAGIO, ISNULL(count(ESTAGIO.SK_ESTAGIO), 0) as how_many
 from ESTAGIO
 left join ESTAGIARIO
 on ESTAGIARIO.SK_ESTAGIO = ESTAGIO.SK_ESTAGIO
 group by
    ESTAGIO.SK_ESTAGIO

When "ESTAGIO.SK_ESTAGIO" doesn't exist in the table "ESTAGIARIO" it returns 1 instead of 0, I already tried to use ISNULL(), NULLIF() and COALESCE() and still couldn't find the problem that is making the query above returning 1 when it should be 0.

like image 589
Leandro Batista Avatar asked Mar 10 '23 00:03

Leandro Batista


1 Answers

You are counting the wrong field. Do it like this, taking the field from the outer joined table ESTAGIARIO (not from ESTAGIO):

SELECT ESTAGIO.SK_ESTAGIO, Count(ESTAGIARIO.SK_ESTAGIO) as how_many
 from ESTAGIO
 left join ESTAGIARIO
 on ESTAGIARIO.SK_ESTAGIO = ESTAGIO.SK_ESTAGIO
 group by
    ESTAGIO.SK_ESTAGIO

BTW, count can never return null.

like image 100
trincot Avatar answered Mar 12 '23 04:03

trincot