0

In a Ruby case statement you can say

name = case foo
       when 'bar', 'baz', 'bof' then 'Tom'
       when 'qux' then 'Jerry'
       end

and in a C/C++ switch statement you can stack cases on top of each other:

switch(foo) {
      case 'bar' :
      case 'baz' :
      case 'bof' :

      ...

but is there anything similar in SQL/Postgres? Or do you have to spell it out for each option eg.

CASE foo
WHEN bar THEN 'Tom'
WHEN baz THEN 'Tom'
WHEN bof THEN 'Tom'
WHEN qux THEN 'Jerry'
END

3 Answers 3

3

You can use the following syntax to write cases in PostgreSQL -

CASE
  WHEN <condition> THEN <return_value>
  WHEN <condition2> THEN <return_value>
  ELSE <return_value>
END

Example -

SELECT letter, 
(
  CASE 
    WHEN letter IN ('a', 'b', 'c') THEN 'a to c'
    WHEN letter = 'd'              THEN 'letter d'
    ELSE 'e to z'
  END
) AS letter_class
FROM alphabets;
Sign up to request clarification or add additional context in comments.

Comments

2

in sql it would be like below

CASE 
WHEN foo in( 'bar','bof','baz') THEN 'Tom'
WHEN foo ='qux' THEN 'Jerry'
END

Comments

1

You can do it like this:

CASE 
  WHEN foo IN (bar, baz, bof) THEN 'Tom'
  WHEN foo=qux THEN 'Jerry'
  ELSE ...
END

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.