SQL Server: Alter a clustered primary index to an non-clustered - sql-server

How do I alter a primary clustered index to become a non-clustured index. (Being a "secondary" table I want to use the clustured index for the foreign key column of the "header" table.)
This doen't work for me (error seems reasonable :)
DROP INDEX ClientUsers.PK_ClientUsers
CREATE UNIQUE CLUSTERED INDEX IDX_ClientUsers_Id ON ClientUsers(Id)
Msg 3723, Level 16, State 4, Line 7
An explicit DROP INDEX is not allowed on index 'ClientUsers.PK_ClientUsers'.
It is being used for PRIMARY KEY constraint enforcement.

I think you will have to:
Drop the FK
Drop the PK
Drop the clustered index
Recreate the PK
Recreate the FK
Recreate the clustered index on the FK column
and then optionally create a secondry index on the PK column

Have you tried dropping the PRIMARY KEY constraint on the table as well - then dropping the index - then re-adding both?
ALTER TABLE table_name DROP primary key

Related

SQL Server - Change clustered index without dropping primary key?

I want to change the clustered index on a table to a column combo other than the primary key.
How can I drop the clustered index, keep the same primary key I have, and add a new clustered index on a new set of columns.
Final result - Non-clustered indexed PK, clustered index on new set of columns.
The only way you can do this is:
1) First Drop the constraints with the below code:
ALTER TABLE TABLENAME DROP CONSTRAINT ConstrainName
2) Then Create the Clustered Index on the Column you want with the below code:
Create clustered index Index_Name on TableName (column1,column2)
3) Create a primary key on a column :
ALTER TABLE TableName
ADD CONSTRAINT constraint_name PRIMARY KEY (ColumnName);

Can I make Primary Key non clustered while another index is clustered?

In my table I have ID as primary key, it is just a meaningless unique code
as it is a primary key SQL Server 2017 made it clustered.
I have another column in my table called myTime this is a timestamp with non uinique non clustered index
Can I make the PK a non clustered and the index is clustered and how?
Yes you can. If you already have an existing table then you need to:
Drop the current clustered PRIMARY KEY
Create your CLUSTERED INDEX
Create a PRIMARY KEY NONCLUSTERED
For example:
IF OBJECT_ID('tempdb..#Test') IS NOT NULL
DROP TABLE #Test
CREATE TABLE #Test (
ID INT,
TimeStamp DATETIME,
CONSTRAINT PK_Test PRIMARY KEY (ID)) -- Clustered by default
ALTER TABLE #Test DROP PK_Test
CREATE CLUSTERED INDEX CI_Test_TimeStamp ON #Test (TimeStamp)
ALTER TABLE #Test ADD CONSTRAINT PK_Test PRIMARY KEY NONCLUSTERED (ID)
The only thing that will enforce uniqueness is the PRIMARY KEY constraint, you can still have a clustered index on repeated values, although it might raise an eyebrow for performance. See Eric's link for details.
Yes you can, by specifying the primary key be nonclustered.
ALTER TABLE TableName
ADD CONSTRAINT PK_name PRIMARY KEY NONCLUSTERED (ID);
You make another index clustered by specifying a clustered index.
CREATE CLUSTERED INDEX IX_Name
ON dbo.TableName (ColumnName);

Moving an index which underlies a PK constraint

SQL Server 2012 SP3
I've got a table with a clustered unique index which I want to move to the SECONDARY filegroup.
The standard method is to ALTER TABLE ... DROP CONSTRAINT and then ALTER TABLE ... ADD CONSTRAINT it back again in the new filegroup. However, there's a chain of FKs which I'd have to drop and recreate.
Is there any other way to move the underlying data without lots of drops?
Use CREATE UNIQUE CLUSTERED INDEX...WITH(DROP_EXISTING=ON) to move the primary key index to a different filegroup. This will also avoid the sort.
CREATE UNIQUE CLUSTERED INDEX PK_YourTable ON dbo.YourTable(YourPrimaryKeyColumn)
WITH(DROP_EXISTING=ON)
ON [YourSecondaryFileGroup];

Is Unique key Clustered or Non-Clustered Index in SQL Server?

