Can we write case statement without having else statement
A case
expression can only manipulate the value of an expression, not remove rows from the result. If you want to omit the null
s from the result, you'll have to add a where
clause:
SELECT CASE WHEN id = 1 THEN 'A'
WHEN id = 2 THEN 'B'
END
FROM test
WHERE id IN (1, 2) -- HERE
You can use a WHERE
clause to restrict the output.
SELECT CASE WHEN id=1 THEN 'A'
WHEN id=2 THEN 'B'
END
FROM test
WHERE id IN (1,2)
Or if you wanted to showcase some other value instead of null
use an else
part inside the CASE
statement.
SELECT CASE WHEN id=1 THEN 'A'
WHEN id=2 THEN 'B' ELSE 'Invalid'
END
FROM test