0

Why alter table <> alter column<> SPARSE does not have an effect in cases 1-3 but only in case 4? I.e. can we say that column can be declared as SPARSE only when creating?

I have tested this code in SQL2012.

-- 1
CREATE TABLE UnSparsed(ID INT IDENTITY(1,1),
FirstCol INT,
SecondCol VARCHAR(100),
ThirdCol SmallDateTime)
GO

INSERT INTO UnSparsed SELECT TOP 50000 NULL,NULL, NULL
FROM master..spt_values v1, 
     master..spt_values v2

GO
sp_spaceused 'UnSparsed'
GO
--- 2
alter table UnSparsed alter column FirstCol int SPARSE NULL
alter table UnSparsed alter column SecondCol VARCHAR(100) SPARSE NULL
alter table UnSparsed alter column ThirdCol SmallDateTime  SPARSE NULL
GO
sp_spaceused 'UnSparsed'
GO
--- 3
truncate table UnSparsed
GO
INSERT INTO UnSparsed SELECT TOP 50000 NULL,NULL, NULL
FROM master..spt_values v1, 
     master..spt_values v2

GO
sp_spaceused 'UnSparsed'
GO
DROP TABLE UnSparsed
GO
--- 4
CREATE TABLE UnSparsed(ID INT IDENTITY(1,1),
FirstCol INT SPARSE NULL,
SecondCol VARCHAR(100)  SPARSE NULL,
ThirdCol SmallDateTime  SPARSE NULL)
GO
INSERT INTO UnSparsed SELECT TOP 50000 NULL,NULL, NULL
FROM master..spt_values v1, 
     master..spt_values v2

GO
sp_spaceused 'UnSparsed'
GO

enter image description here

Martin Smith
  • 438,706
  • 87
  • 741
  • 845
ZedZip
  • 5,794
  • 15
  • 66
  • 119
  • 2
    Possible duplicate of [Adding SPARSE made table much bigger](http://dba.stackexchange.com/q/12256/3690) – Martin Smith Jun 15 '14 at 14:49
  • Though in your case you have no clustered index to `REBUILD` so would need to recreate the table or add and drop a CI. – Martin Smith Jun 15 '14 at 14:54
  • I have some large tables and want to apply property 'sparse' to some of really sparse columns. Does it mean it is not always reduce the existing table space? – ZedZip Jun 15 '14 at 15:37
  • @Oleg, SPARSE is only needed on fixed-width columns to allow them to not take up that amount of space when set to NULL; it is _not_ needed on variable-width columns (i.e. your `SecondCol VARCHAR(100)`) as they naturally don't take up any space when empty. – Solomon Rutzky Jun 24 '14 at 17:02
  • Yes, thank you, I see. I have some tables with many uniqueidentifier fields containing nulls. – ZedZip Jun 27 '14 at 09:31

1 Answers1

0

It seems need to do

ALTER TABLE t REBUILD; 

after this action all is ok.

ZedZip
  • 5,794
  • 15
  • 66
  • 119