Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we write case statement without having else statement

I have this query:

select case when id=1 then 'A'
when id=2 then 'B'
end 
from test

It is giving me o/p as

Id
A
B
NULL
NULL
NULL

I don't want to have NULL values in my output, I only want to compare in A and B, is it possible in case statement.

like image 602
Red Devil Avatar asked Oct 18 '16 07:10

Red Devil


2 Answers

A case expression can only manipulate the value of an expression, not remove rows from the result. If you want to omit the nulls 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
like image 97
Mureinik Avatar answered Oct 24 '22 13:10

Mureinik


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
like image 45
Unnikrishnan R Avatar answered Oct 24 '22 14:10

Unnikrishnan R