Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why sql case is not working on null condition of int column

I have used SQL CASE statement on an INT type of column of a table. Following is the SQL table schema and query which is working fine.

SQL Query

CREATE TABLE #TEMP_A(ID BIGINT ,ACCEPTED INT)
INSERT INTO #TEMP_A VALUES(1,1)
INSERT INTO #TEMP_A(ID) VALUES(2)
INSERT INTO #TEMP_A(ID) VALUES(3)
INSERT INTO #TEMP_A(ID) VALUES(4)
INSERT INTO #TEMP_A VALUES(5,1)

SELECT T.ID,T.ACCEPTED,
(CASE WHEN(T.ACCEPTED=1) THEN 'ACCEPTED' ELSE 'NOT ACCEPTED' END) AS STATUS
FROM #TEMP_A T

Query OUTPUT

ID  ACCEPTED    STATUS
1   1           ACCEPTED
2   NULL        NOT ACCEPTED
3   NULL        NOT ACCEPTED
4   NULL        NOT ACCEPTED
5   1           ACCEPTED

But now problem is here that I have a condition that I need to print not accepted in select statement so I tried following query

SQL Query

SELECT T.ID,T.ACCEPTED,
(CASE WHEN(T.ACCEPTED=NULL) THEN 'NOT ACCEPTED' END) AS STATUS
FROM #TEMP_A T

Query Actual OUTPUT

ID  ACCEPTED    STATUS
1   1           NULL
2   NULL        NULL
3   NULL        NULL
4   NULL        NULL
5   1           NULL

Query Required OUTPUT

ID  ACCEPTED    STATUS
1   1           NULL
2   NULL        NOT ACCEPTED
3   NULL        NOT ACCEPTED
4   NULL        NOT ACCEPTED
5   1           NULL

I have to print status of those which are not accepted in select statement what should I do to get required result.

like image 603
islamuddin Avatar asked Feb 09 '23 22:02

islamuddin


2 Answers

try:

SELECT T.ID,T.ACCEPTED,
(CASE WHEN T.ACCEPTED IS NULL THEN 'NOT ACCEPTED' END) AS STATUS
FROM #TEMP_A T
like image 79
A_Sk Avatar answered Feb 11 '23 13:02

A_Sk


Use IS NULL to check for a NULL value. Try this query:

SELECT T.ID,T.ACCEPTED,
(CASE WHEN (T.ACCEPTED IS NULL) THEN 'NOT ACCEPTED' END) AS STATUS
FROM #TEMP_A T
like image 35
Tim Biegeleisen Avatar answered Feb 11 '23 13:02

Tim Biegeleisen