I'm using database projects in Visual Studio and I'm looking to make a unique index with a where clause on table creation, rather than having to create the table and add another script to add the constraint to the index. My constraint is
CREATE UNIQUE NONCLUSTERED INDEX ix_IdNotNull
ON MyTable(MyId)
WHERE MyId IS NOT NULL;
I'm looking for something like
create table MyTable
(
MyId int unique where MyId is not null
)
but SSMS doesn't like this. Is it possible to assign a where clause to a unique constraint when the table is created?
Add NC UNIQUE index
For sql 2016 +
create table MyTable
(
MyId int ,
INDEX [i_MyTable] UNIQUE NONCLUSTERED (MyId) WHERE [MyId] IS NOT NULL
)
early version
CREATE UNIQUE NONCLUSTERED INDEX [i_MyTable]
ON [MyTable] (MyId)
WHERE [MyId] IS NOT NULL
Related
to enable incremental update statistics i have to create partition function, partition scheme, index on my table and create table in this way
create table [tmp].[PartitionTest]
(
[RecordId] int not null
,[CreateDate] datetime
,[Quantity] int
) on [ups_partionByDate_scheme226] ([CreateDate])
But, when I can't create table like and add this line
on [ups_partionByDate_scheme226] ([CreateDate])
Can I do this by alter table or other way?
Yes.
If your table has a clustered index, then you need to drop it and after that you can use the following code snippet. If you have no cluster index, skip the previous sentence.
ALTER TABLE [tmp].[PartitionTest] ADD CONSTRAINT [PK_ParitionTest_CreateDate] PRIMARY KEY CLUSTERED
(
[CreateDate]
) ON [ups_partionByDate_scheme226] ([CreateDate]);
See also Create Partitioned Tables and Indexes
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 use SQL Server 2008.
I am trying to create a nonclustered index on my table. I want to check if there exists a way to create this without giving a name to the index.
For e.g.
CREATE TABLE #mytable (Date_ datetime NOT NULL, ID_ varchar(10) NOT NULL, Value_)
When I add a PK to this table, I do not specify the name of that key. For e.g.
ALTER TABLE #mytable ADD PRIMARY KEY CLUSTERED (Date_ ASC, ID_ ASC)
Is it possible to do something similar to create a nonclustered index without specifying a name?
For e.g.
ALTER TABLE #mytable ADD NONCLUSTERED INDEX (Date_, Value_) -- FAILS!!!
The only command I know is
CREATE NONCLUSTERED INDEX *keyname* ON #mytable (Date_, Value_)
After create temp table execute dynamic sequel with guid as index name
DECLARE #NewId VARCHAR(64) = REPLACE(NEWID(),'-','');
EXEC('CREATE INDEX IX_'+#NewId+' ON #Table (ColA,ColB) INCLUDE (ColZ)');
No, it is not possible to create a non-clustered index without a name, the syntax is quite clear:
CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name
index_name
Is the name of the index. Index names must be unique within a table or
view but do not have to be unique within a database. Index names must
follow the rules of identifiers.
CREATE INDEX (Transact-SQL)
The database object name is referred to as its identifier. Everything
in Microsoft SQL Server can have an identifier. Servers, databases,
and database objects, such as tables, views, columns, indexes,
triggers, procedures, constraints, and rules, can have identifiers.
Identifiers are required for most objects, but are optional for some
objects such as constraints.
Database Identifiers
Can I create a non-unique index during the CREATE TABLE statement in SQLServer 2012? I've found some pre-release documents referencing this, but when I try it, it doesn't work. It looks like that didn't make it into the release, but I'd like to get a more definitive answer.
The document indicated you could do something like:
create table rm.test (
t1 int not null,
t2 int,
constraint pk_t1 primary key (t1),
index idx_t2 (t2)
)
However, it complains on the "index". Is there a way to do this or am I stuck with doing a CREATE INDEX after the table is created?
No.
The inline index definition is new for SQL Server 2014.
In this case you can do
CREATE TABLE rm.test
(
t1 INT NOT NULL CONSTRAINT pk_t1 PRIMARY KEY,
t2 INT,
CONSTRAINT idx_t2 UNIQUE NONCLUSTERED (t2, t1)
)
Which actually creates the same thing though.
Primary keys are the clustered index by default and the CI key gets appended to non unique non clustered keys implicitly to guarantee uniqueness.
Is it possible to create a clustered index from a create table statement in SQL Server 2008 that is not a primary key?
The purpose of this is for a table in SQL Azure, so it is not an option for me to first create the table, and then create the clustered index on the table.
Edit: Apparently it was FluentMigrator that was causing my problems, it's version table does not have a clustered index so it was erroring trying to create the versioning table not my table.
Yes, it is possible to create a clustered index that is not the primary key. Just use a CREATE CLUSTERED INDEX statement.
CREATE TABLE dbo.myTable (
myTableId int PRIMARY KEY NONCLUSTERED
myColumn int NOT NULL
)
CREATE CLUSTERED INDEX myIndex ON dbo.myTable(myColumn)
Prior to version Azure SQL Database v12, you had to have a clustered index before you could insert any data to a table. As of Azure SQL Database v12, heaps (tables without a clustered index) are now supported.
If your database was created prior to June 2016, here are the instructions for upgrading to version 12.
CREATE TABLE dbo.Table_1
(
Id int NOT NULL IDENTITY (1, 1) PRIMARY KEY NONCLUSTERED,
SomeOtherUniqueColumn int NOT NULL CONSTRAINT Item4 UNIQUE CLUSTERED
) ON [PRIMARY]
note the specification of nonclustered on the primary key
This will still work.
CREATE TABLE dbo.Table_1
(
SomeOtherUniqueColumn int NOT NULL CONSTRAINT Item4 UNIQUE CLUSTERED
) ON [PRIMARY]
The code below is compatible with Azure. It creates a primary key non-clustered and a clustered index in a single create table statement. This syntax also allows for specifying more than one column in your key.
CREATE TABLE MyTable (
ID uniqueidentifier NOT NULL,
UserID uniqueidentifier NOT NULL,
EntryDate DATETIME NOT NULL,
CONSTRAINT PK_MyPrimaryKey_Name PRIMARY KEY NONCLUSTERED (ID),
CONSTRAINT UCI_MyClusteredIndexName UNIQUE CLUSTERED (UserID ASC,EntryDate ASC,ID ASC)
);
In order to change a tables clustered index, the clusteredd index must be dropped, which converts the table into a heap and then the new clustered index is applied. Because Azure does not support heaps (tables without clustered indexes) it is not possible to change the clustered index without dropping the table and recreating it. In Azure you can not specify a clustered index in any other place other than the table create statement.