Question: When we drop primary key on the column, does it automatically drop a clustered index on the same column (if created)?
Answer: This is one of the most popular questions, whenever I ask this to any candidate, they usually give an answer in yes or no. However, if I ask them follow up question to confirm, I have noticed most of the time they change the reply or accept that they really do not know the answer. It is totally fine. As when I was beginning with SQL, I even did not know the answer of it. I learn doing various experiments and doing various interviews.
Well, the answer in one simple statement – “When you drop the primary key constraint on a column where there is a clustered index, it will drop clustered index along the clustered index as well.“
Here is a small reproduction script.
First, let us create a sample table.
-- Create Table CREATE TABLE Table1( Col1 INT NOT NULL, Col2 VARCHAR(100) CONSTRAINT PK_Table1_Col1 PRIMARY KEY CLUSTERED ( Col1 ASC) ) GO
Next let us check the primary key on the table with following script. Along with that we will also check clustered index on the same table.
-- Check the Name of Primary Key SELECT name FROM sys.key_constraints WHERE type = 'PK' AND OBJECT_NAME(parent_object_id) = N'Table1' GO
-- Check the Clustered Index SELECT OBJECT_NAME(object_id),name FROM sys.indexes WHERE OBJECTPROPERTY(object_id, 'IsUserTable') = 1 AND type_desc='CLUSTERED' AND OBJECT_NAME(object_id) = N'Table1' GO
Now let us drop the primary key constraint. Please note that we are not dropping the clustered index, we are just dropping primary key constraint on the column where there is a clustered index.
-- Drop Primary Key Constraint ALTER TABLE Table1 DROP CONSTRAINT PK_Table1_Col1 GO
Now, once again, let us run two scripts where we can see the primary key and clustered index.
-- Check the Name of Primary Key SELECT name FROM sys.key_constraints WHERE type = 'PK' AND OBJECT_NAME(parent_object_id) = N'Table1' GO
-- Check the Clustered Index SELECT OBJECT_NAME(object_id),name FROM sys.indexes WHERE OBJECTPROPERTY(object_id, 'IsUserTable') = 1 AND type_desc='CLUSTERED' AND OBJECT_NAME(object_id) = N'Table1' GO
This time you can see that results are empty.
Let us clean up the created table for our experiment.
-- Clean up DROP TABLE Table1 GO
Summary: From the example it is very clear that when we drop the primary key constraint on a column where there is a clustered index, it will drop clustered index on the table as well.
Let me know what you think about this blog post. Leave your favorite interview question in the comment and I will do my best to answer in the future blog posts.
Reference: Pinal Dave (http://blog.sqlauthority.com)
First appeared on Does Dropping Primary Key Drop Clustered Index on the Same Column? – Interview Question of the Week #082