What is the difference between “Is Not Null” and “Not Is Null”

后端 未结 3 1164
攒了一身酷
攒了一身酷 2021-02-02 08:49
SELECT id FROM customers WHERE type IS NOT Null;

Versus:

SELECT id FROM customers WHERE NOT type IS NULL;

The data th

3条回答
  •  醉梦人生
    2021-02-02 09:11

    There is no difference.

    It seems to me that there might be a difference when it comes to performance. Anyone care to elaborate on this?

    All major engines (that is MySQL, SQL Server, Oracle and PostgreSQL) will merge these predicates on parsing stage, making identical plans from them.

    Handling of these conditions is more complex that mere applying operators in one or another order.

    For instance, in Oracle, an IS NOT NULL (or NOT IS NULL) condition implies a possibility to use an index, so a query like this:

    SELECT  column
    FROM    mytable
    WHERE   column IS NOT NULL
    

    will most probably be executed with an index fast full scan, with no additional checks made in runtime (since the NULL values just won't make it into the index, so it's no use to check them).

    Even if each record would need to be checked, the order of checks will be defined by the optimizer (and not by the order the predicates and operators appear in the WHERE clause).

    For instance, here is a plan for an Oracle query:

    SQL> EXPLAIN PLAN FOR
      2  
      2  SELECT *
      3  FROM   t_test
      4  WHERE  NOT column IS NULL
      5  /
    
    Explained
    
    SQL> SELECT  *
      2  FROM    TABLE(DBMS_XPLAN.display())
      3  /
    
    PLAN_TABLE_OUTPUT
    --------------------------------------------------------------------------------
    Plan hash value: 958699830
    ----------------------------------------------------------------------------
    | Id  | Operation         | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
    ----------------------------------------------------------------------------
    |   0 | SELECT STATEMENT  |        |    30 |  1260 |     3   (0)| 00:00:01 |
    |*  1 |  TABLE ACCESS FULL| T_TEST |    30 |  1260 |     3   (0)| 00:00:01 |
    ----------------------------------------------------------------------------
    Predicate Information (identified by operation id):
    ---------------------------------------------------
       1 - filter("COLUMN" IS NOT NULL)
    

    As you can see, the filter was translated internally into an IS NOT NULL (which Oracle along with most commenters seems to believe to be a more appropriate form)

    Update:

    As Jonathan Leffler pointed out, these is difference when evaluating tuples (as opposed to single columns).

    A tuple consisting of mixed NULL and non-NULL values is neither a NULL nor a NOT NULL.

    In PostgreSQL (which supports this predicate against tuples), both these expressions:

    SELECT  (1, NULL) IS NULL
    SELECT  (1, NULL) IS NOT NULL
    

    evaluate to false.

提交回复
热议问题