2

Print not found when there is no data found in database. For example in my database I do not have 56443 therefore it should print 'not found'

SELECT uid, (CASE WHEN (u.uid = null) THEN 'not found' ELSE 'found' END) as result
FROM (SELECT uid
            FROM users
            WHERE uid IN (1,2,56443,3)) as u;

Getting result as follows

+--------+--------+
| uid    | result|
+--------+--------+
| 1      | found | 
| 2      | found |
| 3      | found |
+--------+--------+

I am also expecting not found row with 56443

1
  • You sould use u.uid is null instead of u.uid = null, as null values can not be compared using = operator in sql. Commented Mar 31, 2016 at 5:22

2 Answers 2

4

You need to use a different approach. You will need to create a inline view with all the values using the UNION ALL, and then left join it with the users table:

SQL Fiddle

Query 1:

SELECT a.uid, (CASE WHEN (u.uid is null) THEN 'not found' ELSE 'found' END) as     result
FROM (select 1 as UID FROM dual
      UNION ALL
      select 2 as UID FROM dual
      UNION ALL
      select 56443 as UID FROM dual
      UNION ALL
      select 3 as UID FROM dual) as a
LEFT JOIN users u on a.uid = u.uid

[Results]:

|   UID |    result |
|-------|-----------|
|     1 |     found |
|     2 |     found |
|     3 |     found |
| 56443 | not found |
Sign up to request clarification or add additional context in comments.

3 Comments

Wow. Thank you very much for your help. I really appreciate it
The query works for this particular case. If you have a different set of values then you have to form this query dynamically otherwise you won't be able to utilize this query. Better do this dummy row generations in application level. @mubeen
@1000111 Thank you for your worry. But query is fine :)
1

That is because you are comparing a value with null aka. unknown. Always use the IS operator when comparing to null values. CASE WHEN (u.uid is null) THEN 'not found' ELSE 'found' END) as result

Try this instead (updated answer):

SELECT u2.uid, (CASE WHEN (u1.uid is null) THEN 'not found' ELSE 'found' END) 
as     result
FROM users u1
RIGHT JOIN 
(select 1 as uid union all
 select 2 as uid union all
 select 3 as uid union all
 select 56443 as uid
) u2
on u1.uid = u2.uid

4 Comments

Try it, but same result :( .
Nope, sqlfiddle.com/#!9/c38d26/1 because there still is no 56443 in users
This also worked! Thank you.. But I can mark only one answer
I noticed the other answer. Awesome.. It's fine you got the correct answer. Cheers!

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.