ppshein ppshein - 5 months ago 15
SQL Question

CASE WHEN statement example in SQL query

And I have special companies in our project that has

top_company
value is false.

special_companies = [111, 222, 333];


And I've wrote following query.

SELECT top_company FROM companies


and top_company will return boolean output. Now got problem if
top_company
return false, I want to check that each companies are included in
special_companies
. If included yes, I want to return that company as boolean
YES
. And If not included, boolean
NO
.

Answer

It seems you want to override the top_company value when a company is in the special list:

select *,
       case when id in (111,222,333) or top_company
         then 'YES'
         else 'NO'
       end as is_top_or_special
from   companies

SQL Fiddle

Or, if you don't need the string YES/NO output, but pure boolean:

select *,
       (id in (111,222,333) or top_company) as is_top_or_special
from   companies