I am trying to check how the table size is going to be increased after adding new column with default values.
I use the following default values: NULL
, ''
(empty string) and some text
(some random text)` but it seems the table size is not changed.
I am using the following statements:
EXEC sp_spaceused '[Table_A]';
ALTER TABLE [dbo].[Table_A]
ADD [Loops] NVARCHAR(900)
CONSTRAINT [DF_Loops] DEFAULT('XXX') WITH VALUES;
EXEC sp_spaceused '[Table_A]';
ALTER TABLE [dbo].[Table_A]
DROP CONSTRAINT [DF_Loops]
ALTER TABLE [dbo].[Table_A]
DROP COLUMN [Loops];
but the sp_spaceused
always returns:
name rows reserved data index_size unused
------------------------------------------------- -------------------- ------------------ ------------------ ------------------ ------------------
Table_A 73540994 8701688 KB 6658544 KB 2042976 KB 168 KB
Could anyone tell what I am doing wrong?
Best Answer
You've added a new column, but SQL Server - if the default value is a runtime constant - will not update the existing pages that hold the table's data, it will be only a metadata change and that's the reason you see no increase in the space used.
For all intents and purposes (as Aaron mentioned in a comment), the values are there - and a
SELECT
will reveal them.Think of it as SQL-Server black magic. It manages to store information in 0 bytes. Remus Rusanu has a nice blog post about this optimization and more details about what (magic) happens in the background and when you subsequently update the column:
Online non-NULL with values column add in SQL Server 2012
The basic info about it, in MSDN docs,
ALTER TABLE
: