2

I have the table in following format. I am trying to query this table to get all the records which are not PC and PT.

So my query should return ID 3,4,5,6,7 and should ignore 1 and 2

    CREATE TABLE #t (ID INT, V VARCHAR(16))

    INSERT  INTO #t
    VALUES  (1, 'PC'),
            (2, 'PT'),
            (3, NULL),
            (4, NULL),
            (5, NULL),
            (6, 'PS'),
            (7, 'PD');

drop table #t

The query that I am using is which returns only 6 and 7 and ignores null records in the result set .:

select 
    id, v 
from 
    #t 
where  
    v != 'PC' and V != PT

Please let me know what should I do in order to include null in my result set?

4
  • 2
    Add OR V IS NULL in the WHERE clause. Commented Apr 21, 2015 at 4:53
  • Just use NOT IN ('PC', 'PT'). It will return all the rows except PC and PT Commented Apr 21, 2015 at 4:56
  • 1
    @PareshJ - NOT IN ('PC','PT') will also exclude NULL records. Commented Apr 21, 2015 at 4:58
  • Yes, it should be not in ('PC','PT') or v is null Commented Apr 21, 2015 at 5:37

3 Answers 3

5

Your query should check null condition as well.

Query -

select id , v from #t where  v not in ('PC' , 'PT') OR v is null
Sign up to request clarification or add additional context in comments.

Comments

0
select id , v from #t where  v!='PC' and V!=PT or OR V IS NULL

All good. please add the null condition too

or

select id , v from #t where  v not in ('PC' , 'PT') and v is null 

use not in It will return all the rows except PC and PT

4 Comments

the first query works but not the second .Thanks for the feedback
SELECT ID, V FROM #t WHERE ISNULL(V,'') NOT IN ('PC' , 'PT')
@ps_prakash02 your query is way better put it as answer or else i will put same aas answer
The first query won't work - you've got two ORs, and mixing AND and OR in your where clause without the brackets means results will return the wrong results
0

Instead of using != for every condition, use a not in and for handling null values, use isnull

select 
  id, v 
from 
  #t 
where  
  isnull(v,'') not in ('PC', 'PT')

Comments

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.