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
Related
Does temp table with PK and identity creates clustered index internally in sql server. Or we have to create explicitly?
I was working on SP optimization, and came across one article which says that #Temp table with bulk data can have temp db out of memory issue. i reduced #Table size to only few required columns which stores only int columns. Now considering sort operation, for actual table has some benefit of PK and Clusterd Index. so i was curious does #table utilize the same capabilities of SQL.
IDENTITY is purely a property of a column, like NOT NULL. It isn't CLUSTERED, nor is it a PRIMARY KEY unless you tell SQL Server so.
CREATE TABLE T (ID int IDENTITY); will not create an index on the column ID, nor will be be indexed.
The only way you would create a CLUSTERED INDEX on an IDENTITY column would be by using synnax for declare it as your CLUSTERED PRIMARY KEY in your create, altering your table to add the IDENTITY column as a CLUSTERED PRIMARY KEY or creating a CLUSTERED INDEX on the column (as your primary key and Clustered Index don't have to be the same column).
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
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 want to create a table which store USERNAME and DOMAIN(both are col. name of same table).
One User can only belong to one domain.
and the The Domain values can be stored in the another table, lets call it "LIST".
Set in your users table domain_id (as relation with domain), then use constraints for two columns (username and domain_id).
MySql example:
ALTER TABLE users ADD UNIQUE unique_index (username, domain_id);
P.S. Look for analog in SQL server. (see example in comments)
I suggest this kind of script to create your tables and put on them determined conditions:
--Create table that will store domains
CREATE TABLE DICT_DOMAINS (
DomainID int IDENTITY(1,1),
DomainName nvarchar(255),
CONSTRAINT [PK_DICT_DOMAINS] PRIMARY KEY CLUSTERED (DomainID ASC)
)
--DomainNames must be unique so we add non clustered index
CREATE UNIQUE NONCLUSTERED INDEX [UX_DICT_DOMAINS_DomainName] ON DICT_DOMAINS (DomainName ASC)
--Create table to store users and there domains
CREATE TABLE USERS_DOMAINS (
DomainID int,
UserName nvarchar(255)
)
--Add foreign key to DICT_DOMAINS table
ALTER TABLE USERS_DOMAINS WITH CHECK ADD CONSTRAINT [FK_USERS_DOMAINS_DICT_DOMAINS] FOREIGN KEY (DomainID)
REFERENCES DICT_DOMAINS (DomainID)
--Usernames must be uniq, no need to add DomainsId to this index
--This is sufficient to provide condition that
--One User can only belong to one domain.
CREATE UNIQUE NONCLUSTERED INDEX [UX_USERS_DOMAINS_UserName] ON USERS_DOMAINS (UserName ASC)
Is the following possible? I am unable to do so. Do I have to have a permanent table to create index?
declare #Beatles table
(
LastName varchar(20) ,
FirstName varchar(20)
)
CREATE CLUSTERED INDEX Index_Name_Clstd ON #Beatles(LastName)
Not on a table variable, but on a temp table see this http://www.sqlteam.com/article/optimizing-performance-indexes-on-temp-tables
No, you cannot create indices on a table variable - see this article here and this posting here comparing local, global temporary tables to table variables.
Restrictions
You cannot create a non-clustered
index on a table variable, unless the
index is a side effect of a PRIMARY
KEY or UNIQUE constraint on the table
(SQL Server enforces any UNIQUE or
PRIMARY KEY constraints using an
index).
According to this post - YES you can.
The following declaration will generate 2 indexes:
DECLARE #Users TABLE
(
UserID INT PRIMARY KEY,
UserName VARCHAR(50),
FirstName VARCHAR(50),
UNIQUE (UserName,UserID)
)
The first index will be clustered, and will include the primary key.
The second index will be non clustered and will include the the columns listed in the unique constraint.
Here is another post, showing how to force the query optimizer to use the indexes generated dynamically, because it will tend to ignore them (the indexes will be generated after the execution plan is evaluated)