skip to Main Content

How to select values in sql with null result
For example we have next table

user code
user1 code 1
user3 code 2
user4 code 4

Select
select * from table where user in ( 'user1', 'user2', 'user3', 'user4')

Result from select will be next

user code
user1 code 1
user2
user3 code 2
user4 code 4

How to select values in sql with null result

2

Answers


  1. You can do it by passing your condition as a subquery then apply left join with your table :

    select s.user, t.code
    from (
      select 'user1' as user union all 
      select 'user2' union all 
      select 'user3' union all 
      select 'user4' 
    ) as s
    left join mytable t on s.user = t.user;
    

    Results :

    user code
    user1 code 1
    user2 null
    user3 code 2
    user4 code 4

    Demo here

    Login or Signup to reply.
  2. You can directly filter it in where clause

    select user,code
    from (
      select 'user1' as user, 'abc' as code union all 
      select 'user2','def' union all 
      select 'user3', 'ghi' union all 
      select 'user4' ,NULL
    ) as s
    where code is null;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search