开发者

Effect of NULL values on storage in SQL Server?

开发者 https://www.devze.com 2023-04-05 09:54 出处:网络
If you have a table with 20 rows that contains 12 null columns and8 columns with values, what is the implications for storage and memory开发者_开发问答 usage?

If you have a table with 20 rows that contains 12 null columns and 8 columns with values, what is the implications for storage and memory开发者_开发问答 usage?

Is null unique or is it stored in memory at the same location each time and just referenced? Do a ton of nulls take up a ton of space? Does a table full of nulls take up the same amount of space as a table the same size full of int values?

This is for Sql server.


This depends on database engine as well as column type.

At least SQLite stores each null column as a "null type" which takes up NO additional space (each record is serialized to a single blob for storage so there is no space reserved for a non-null value in this case). With optimizations like this a NULL value has very little overhead to store. (SQLite also has optimizations for the values 0 and 1 -- the designers of databases aren't playing about!) See 2.1 Record Format for the details.

Now, things can get much more complex, especially with updating and potential index fragmentation. For instance, in SQL Server space may be reserved for the column data, depending upon the type. For instance, a int null will still reserve space for the integer (as well as have an "is null" flag somewhere), however varchar(100) null doesn't seem to reserve the space (this last bit is from memory, so be warned!).

Happy coding.


Starting with SQL Server 2008, you can define a column as SPARSE when you have a "ton of nulls". This will save some space but it requires a portion of the values of a column to be null . Exactly how much depends on the type.

See the Estimated Space Savings by Data Type tables in the article Using Sparse Columns which will tell you what percentage of the values need to be null for net saving of 40%

For example according to the tables 98% of values in a bit field must be null in order to get a savings of 40% while only 43% of a uniqueidentifier column will net you the same percentage.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号