I am new to SQL Server and while learning about clustered index, I got confused!
Is unique key clustered or a non-clustered index? Unique key holds only unique values in the column including null, so according to this concept, unique key should be a clustered index, right? But when I went through this article I got confused MSDN
When you create a UNIQUE constraint, a unique nonclustered index is
created to enforce a UNIQUE constraint by default. You can specify a
unique clustered index if a clustered index on the table does not
already exist.
Please help me to understand the concept in a better manner, Thank you.
There are three ways of enforcing uniqueness in SQL Server indexes.
Primary Key constraint
Unique constraint
Unique index (not constraint based)
Whether they are clustered or non clustered is orthogonal to whether or not the indexes are declared as unique using any of these methods.
All three methods can create a clustered or non clustered index.
By default the unique constraint and Unique index will create a non clustered index if you don't specify any different (and the PK will by default be created as CLUSTERED if no conflicting clustered index exists) but you can explicitly specify CLUSTERED/NONCLUSTERED for any of them.
Example syntax is
CREATE TABLE T
(
X INT NOT NULL,
Y INT NOT NULL,
Z INT NOT NULL
);
ALTER TABLE T ADD PRIMARY KEY NONCLUSTERED(X);
--Unique constraint NONCLUSTERED would be the default anyway
ALTER TABLE T ADD UNIQUE NONCLUSTERED(Y);
CREATE UNIQUE CLUSTERED INDEX ix ON T(Z);
DROP TABLE T;
For indexes that are not specified as unique SQL Server will silently make them unique any way. For clustered indexes this is done by appending a uniquefier to duplicate keys. For non clustered indexes the row identifier (logical or physical) is added to the key to guarantee uniqueness.
Unique index can be both clustered or non-clustered.
But if you have nullable column the NULL value should be unique (only 1 row where column is null).
If you want to store more then 1 NULLs you can create the index with filter "where columnName is not null".
well all the answers provided was very helpful, but still i would like to add some detailed answer so that i would be helpful for some others as well
A table can contain only one clustered index and a primary key can
be a clustered / non-clustered index.
Unique Key can be a clustered/non-clustered index as well,
below are some of the examples
Scenario 1 : Primary Key will default to Clustered Index
In this case we will create only Primary Key and when we check the kind of index created on the table we will notice that it has created clustered index automatically over it.
USE TempDB
GO
-- Create table
CREATE TABLE TestTable
(ID INT NOT NULL PRIMARY KEY,
Col1 INT NOT NULL)
GO
-- Check Indexes
SELECT OBJECT_NAME(OBJECT_ID) TableObject,
[name] IndexName,
[Type_Desc] FROM sys.indexes
WHERE OBJECT_NAME(OBJECT_ID) = 'TestTable'
GO
-- Clean up
DROP TABLE TestTable
GO
Scenario 2: Primary Key is defined as a Non-clustered Index
In this case we will explicitly defined Primary Key as a non-clustered index and it will create it as a non-clustered index. It proves that Primary Key can be non-clustered index.
USE TempDB
GO
-- Create table
CREATE TABLE TestTable
(ID INT NOT NULL PRIMARY KEY NONCLUSTERED,
Col1 INT NOT NULL)
GO
-- Check Indexes
SELECT OBJECT_NAME(OBJECT_ID) TableObject,
[name] IndexName,
[Type_Desc] FROM sys.indexes
WHERE OBJECT_NAME(OBJECT_ID) = 'TestTable'
GO
-- Clean up
DROP TABLE TestTable
GO
Scenario 3: Primary Key defaults to Non-Clustered Index with another column defined as a Clustered Index
In this case we will create clustered index on another column, SQL Server will automatically create a Primary Key as a non-clustered index as clustered index is specified on another column.
-- Case 3 Primary Key Defaults to Non-clustered Index
USE TempDB
GO
-- Create table
CREATE TABLE TestTable
(ID INT NOT NULL PRIMARY KEY,
Col1 INT NOT NULL UNIQUE CLUSTERED)
GO
-- Check Indexes
SELECT OBJECT_NAME(OBJECT_ID) TableObject,
[name] IndexName,
[Type_Desc] FROM sys.indexes
WHERE OBJECT_NAME(OBJECT_ID) = 'TestTable'
GO
-- Clean up
DROP TABLE TestTable
GO
Scenario 4: Primary Key defaults to Clustered Index with other index defaults to Non-clustered index
In this case we will create two indexes on the both the tables but we will not specify the type of the index on the columns. When we check the results we will notice that Primary Key is automatically defaulted to Clustered Index and another column as a Non-clustered index.
-- Case 4 Primary Key and Defaults
USE TempDB
GO
-- Create table
CREATE TABLE TestTable
(ID INT NOT NULL PRIMARY KEY,
Col1 INT NOT NULL UNIQUE)
GO
-- Check Indexes
SELECT OBJECT_NAME(OBJECT_ID) TableObject,
[name] IndexName,
[Type_Desc] FROM sys.indexes
WHERE OBJECT_NAME(OBJECT_ID) = 'TestTable'
GO
-- Clean up
DROP TABLE TestTable
GO
reference:the above details is been refrenced from this article

Alter a column length

I need to alter the length of a column column_length in say more than 500 tables and the tables might have no of records ranging from 10 records to 3 or 4 million records.
The column may just be a normal column
CREATE TABLE test(column_length varchar(10))
The column might contain non-clustered index on it.
CREATE TABLE test(column_length varchar(10))
CREATE UNIQUE NONCLUSTERED INDEX column_length_ind ON test (column_length)
The column might contain PRIMARY KEY clustered index on it
CREATE TABLE test(column_length varchar(10))
ALTER TABLE test ADD PRIMARY KEY CLUSTERED INDEX ON column_length
The column might be a composite primary key
The column might have a foreign key reference
In short the column column_length might be anything.
All I need is to create scripts to alter the length of the column_length from varchar(10) to varchar(50). Should I drop the indexes before altering and then recreate them? What about the primary key and foreign key?
Through my research and testing I figured out that I can just alter the column's length without dropping the primary key or any indexes but have to drop and recreate the foreign key alone.
Is this assumption right?
Yes you should be able to just modify the columns. From my experience it is faster to leave the index and primary key in place.
Likely you will need to do alter column on the foreign key tables as well to increase the size. SO first you drop the fk constraint, then fix the forign kkey fields, then fix the primary key field then put the constraints back on.

Resources