1

I have a column which can contain values from 1 to 6 and null..

Then when I try to run the query below.. rows with null value on that column do not return

select * from customer where Position not IN  ('1','2', '3', '4' ,'5', '6')

Is there way I can retrieve null results without adding this on above query

OR Position is null
6
  • The answer is: No. (But why a condition checking for all possible values?) Commented Dec 27, 2016 at 9:39
  • I created a system where user can select NOT IN condition then he will indicate the values. Commented Dec 27, 2016 at 9:40
  • For example in above query... users select NOT IN condition then he input the values 1,2,3,4,5,6.. that's why I arrived on that kind of query Commented Dec 27, 2016 at 9:42
  • Why are you storing (or comparing) numbers as strings? Commented Dec 27, 2016 at 9:54
  • each number, 1-6 , has corresponding name saved in the system.. Commented Dec 27, 2016 at 9:57

4 Answers 4

3

One trick you could use would be to coalesce the position to some value which does not appear in the restricted list, e.g.

SELECT *
FROM customer
WHERE COALESCE(Position, '9') NOT IN  ('1', '2', '3', '4' ,'5', '6')

However, I would probably just use an is null clause here:

SELECT *
FROM customer
WHERE Position NOT IN  ('1', '2', '3', '4' ,'5', '6') OR
      Position IS NULL
Sign up to request clarification or add additional context in comments.

Comments

1

Is there way I can retrieve null results without adding OR Position is null


There are plenty of ways, but OR Position is null is the easiest, the shorteste and the most natural way.

If you don't like it, then there are few ideas below:

select *
 from customer where ID NOT IN (
  select ID
    from customer where Position IN  ('1','2', '3', '4' ,'5', '6')
);


select *
 from customer where
 1 = CASE WHEN Position IN  ('1','2', '3', '4' ,'5', '6')
          THEN 0 ELSE 1 END;


select * from customer c
left join (
    SELECT * FROM unnest(ARRAY[1,2,3,4,5,6]) x
) x
ON c.position = x.x
WHERE x.x IS NULL

Comments

0

If you want to return the NULL result then include that as a condition in your WHERE clause else NO it's not possible

select * from customer 
where Position not IN  ('1','2', '3', '4' ,'5', '6')
or Position is null

Comments

0

You can add a condition : Position IS NULL

SELECT    *
FROM      Customer
WHERE     Position NOT IN  ('1','2', '3', '4' ,'5', '6') OR Position IS NULL

You can see this here => http://rextester.com/HEZ87754

Hope this helps!!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.