Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server creating table with clustered index without a primary key

Tags:

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.

like image 556
Chris Marisic Avatar asked Nov 30 '11 21:11

Chris Marisic


People also ask

Is primary key required for clustered index?

When you create a PRIMARY KEY constraint, a unique clustered index on the column or columns is automatically created if a clustered index on the table does not already exist and you do not specify a unique nonclustered index. The primary key column cannot allow NULL values.

Can we create table without primary key in SQL Server?

Should you create a database table without a primary key? No. Every table should have some column (or set of columns) that uniquely identifies one and only one row. It makes it much easier to maintain the data.

Can we create non-clustered index without clustered index SQL Server?

Generally, nonclustered indexes are created to improve the performance of frequently used queries not covered by the clustered index or to locate rows in a table without a clustered index (called a heap). You can create multiple nonclustered indexes on a table or indexed view.


2 Answers

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.

like image 59
Rob Boek Avatar answered Oct 15 '22 04:10

Rob Boek


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]
like image 20
Buildstarted Avatar answered Oct 15 '22 04:10

Buildstarted