Query Performance with NULL

前端 未结 8 1992
失恋的感觉
失恋的感觉 2021-01-14 14:29

I would like to know about how NULL values affect query performance in SQL Server 2005.

I have a table similar to this (simplified):

ID | ImportantDa         


        
相关标签:
8条回答
  • 2021-01-14 14:53

    They do not have a negative performance hit on the database. Remember, NULL is more of a state than a value. Checking for NOT NULL vs setting that value to a -1 makes no difference other than the -1 is probably breaking your data integrity, imo.

    0 讨论(0)
  • 2021-01-14 14:55

    SQL Server's performance can be affected by using NULLS in your database. There are several reasons for this.

    First, NULLS that appear in fixed length columns (CHAR) take up the entire size of the column. So if you have a column that is 25 characters wide, and a NULL is stored in it, then SQL Server must store 25 characters to represent the NULL value. This added space increases the size of your database, which in turn means that it takes more I/O overhead to find the data you are looking for. Of course, one way around this is to use variable length fields instead. When NULLs are added to a variable length column, space is not unnecessarily wasted as it is with fixed length columns.

    Second, use of the IS NULL clause in your WHERE clause means that an index cannot be used for the query, and a table scan will be performed. This can greatly reduce performance.

    Third, the use of NULLS can lead to convoluted Transact-SQL code, which can mean code that doesn't run efficiently or that is buggy.

    Ideally, NULLs should be avoided in your SQL Server databases.

    Instead of using NULLs, use a coding scheme similar to this in your databases:

    • NA: Not applicable
    • NYN: Not yet known
    • TUN: Truly unknown

    Such a scheme provides the benefits of using NULLs, but without the drawbacks.

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