I have a large table with say 10 columns. 4 of them remains null most of the times. I have a query that does null value takes any size or no size in bytes. I read few articles some of them are saying :
http://www.sql-server-citation.com/2009/12/common-mistakes-in-sql-server-part-4.html
There is a misconception that if we have the NULL values in a table it doesn't occupy storage space. The fact is, a NULL value occupies space – 2 bytes
SQL: Using NULL values vs. default values
A
NULL
value in databases is a system value that takes up one byte of storage and indicates that a value is not present as opposed to a space or zero or any other default value.
Can you please guide me regarding the size taken by null value.
If the field is fixed width storing NULL takes the same space as any other value - the width of the field.
If the field is variable width the NULL value takes up no space.
In addition to the space required to store a null value there is also an overhead for having a nullable column. For each row one bit is used per nullable column to mark whether the value for that column is null or not. This is true whether the column is fixed or variable length.
The reason for the discrepancies that you have observed in information from other sources:
The start of the first article is a bit misleading. The article is not talking about the cost of storing a NULL value, but the cost of having the ability to store a NULL (i.e the cost of making a column nullable). It's true that it costs something in storage space to make a column nullable, but once you have done that it takes less space to store a NULL than it takes to store a value (for variable width columns).
The second link seems to be a question about Microsoft Access. I don't know the details of how Access stores NULLs but I wouldn't be surprised if it is different to SQL Server.
Storing a NULL value does not take any space.
This is a misconception -- that's 2 bytes per row, and I'm pretty sure that all rows use those 2 bytes regardless of whether there's any nullable columns.
This is talking about databases in general, not specifically SQL Server. SQL Server does not use 1 byte to store NULL values.
From this link:
The following link claims that if the column is variable length, i.e.
varchar
thenNULL
takes 0 bytes (plus 1 byte is used to flag whether value isNULL
or not):The above link, as well as the below link, claim that for fixed length columns, i.e.
char(10)
orint
, a value ofNULL
occupies the length of the column (plus 1 byte to flag whether it'sNULL
or not):Examples:
char(10)
toNULL
, it occupies 10 bytes (zeroed out)int
takes 4 bytes (also zeroed out).varchar(1 million)
set toNULL
takes 0 bytes (+ 2 bytes)Note: on a slight tangent, the storage size of
varchar
is the length of data entered + 2 bytes.