sqlsql-servernullif

How can you use NULLIF in the where clause?


I am trying to do something like this:

select
     col_1, col_2, etc
from
     table
where
     col_1 = nullif('', '')

Am I doing this incorrectly? I am not getting any results back.

Edit:

My expected results are to get every record back where col_1 is NULL.

I know I can use where col_1 is null, but I am using SSIS and a variable. Sometimes the col_1 is actually NULL and sometimes it is not.

Sample data:

 collaboration     first_name     last_name          city     
          NULL            Bob         Smith       Chicago
Data Migration           John         Smith        Austin
          NULL           Pika           Chu       Houston
    Production            ash       ketchum         tokyo

Sometimes I may want to return the records where collaboration is NULL, sometimes I want to return the records where it says Production.

I'd like to use the same query, if possible, with little modification.

Edit Part 2:

I tried to experiment with this.

select
     col_1, col_2, etc
from
     table
where
     case
         when col_1  = '' then NULL
         else col_1
         end

But I am getting the error message:

An expression of non-boolean type specified in a context where a condition is expected, near ORDER.

Query speed it not something I am concerned with.


Solution

  • This is the query you need

    select
         col_1, col_2, etc
    from
         table
    where
         col_1 is null
    

    is null checks if a column is null, nullif(@expr1,@expr2) could be rewritten as:

    case when @expr1 = @expr2 return null else return @expr1 end
    

    EDIT: you can relax filters adding OR condition into the 'where' clause (TIP: remember AND is evaluated before OR)

    select
         col_1, col_2, etc
    from
         table
    where
         (col_1 is null OR col1 like 'production')
    

    if you want to decide runtime wich one you neeed you could write a procedure:

    create proc my_proc @var AS varchar(100) = 'NULL§159§' -- this defaults to null, if you put a parameter it queries with parameter passed
    as
    select
             col_1, col_2, etc
        from
             table
        where
             WHERE coalesce(col_1,'NULL§159§') = @var 
    -- added §159§ symbol to the null to make sure the queried string is impossible in the database, 
    -- obviously into the database the value 'NULL159' hase become a sort of 'reserved word', but hopefully is odd enough not to appear in data
    GO
    

    and call it by exec my_proc('production')