How do NULL values affect performance in a database search?

前端 未结 8 735
死守一世寂寞
死守一世寂寞 2020-12-02 13:13

In our product we have a generic search engine, and trying to optimze the search performance. A lot of the tables used in the queries allow null values. Should we redesign o

8条回答
  •  渐次进展
    2020-12-02 14:06

    An extra answer to draw some extra attention to David Aldridge's comment on Quassnoi's accepted answer.

    The statement:

    this query:

    SELECT * FROM table WHERE column IS NULL

    will always use full table scan

    is not true. Here is the counter example using an index with a literal value:

    SQL> create table mytable (mycolumn)
      2  as
      3   select nullif(level,10000)
      4     from dual
      5  connect by level <= 10000
      6  /
    
    Table created.
    
    SQL> create index i1 on mytable(mycolumn,1)
      2  /
    
    Index created.
    
    SQL> exec dbms_stats.gather_table_stats(user,'mytable',cascade=>true)
    
    PL/SQL procedure successfully completed.
    
    SQL> set serveroutput off
    SQL> select /*+ gather_plan_statistics */ *
      2    from mytable
      3   where mycolumn is null
      4  /
    
      MYCOLUMN
    ----------
    
    
    1 row selected.
    
    SQL> select * from table(dbms_xplan.display_cursor(null,null,'allstats last'))
      2  /
    
    PLAN_TABLE_OUTPUT
    -----------------------------------------------------------------------------------------
    SQL_ID  daxdqjwaww1gr, child number 0
    -------------------------------------
    select /*+ gather_plan_statistics */ *   from mytable  where mycolumn
    is null
    
    Plan hash value: 1816312439
    
    -----------------------------------------------------------------------------------
    | Id  | Operation        | Name | Starts | E-Rows | A-Rows |   A-Time   | Buffers |
    -----------------------------------------------------------------------------------
    |   0 | SELECT STATEMENT |      |      1 |        |      1 |00:00:00.01 |       2 |
    |*  1 |  INDEX RANGE SCAN| I1   |      1 |      1 |      1 |00:00:00.01 |       2 |
    -----------------------------------------------------------------------------------
    
    Predicate Information (identified by operation id):
    ---------------------------------------------------
    
       1 - access("MYCOLUMN" IS NULL)
    
    
    19 rows selected.
    

    As you can see, the index is being used.

    Regards, Rob.

提交回复
热议问题