Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create nonclustered index in Create Table?

Create table FavoriteDish    
(    
FavID int identity (1,1) primary key not null,    
DishID int references Dishes(DishID) not null ,    
CelebrityName nvarchar(100)  nonclustered not null     
)

This results in

Incorrect syntax near the keyword 'nonclustered'.

I referred to the MSDN help for the create table syntax. I am not sure whats wrong here.

like image 844
Rasshme Chawla Avatar asked Apr 22 '10 10:04

Rasshme Chawla


People also ask

Can I create index on Create Table statement?

It is possible to create a primary key or unique index within a SQL Server CREATE TABLE statement.

Can we create non-clustered index on table variable?

Inline index creation on table variables. The new syntax works on table variables, too! This means that with SQL Server 2014 and higher, you can create non-unique nonclustered indexes on table variables. You can even set the fillfactor option.

Can we create inline index with Create Table command?

The new syntax was introduced which allows you to create certain index types inline with the table definition. These could be at column level, concerning just that column, or at the table level, with indexes containing several columns.


2 Answers

The help in books online does in fact mention the keyword CLUSTERED, but it is only relevant for UNIQUE or PRIMARY KEY constraints. Both these constraints create an index, and you can specify if that index is to be clustered or non-clustered.

You cannot use that syntax to create a standard non clustered index.

Create table FavoriteDish    
(    
FavID int identity (1,1) primary key not null,    
DishID int references Dishes(DishID) not null ,    
CelebrityName nvarchar(100)   constraint ux_CelebrityName unique NONCLUSTERED not null     
)
like image 125
edosoft Avatar answered Oct 13 '22 02:10

edosoft


Erase this nonclustered keyword and use CREATE INDEX statement to add index to this table, documentation of this can read in:

http://msdn.microsoft.com/en-us/library/ms188783.aspx

Syntax is here:

CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name 
    ON <object> ( column [ ASC | DESC ] [ ,...n ] ) 
    [ INCLUDE ( column_name [ ,...n ] ) ]
    [ WHERE <filter_predicate> ]
    [ WITH ( <relational_index_option> [ ,...n ] ) ]
    [ ON { partition_scheme_name ( column_name ) 
         | filegroup_name 
         | default 
         }
    ]
    [ FILESTREAM_ON { filestream_filegroup_name | partition_scheme_name | "NULL" } ]

[ ; ]

Code is here:

CREATE NONCLUSTERED INDEX index_clustered ON FavoriteDish(CelebrityName asc)
like image 22
Svisstack Avatar answered Oct 13 '22 03:10

Svisstack