Read more: http://www.blogsmonetize.com/2010/10/how-to-use-syntax-highlighter-3083-in.html#ixzz1DHzvEgBA

Friday, March 11, 2011

Importance of Column order on a Table

Here Let us see what is the significance of of columns on a table.
Create a Test Table with 10 columns having first two column as default(for easy purpose)and the rest with null to test the table size.


Create Table Table_Size
(
Col1 int Default(1),
Col2 Varchar(50) Default 'Test',
Col3 Varchar(50) NULL,
Col4 Varchar(50) NULL,
Col5 Varchar(50) NULL,
Col6 Varchar(50) NULL,
Col7 Varchar(50) NULL,
Col8 Varchar(50) NULL,
Col9 Varchar(50) NULL,
Col10 Varchar(50) NULL,
Col11 Varchar(50) NULL,
Col12 Varchar(50) NULL,
Col13 Varchar(50) NULL,
Col14 Varchar(50) NULL,
Col15 Varchar(50) NULL,
Col16 Varchar(50) NULL,
Col17 Varchar(50) NULL,
Col18 Varchar(50) NULL,
Col19 Varchar(50) NULL
)


Find out the object id of the table to use the same for finding out the record size.

Select * From sys.tables Where name='Table_Size'


Use sys.dm_db_index_physical_statsdynamic management view to get the record size information as min, max and avg sizes.

Select min_record_size_in_bytes,max_record_size_in_bytes,avg_record_size_in_bytes From sys.dm_db_index_physical_stats
(5,1925655066,NULL,NULL,'DETAILED')


Test Case1:
1. Insert default value
2. Get the record size information
3. Insert values to the very next column
4. Get the record size information

Insert into Table_Size default values
--Min-21,Max-21,Avg-21

Insert into Table_Size(Col1,Col2)Select 2,'Test'
--Min-21,Max-21,Avg-21


Truncate the table for the next test case.

Truncate Table Table_Size
--Min-0,Max-0,Avg-0


Test Case2:
1. Insert default value
2. Get the record size information
3. Insert values to the third next column
4. Get the record size information

Insert into Table_Size default values
--Min-21,Max-21,Avg-21

Insert into Table_Size(Col1,Col3)Select 2,'Test'
--Min-21,Max-27,Avg-24


Truncate the table for the next test case.

Truncate Table Table_Size
--Min-0,Max-0,Avg-0


Test Case3:
1. Insert default value
2. Get the record size information
3. Insert values to the last next column
4. Get the record size information

Insert into Table_Size default values
--Min-21,Max-21,Avg-21

Insert into Table_Size(Col1,Col19)Select 2,'Test'
--Min-21,Max-59,Avg-33.666





Conclusion:

From the above test, it is clear that for every column it adds a 2 byte.
21 bytes - for the record
38 bytes - for 19 columns ( 19 columns * 2 bytes)
59 bytes - for the entire table.

It is always keep non-nullable values first and then nullable values. The reason is that SQL server uses 2 bytes offset to store the information in variable block for variable width columns. Even we do not have values in the first18 columns, the offset uses for those 18 columns if we have value in 19th column.

No comments: