Home > Software design >  Which approach is better for "case when then" in Postgresql?
Which approach is better for "case when then" in Postgresql?

Time:12-15

quick one, which approach is better or more correct to take.

Option 1:

CASE 
WHEN col1=A THEN true
WHEN col1=B THEN true
ELSE false
END

Option 2:

CASE 
WHEN col1=A or col1=B THEN true
ELSE false
END   

edit: typo in the 1st case

CodePudding user response:

Table and data.

create table test_table(id serial, col1 text);

insert into test_table (col1) values ('A'), ('B'),('C'),('D');

select * from test_table;

 id | col1
---- ------
  1 | A
  2 | B
  3 | C
  4 | D

(col1='A' or col1='B') is a bool type expression so case statement is not required

results

select (col1='A' or col1='B') from test_table where id=1;
 ?column?
----------
 t
select (col1='A' or col1='B') from test_table where id=3;
 ?column?
----------
 f

CodePudding user response:

Thanks everyone for the answers. I used simplified data sample, therefore proposals to do it without case expression are not suitable.

In the end, I decided to go with CASE WHEN col1 IN (A, B) THEN true ELSE false END

  • Related