I used SQL Server 2017. The executed query is as follows.
CREATE TABLE T11 (
COL VARCHAR NOT NULL,
COL2 VARCHAR,
COL3 VARCHAR
)
GO
CREATE UNIQUE NONCLUSTERED INDEX PK_T11 ON T11 (
COL ASC
)
GO
CREATE TABLE T12 (
COL VARCHAR NOT NULL
)
GO
CREATE UNIQUE NONCLUSTERED INDEX PK_T12 ON T12 (
COL ASC
)
GO
CREATE NONCLUSTERED INDEX FK_T11_TO_T12 ON T12 (
COL ASC
)
GO
ALTER TABLE T12
ADD
CONSTRAINT FK_T11_TO_T12
FOREIGN KEY (
COL
)
REFERENCES T11 (
COL
)
ON DELETE NO ACTION
ON UPDATE NO ACTION
GO
I ran the following query to remove it.
DROP INDEX T11.PK_T11
GO
DROP INDEX T12.PK_T12
GO
DROP TABLE T11
GO
DROP TABLE T12
GO
When I do the syntax to remove the index, I get the following error:
An explicit DROP INDEX is not allowed on index 'T11.PK_T11'. It is being used for FOREIGN KEY constraint enforcement.
How do I fix it?
The concept of a Foreign Key constraint is that you have a column (or set of columns) in a table (like T12) that references a column (or set of columns) in another table (like T11), such that that column in T12 can only contain values that exist in the corresponding column in T11.
But to do this, there must be a unique index or primary key on the column(s) in T11.
So if you're trying to remove that index on T11 (or drop the whole table T11), it will be prevented by the Foreign Key constraint on T12. Unless you first remove the constraint on T12 or drop the whole table T12. Then you can remove the index on T11 (or drop that table).
Make sense? It's like removing the product list while you've still got orders that refer to those products. It's not just the product values that need to be in the products table, but the list (index) of products needs to be there too.
Related
I have a table where I've merged 2 tables into one.
One of the tables had an ID (primary key).
Now I got a merged table where some of the ID is 0.
I now try to restore and fill out the 0 with AUTO_INCREMENT so I
get a table with unique numbers (and not lose the one already there )
Someone got a god solution here ?
Firstly, the fact that you have a bunch of 0's in the table implies 2 additional problems:
The "ID" column is not a Primary Key or dose not have a Unique Index on it; meaning that duplicates were inserted
The column is (likely) no longer an IDENTITY.
Firstly, You'll need to get the new values in there. This can be done with an updatable CTE, with ROW_NUMBER and a windowed MAX
First some sample data:
CREATE TABLE dbo.TestTable (ID int NOT NULL);
INSERT INTO dbo.TestTable (ID)
VALUES(1),(2),(3),(0),(0),(0);
And now to UPDATE the rows with 0:
WITH RNs AS(
SELECT ID,
ROW_NUMBER() OVER (PARTITION BY CASE ID WHEN 0 THEN 0 ELSE 1 END ORDER BY (SELECT NULL)) + --If you have a way of determining the order, change the ORDER BY
MAX(ID) OVER () AS [NewID]
FROM dbo.TestTable)
UPDATE RNs
SET ID = [NewID]
WHERE ID = 0;
Now we (probably) need to fix the table and get the IDENTITY column in there. You can't change a column to an IDENTITY, so we'll need to create a new one and ensure it follows the value of the existing ID.
First, therefore, we need to add a CLUSTERED index to the table, so that the new IDENTITY will use that to generate its value:
ALTER TABLE dbo.TestTable ADD CONSTRAINT PK_TestTable PRIMARY KEY CLUSTERED (ID);
Now we can add the new IDENTITY column:
ALTER TABLE dbo.TestTable ADD IdentityID int IDENTITY NOT NULL;
Then we need to DROP the Primary Key we just created, and then the old column:
ALTER TABLE dbo.TestTable DROP CONSTRAINT PK_TestTable ;
ALTER TABLE dbo.TestTable DROP COLUMN ID;
And then, finally, we can rename the new column, and then recreate the Primary Key:
EXEC sys.sp_rename N'dbo.TestTable.IdentityID','ID','COLUMN';
GO
ALTER TABLE dbo.TestTable ADD CONSTRAINT PK_TestTable PRIMARY KEY CLUSTERED (ID);
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
I found a table in DB with two separate indexes over the same column. The column type is int and there is a clustered primary key on this column. In addition to this, there is a unique non-clustered index on the same column. Indexes have the same options (sort direction and others) and don't contain any included columns.
This index is used by foreign key constraints in some other tables, thus I can't drop it without recreating foreign key constraints.
Could be any sane reason for this?
Maybe it is for efficiency. The nonclustered index is normally smaller than the clustered index, because the clustered index at the leaf level contains all the (non-LOB) fields. So maybe it prefers to use the nonclustered index to enforce the foreign key constraints.
Update: I have done some further tests using AdventureWorks database, which bear out this theory. See below.
I can reproduce the problem using two tables T1 and T2. T1 is the parent and there is a foreign key relationship from T2 to T1.
When T1 has a clustered primary key constraint and a nonclustered unique index Ix-T1, I can alter the table and drop the clustered primary key constraint, but I can't drop Ix-T1 as you found.
If I make T1 with a nonclustered primary key constraint and a clustered unique index Ix_T1, then the situation is reversed: I can drop Ix-T1, but I can't remove the primary key constraint.
CREATE TABLE T1
(
id int NOT NULL CONSTRAINT PK_T1 PRIMARY KEY CLUSTERED
);
CREATE UNIQUE NONCLUSTERED INDEX Ix_T1
ON T1(id);
CREATE TABLE T2
(
id2 int NOT NULL PRIMARY KEY CLUSTERED,
id1 int NOT NULL FOREIGN KEY REFERENCES dbo.T1(id)
);
INSERT INTO T1 (id)
VALUES (1), (2), (3), (4);
INSERT INTO T2 (id2, id1)
VALUES (11, 1), (12, 2), (13, 3);
Try to drop the nonclustered index. This fails.
DROP INDEX Ix_T1
ON dbo.T1;
However I can drop the clustered primary key constraint.
ALTER TABLE dbo.T1
DROP CONSTRAINT PK_T1;
Repeat the test with T1 having a nonclustered primary key and a clustered unique index.
CREATE TABLE T1
(
id int NOT NULL CONSTRAINT PK_T1 PRIMARY KEY NONCLUSTERED
);
CREATE UNIQUE CLUSTERED INDEX Ix_T1
ON T1(id);
This time, I cannot drop the primary key constraint.
ALTER TABLE dbo.T1
DROP CONSTRAINT PK_T1;
However I can drop the clustered index.
DROP INDEX Ix_T1
ON dbo.T1;
So, if my theory is correct, the performance could suffer if you remove the nonclustered index. You might want to do some investigation and tests.
Is there any documentation for the database schema explaining why the index exists? Or can you ask the person who designed the database?
I've done some further tests using AdventureWorks2014, which bear out my theory.
USE AdventureWorks2014;
GO
CREATE SCHEMA test;
GO
-- Create two test tables
SELECT *
INTO test.SalesOrderHeader
FROM Sales.SalesOrderHeader;
SELECT *
INTO test.SalesOrderDetail
FROM Sales.SalesOrderDetail;
-- Test 1 - Clustered primary key and nonclustered index
ALTER TABLE test.SalesOrderHeader
ADD CONSTRAINT PK_Test_SalesOrderHeader PRIMARY KEY CLUSTERED (SalesOrderID);
CREATE UNIQUE NONCLUSTERED INDEX Ix_Test_SalesOrderHeader
ON test.SalesOrderHeader(SalesOrderID);
-- Test 2 - Nonclustered primary key and clustered index
CREATE UNIQUE CLUSTERED INDEX Ix_Test_SalesOrderHeader
ON test.SalesOrderHeader(SalesOrderID);
ALTER TABLE test.SalesOrderHeader
ADD CONSTRAINT PK_Test_SalesOrderHeader PRIMARY KEY NONCLUSTERED (SalesOrderID);
-- Test 3 - Clustered primary key only
ALTER TABLE test.SalesOrderHeader
ADD CONSTRAINT PK_Test_SalesOrderHeader PRIMARY KEY CLUSTERED (SalesOrderID);
-- Same for all tests
ALTER TABLE test.SalesOrderDetail
ADD CONSTRAINT PK_Test_SalesOrderDetail PRIMARY KEY CLUSTERED (SalesOrderDetailID);
ALTER TABLE test.SalesOrderDetail
ADD CONSTRAINT FK_Test_SalesOrderDetail_SalesOrderHeader FOREIGN KEY (SalesOrderID) REFERENCES test.SalesOrderHeader(SalesOrderID);
-- Update 100 records in SalesOrderDetail
UPDATE test.SalesOrderDetail
SET SalesOrderID = SalesOrderID + 1
WHERE SalesOrderDetailID BETWEEN 57800 AND 57899;
Actual execution plan for test 1.
Actual execution plan for test 2. The estimated subtree cost for the Index Seek operator is almost identical to test 1.
Actual execution plan for test 3. The estimated subtree cost for the Index Seek is more than double test 1 or test 2.
And here is a query that measures the sizes of the indexes. (Test 1 configuration.) You can clearly see that the clustered index is much bigger.
-- Measure sizes of indexes
SELECT I.object_id, I.name, I.index_id, I.[type], I.[type_desc], SUM(s.used_page_count) * 8 AS 'IndexSizeKB'
FROM sys.indexes AS I
INNER JOIN sys.dm_db_partition_stats AS S
ON S.[object_id] = I.[object_id] AND S.index_id = I.index_id
WHERE I.[object_id] = OBJECT_ID('test.SalesOrderHeader')
GROUP BY I.object_id, I.name, I.index_id, I.[type], I.[type_desc];
Here are some references that explain clustered indexes and nonclustered indexes.
TechNet > Tables and Index Data Structures Architecture: https://technet.microsoft.com/en-us/library/ms180978(v=sql.105).aspx
Training kit 70-462 Administering Microsoft SQL Server 2012 Databases > Chapter 10: Indexes and Concurrency > Lesson 1: Implementing and Maintaining Indexes
Microsoft SQL Server 2012 Internals by Kalen Delaney > Chapter 7: Indexes: internals and management
Yes i am very well aware the consequences. But i just want to reorder them. Start from 1 to end.
How do I go about reordering the keys using a single query ?
It is clustered primary key index
Reordering like
First record Id 1
second record Id 2
The primary key is Int
Drop PK constraint
Drop Identity column
Re-create Identity Column
Re-Create PK
USE Test
go
if(object_id('IdentityTest') Is not null)
drop table IdentityTest
create table IdentityTest
(
Id int identity not null,
Name varchar(5),
constraint pk primary key (Id)
)
set identity_insert dbo.IdentityTest ON
insert into dbo.IdentityTest (Id,Name) Values(23,'A'),(26,'B'),(34,'C'),(35,'D'),(40,'E')
set identity_insert dbo.IdentityTest OFF
select * from IdentityTest
------------------1. Drop PK constraint ------------------------------------
ALTER TABLE [dbo].[IdentityTest] DROP CONSTRAINT [pk]
GO
------------------2. Drop Identity column -----------------------------------
ALTER table dbo.IdentityTest
drop column Id
------------------3. Re-create Identity Column -----------------------------------
ALTER table dbo.IdentityTest
add Id int identity(1,1)
-------------------4. Re-Create PK-----------------------
ALTER TABLE [dbo].[IdentityTest] ADD CONSTRAINT [pk] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
--------------------------------------------------------------
insert into dbo.IdentityTest (Name) Values('F')
select * from IdentityTest
IDENTITY columns are not updatable irrespective of SET IDENTITY_INSERT options.
You could create a shadow table with the same definition as the original except for the IDENTITY property. Switch into that (this is a metadata only change with no movement of rows that just affects the table's definition) then update the rows and switch back though.
A full worked example going from a situation with gaps to no gaps is shown below (error handling and transactions are omitted below for brevity).
Demo Scenario
/*Your original table*/
CREATE TABLE YourTable
(
Id INT IDENTITY PRIMARY KEY,
OtherColumns CHAR(100) NULL
)
/*Some dummy data*/
INSERT INTO YourTable (OtherColumns) VALUES ('A'),('B'),('C')
/*Delete a row leaving a gap*/
DELETE FROM YourTable WHERE Id =2
/*Verify there is a gap*/
SELECT *
FROM YourTable
Remove Gaps
/*Create table with same definition as original but no `IDENTITY`*/
CREATE TABLE ShadowTable
(
Id INT PRIMARY KEY,
OtherColumns CHAR(100)
)
/*1st metadata switch*/
ALTER TABLE YourTable SWITCH TO ShadowTable;
/*Do the update*/
WITH CTE AS
(
SELECT *,
ROW_NUMBER() OVER (ORDER BY Id) AS RN
FROM ShadowTable
)
UPDATE CTE SET Id = RN
/*Metadata switch back to restore IDENTITY property*/
ALTER TABLE ShadowTable SWITCH TO YourTable;
/*Remove unneeded table*/
DROP TABLE ShadowTable;
/*No Gaps*/
SELECT *
FROM YourTable
I don't think there is any way to do this in a single query. Your best bet is to copy the data to a new table, drop and recreate the original table (or delete the data and reseed the identity) and reinsert the data in the original order using the previous identity as the ordering (but not re-inserting it).
CREATE TABLE Table1_Stg (bla bla bla)
INSERT INTO Table1_Stg (Column2, Column3,...) SELECT Column2, Column3,... FROM Table1 ORDER BY Id
Here the Id column is excluded from the SELECT column list.
Or, you can do:
SELECT * INTO Table1_Stg FROM Table1 ORDER BY Id
DROP Table1
sp_rename Table1_stg Table1
Please lookup the usage for sp_rename as I am doing this from memory.
Hope this helps.
EDIT: Please save a script with all your indexes and constraints if any on Table1.
EDIT2: Added second method of creating table and inserting into table.
UPDATE tbl SET id = (SELECT COUNT(*) FROM tbl t WHERE t.id <= tbl.id);
This last statement is genius. Just had to remove the primary key from the table design first and make sure under the design option Identity Specifications is set to no. Once you run the query set these options back.
I am student of RDBMS.
I have very basic question let say I have one existing Table in SQL server. What will be script to alter table.
Drop Column 'RowId' if exist.
Drop contraint if exist.
Add one new column 'RowId' into table.
Make this column as primary key.
Autoincrement type int.
In SQL Server 2005 or newer, you could use this script:
-- drop PK constraint if it exists
IF EXISTS (SELECT * FROM sys.key_constraints WHERE type = 'PK' AND parent_object_id = OBJECT_ID('dbo.YourTable') AND Name = 'PK_YourTable')
ALTER TABLE dbo.YourTable
DROP CONSTRAINT PK_YourTable
GO
-- drop column if it already exists
IF EXISTS (SELECT * FROM sys.columns WHERE Name = 'RowId' AND object_id = OBJECT_ID('dbo.YourTable'))
ALTER TABLE dbo.YourTable DROP COLUMN RowId
GO
-- add new "RowId" column, make it IDENTITY (= auto-incrementing)
ALTER TABLE dbo.YourTable
ADD RowId INT IDENTITY(1,1)
GO
-- add new primary key constraint on new column
ALTER TABLE dbo.YourTable
ADD CONSTRAINT PK_YourTable
PRIMARY KEY CLUSTERED (RowId)
GO
Of course, this script may still fail, if other tables are referencing this dbo.YourTable using foreign key constraints onto the pre-existing RowId column...
Update: and of course, anywhere I use dbo.YourTable or PK_YourTable, you have to replace those placeholder with the actual table / constraint names from your own database (you didn't mention what they were, in your question.....)
Note: this answer was added before questions update
Add new column (note: you can only have one IDENTITY column per table)
Drop old primary key
Add new primary key
Drop old column if needed
Sample script:
CREATE TABLE whatever (
OldPKColumn uniqueidentifier NOT NULL,
CONSTRAINT PK_whatever PRIMARY KEY (OldPKColumn)
)
ALTER TABLE whatever
ADD RowId int NOT NULL IDENTITY (1,1);
ALTER TABLE whatever
DROP CONSTRAINT PK_whatever;
ALTER TABLE whatever WITH CHECK
ADD CONSTRAINT PK_whatever PRIMARY KEY CLUSTERED (RowId);
ALTER TABLE whatever
DROP COLUMN oldPKcolumn;
And a random thought... are you trying to reset an IDENTITY column?
If so, then use DBCC CHECKIDENT
Just a comment to improve these great answers (can't use comments yet - I'm one reputation point away from that privilege) and as future reference for myself:
A new IDENTITY (autonumber) column can be added and made the primary key in a single statement as well:
ALTER TABLE [TableName] ADD [ColumnName] int IDENTITY PRIMARY KEY;
I prefer not to bother with constraint names when it doesn't help.
You can specify seed (and increment) values between parantheses after the IDENTITY keyword.