Compare NULL using CASE SQL

Asked

Viewed 26,028 times

2

I have to recover 2 fields in this query (number of projects and the management that runs such a project). This query will be used to generate a report in JASPER and it does not display field with value NULL, so I want every null in the column f.br_nome_ger_executo the query returns "manage not informed". This query is working, but displays the null in the response to the consultation.

select  count(i.is_active) NUMERO_PROJETOS,
case f.br_nome_ger_executo
      when null then 'Gerencia nao informada'
      else f.br_nome_ger_executo end as GERENCIA_EXECUTORA
from inv_investments i
join odf_ca_project f on i.id = f.id  and i.is_active = 1
group by f.br_nome_ger_executo

I made a test with the acronym of one of the management and it returns the text correctly.

I appreciate the help.

1 answer

6


To compare a null value you must use it in WHEN with IS NULL:

SELECT COUNT(i.is_active) AS NUMERO_PROJETOS,
       CASE
         WHEN f.br_nome_ger_executo IS NULL THEN 'Gerencia nao informada'
         ELSE f.br_nome_ger_executo
       END AS GERENCIA_EXECUTORA
  FROM inv_investments i
 INNER JOIN odf_ca_project f
    ON i.id = f.id
   and i.is_active = 1
 GROUP BY f.br_nome_ger_executo

Another way to get the desired result is to use the function ISNULL:

SELECT COUNT(i.is_active) AS NUMERO_PROJETOS,
       ISNULL(f.br_nome_ger_executo, 'Gerencia nao informada') AS GERENCIA_EXECUTORA
  FROM inv_investments i
 INNER JOIN odf_ca_project f
    ON i.id = f.id
   AND i.is_active = 1
 GROUP BY f.br_nome_ger_executo

ISNULL

Replaces NULL with the specified replacement value.


Here you give a brief explanation of why the initial solution did not work: Why NULL values are not selected?

  • It worked! Thank you very much. I’ve only been an intern for a month and I came to use is null in many ways and gave an error of "from not found, out of place". So much so that I got this first code half discredited. Why did this one take and not mine ? haha Uppercase sql reserved words can have relation ? Thank you very much.

  • @Jessépereira I am happy that the answer helped you. Do not forget to mark the answer as chosen in the green "V". As for the case of words, it depends on the collation of your database, but usually in SQL Server makes no difference

  • Does this ISNULL function exist in oracle? Gave a google and vi only in mysql and sql server.

  • @Jessépereira in Oracle does not exist ISNULL, but you can replace it with COALESCE, which has the same principle but can receive more than two parameters and returns the first non-null

Browser other questions tagged

You are not signed in. Login or sign up in order to post.