“<>” vs “NOT IN”

后端 未结 9 1464
Happy的楠姐
Happy的楠姐 2020-12-14 17:53

I was debugging a stored procedure the other day and found some logic something like this:

SELECT something
FROM someTable
WHERE idcode <> (SELECT ids          


        
相关标签:
9条回答
  • 2020-12-14 18:09

    in some versions of SQL != should be used for a "not equals" logical statement. Have you tried that?

    0 讨论(0)
  • 2020-12-14 18:19
    SELECT something
    FROM someTable
    WHERE idcode NOT IN (SELECT ids FROM tmpIdTable)
    

    checks against any value in the list.

    However, the NOT IN is not NULL-tolerant. If the sub-query returned a set of values that contained NULL, no records would be returned at all. (This is because internally the NOT IN is optimized to idcode <> 'foo' AND idcode <> 'bar' AND idcode <> NULL etc., which will always fail because any comparison to NULL yields UNKNOWN, preventing the whole expression from ever becoming TRUE.)

    A nicer, NULL-tolerant variant would be this:

    SELECT something
    FROM someTable
    WHERE NOT EXISTS (SELECT ids FROM tmpIdTable WHERE ids = someTable.idcode)
    

    EDIT: I initially assumed that this:

    SELECT something
    FROM someTable
    WHERE idcode <> (SELECT ids FROM tmpIdTable)
    

    would check against the first value only. It turns out that this assumption is wrong at least for SQL Server, where it actually triggers his error:

    Msg 512, Level 16, State 1, Line 1
    Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
    
    0 讨论(0)
  • 2020-12-14 18:21

    <> is a "singular" NOT operation; NOT IN is a set operation, so it makes sense that the former wouldn't work. I have no idea whether or not it may have done so under a previous version of SQL Server, however.

    0 讨论(0)
提交回复
热议问题