How do NULL values affect performance in a database search?

前端 未结 8 733
死守一世寂寞
死守一世寂寞 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 13:45

    If your column doesn't contain NULLs it is best to declare this column NOT NULL, the optimizer may be able to take more efficient path.

    However, if you have NULLs in your column you don't have much choice (a non-null default value may create more problems than it solves).

    As Quassnoi mentionned, NULLs are not indexed in Oracle, or to be more precise, a row won't be indexed if all the indexed columns are NULL, this means:

    • that NULLs can potentially speed up your research because the index will have fewer rows
    • you can still index the NULL rows if you add another NOT NULL column to the index or even a constant.

    The following script demonstrates a way to index NULL values:

    CREATE TABLE TEST AS 
    SELECT CASE
              WHEN MOD(ROWNUM, 100) != 0 THEN
               object_id
              ELSE
               NULL
           END object_id
      FROM all_objects;
    
    CREATE INDEX idx_null ON test(object_id, 1);
    
    SET AUTOTRACE ON EXPLAIN
    
    SELECT COUNT(*) FROM TEST WHERE object_id IS NULL;
    

提交回复
热议问题