Groups | Blog | Home
all groups > sql server programming > february 2004 >

sql server programming : Performance problem - Adding column and assigning value to table with 60M rows


TJTODD
2/7/2004 7:27:42 PM
Hi,

I have alarge table with 60 Million rows. I needed to add a new INT column
to the table and then assign it a value of 0. The Alter statement to add
the column ran pretty quick:
ALTER TABLE tb1
ADD c1 INT NOT NULL

but the update statement:
UPDATE tb1
SET c1 = 0
ran for over 7 hours.

Is there a better way to do this?

Thanks in advance

Dan Guzman
2/7/2004 11:03:57 PM
[quoted text, click to view]

Hmm. I wouldn't expect SQL Server to allow you to add a NOT NULL column to
a non-empty table unless you also specify a default constraint.

For large tables, you may find it faster to create a new table using SELECT
INTO and then rename. This will be minimally logged in the SIMPLE or
BULK_LOGGED recovery model. Example script below.

CREATE TABLE tbl
(
c0 int not null
)

INSERT INTO tbl VALUES(1)

SELECT
c0,
ISNULL(CAST(0 AS int), 0) AS c1
INTO tbl_new
FROM tbl

DROP TABLE tbl

EXEC sp_rename 'tbl_new', 'tbl'

--
Hope this helps.

Dan Guzman
SQL Server MVP

[quoted text, click to view]

Uri Dimant
2/8/2004 11:44:40 AM
Dan
You are right.
CREATE TABLE TEST
(
COL INT NOT NULL
)
INSERT INTO TEST VALUES (1)
INSERT INTO TEST VALUES (4)
INSERT INTO TEST VALUES (3)
GO
ALTER TABLE TEST ADD COL1 INT NOT NULL

SELECT * FROM TEST

He should get
Server: Msg 4901, Level 16, State 1, Line 1
ALTER TABLE only allows columns to be added that can contain nulls or have a
DEFAULT definition specified. Column 'COL1' cannot be added to table 'TEST'
because it does not allow nulls and does not specify a DEFAULT definition.




[quoted text, click to view]

Louis Davidson
2/8/2004 3:15:55 PM
However, if you add a NULL column it will run very quick. All it has to do
is simply add the column into the meta data. When the update executes, it
has to allocate space for each new row.

--
----------------------------------------------------------------------------
-----------
Louis Davidson (drsql@hotmail.com)
Compass Technology Management

Pro SQL Server 2000 Database Design
http://www.apress.com/book/bookDisplay.html?bID=266

Note: Please reply to the newsgroups only unless you are
interested in consulting services. All other replies will be ignored :)

[quoted text, click to view]

AddThis Social Bookmark Button