Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clustered vs NonClustered Primary Key

begin transaction;
create table person_id(person_id integer primary key);
insert into person_id values(1);
... snip ...
insert into person_id values(50000);
commit;

This code takes about 0.9 seconds on my machine and creates a db file taking up 392K. These numbers become 1.4 seconds and 864K if I change the second line to

create table person_id(person_id integer nonclustered primary key);

Why is this the case?

like image 306
Elite Mx Avatar asked Jan 26 '10 09:01

Elite Mx


People also ask

Should primary key be clustered or nonclustered?

It's more efficient to create a clustered primary key.

What is the difference between clustered and nonclustered?

A clustered index is used to define the order or to sort the table or arrange the data by alphabetical order just like a dictionary. A non-clustered index collects the data at one place and records at another place. It is faster than a non-clustered index. It is slower than the clustered index.

Should a primary key be clustered?

By default a primary keys gets to be the clustered index key too, but this is not a requirement. The primary key is a logical concept: is the key used in your data model to reference entities. The clustered index key is a physical concept: is the order in which you want the rows to be stored on disk.

Which is better clustered or nonclustered index?

A clustered index may be the fastest for one SELECT statement but it may not necessarily be correct choice. SQL Server indices are b-trees. A non-clustered index just contains the indexed columns, with the leaf nodes of the b-tree being pointers to the approprate data page.

What is clustered and non-clustered primary key in SQL Server?

A cluster index is a type of index that sorts the data rows in the table on their key values, whereas the Non-clustered index stores the data at one location and indices at another location.

What is the difference between primary key and clustered index?

If Primary Keys are good at uniquely identifying each row in a data table, Clustered Indexes are good at finding the specific rows quickly. A Clustered Index actually sorts the table using the values in the specified column.


1 Answers

A great answer to this question is available over at the DBA StackExchange: https://dba.stackexchange.com/questions/7741/when-should-a-primary-key-be-declared-non-clustered/7744#7744

like image 143
Ryan Kirkman Avatar answered Oct 24 '22 09:10

Ryan Kirkman