Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will adding a nonclustered index lock my table?

I have a table with ~2 million records in and I need to add a new nonclustered index to a uniqueidentifier to improve query performance.

Will adding a nonclustered index lock the table or otherwise degrade performance significantly while it's being applied?

There's lots of information out there about the benefits/pitfalls of indexing, but I can't find anything that tells me that happens during an indexing operation

I'm running SQL Server 2008 R2 (on Windows Server 2008 if that's important)

EDIT: It's the Enterprise Edition

like image 524
dave clements Avatar asked Feb 28 '14 11:02

dave clements


People also ask

Does creating a nonclustered index lock table?

An offline index operation that creates a nonclustered index acquires a Shared (S) lock on the table. This prevents updates to the underlying table but allows read operations, such as SELECT statements.

Does adding an index lock a table SQL Server?

Yes, it is absolutely true if you create an index on the huge table it may take lots of time to create it and create inconvenience to your users. However, if you using the enterprise version of SQL Server you can easily create an index that is online and does not lock your table.

What happens when you create a non-clustered index?

Generally, nonclustered indexes are created to improve the performance of frequently used queries not covered by the clustered index or to locate rows in a table without a clustered index (called a heap). You can create multiple nonclustered indexes on a table or indexed view.

Can a table have both clustered and nonclustered index?

There can be only one clustered index per table. However, you can create multiple non-clustered indexes on a single table.


1 Answers

For those of us not running "Expensive Edition" (Enterprise), the answer is thus:

An offline index operation that creates a nonclustered index acquires a Shared (S) lock on the table. This prevents updates to the underlying table but allows read operations, such as SELECT statements.

So basically it renders the target table "read only" while the index is built. This may or may not be a problem for your overlaying applications -- check with your dev teams and users!

PS: The question of whether or not, or why, to apply such an index, is an entirely different conversation. The SQL community and its legion of professional bloggers & SMEs are your friends.

like image 196
NateJ Avatar answered Oct 12 '22 14:10

NateJ