Search code examples
sqlpostgresqlcase

Not equals when using CASE statement in SQL


In postgresql, I have a case statement that I need to add a "not equals" clause.

When v1 equals v2, I want it to say 1, when v1 DOES NOT EQUAL v2, I would like to say 2.

create table test (
v1      varchar(20),
v2      varchar(20)
);

insert into test values ('Albert','Al'),('Ben','Ben')

select case v1
when v2 then 1
    else 3
end 
from test

I tried using != or <>, but that does not seem to work.

Does anyone have any idea how to use not equals in a case statement in SQL?


Solution

  • You could always just be more explicit with your case statement. Here's an example...

        select 
          case when v1 = v2 then 1
           when v1 <> v2 then 2
          end
        from test