Question

Is it possible to create a table in SQL Server database , where one column is primary and other column has clustered index , as shown below

create table tablename ( id int primary key , contact int clustered index)

what will be the order of data?

Was it helpful?

Solution

It is possible to create a table where one column is the PK and other column has a clustered index, like this:

CREATE TABLE TableName
(ID INT NOT NULL PRIMARY KEY,
Contact INT NOT NULL UNIQUE CLUSTERED)
GO

SQL Server will automatically create a Primary Key as a non-clustered index as clustered index is specified on another column.

The order of data is never guaranteed in any RDBMS.

OTHER TIPS

In SQL Server you can create a clustered index on any column(s) that can be indexed. It doesn't have to be the same column(s) as your primary key and nor does the clustered index have to be a unique one.

There is really no such thing as one true "order of data" in SQL Server. The logical ordering of pages within a clustered index is maintained as a doubly linked list whereby each data page points to the next and the previous page. When you create a clustered index these pages are usually to some degree "adjacent" pages on disk but SQL Server doesn't attempt to maintain any physical ordering and will split a page and allocate new ones elsewhere as required. The logical order of rows within a data page is defined by a slot array on each page - rows are stored in allocation order, not cluster key order within a page even in a clustered index.

Those logical orderings of pages and rows don't necessarily have anything to do with the order of rows you see in your query results however. So the proper answer to your question is that the order is whatever you want it to be when you specify an ORDER BY clause in your queries. If you don't specify ORDER BY then that order is undefined.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top