6

enter image description here

I am trying to use the "Not Equal" command in Sql but it does not seem to be working. I want to get the total count when all the 3 fields (status1, status2 and status3) are not equal to Yes. For some reason I am getting 0 records.

SELECT
    COUNT(ID) from [maintable]
WHERE 
    status1 <> 'YES'
    and status2 <> 'YES'
    and status3 <> 'YES'

The above query does not generate any results. What am i doing wrong here? Thanks

2
  • 4
    What is the type of those fields, are they nullable? Commented Jan 7, 2013 at 16:44
  • Can you provide some sample data? As @TimSchmelter alluded to, if those tuples are NULL, then an equality comparison with NULL is unpredictable. It needs to be handled. Commented Jan 7, 2013 at 16:50

3 Answers 3

15

Try this:

SELECT
    COUNT(ID) from [maintable]
WHERE
    COALESCE(status1, '') <> 'YES'
    AND COALESCE(status2, '') <> 'YES'
    AND COALESCE(status3, '') <> 'YES'

null values are not <> 'YES', they are undefined.

COALESCE

Sign up to request clarification or add additional context in comments.

6 Comments

Tim, i am still getting no data back when i run the qry. Pls. see my post on the top i have just added a picture of how my table look like when i just run the select statement. thnx
Tim's query is fine. If data sample is all data you have in your table it is OK that you get no data because there are no records which meet the where clause
@user1858332 - What rows were you expecting to be returned from that sample data? Maybe you need OR instead of AND
@MaksymStrukov: Btw, here's your sample data and yes, it doesn't return a record: SQL-Fiddle. But that makes sense since even the last row's status3 is 'YES', hence it is not returned. All conditions in a WHERE must be true to return that record if using AND.
@TimSchmelter: Actually that's what I wrote to user1858332. This is not my sample data and not even my question. I'm absolutley with you that it's OK that no data is returned if the sample data is used only.
|
2

Try using EXCEPT.

SELECT
    COUNT(ID) from [maintable]
EXCEPT
SELECT
    COUNT(ID) from [maintable]
WHERE 
    status1 = 'YES'
    and status2 = 'YES'
    and status3 = 'YES'

Comments

0
SELECT
    COUNT(ID) from [maintable]
WHERE
    NVL(status1, 'NO') <> 'YES'
    NVL COALESCE(status2, 'NO') <> 'YES'
    NVL COALESCE(status3, 'NO') <> 'YES'

we can use nvl for null cases

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.