Search code examples
mysqlsqlin-clause

Return null values IN clause mysql


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


Solution

  • 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 |