Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does primary key order matter?

I recently set up a class in an EntityFramework project which designated a couple of its members as a composite key.

However, when it came to time to create the database from this it gave the error

Unable to determine composite primary key ordering for type 'NNNNN'. Use the ColumnAttribute or the HasKey method to specify an order for composite primary keys.

I know how to solve the problem, but I was just wondering why it cares about the order. Isn't a composite primary key just a set of columns on which to key the records, without any particular ordering necessary?

like image 212
Stephen Holt Avatar asked May 23 '13 11:05

Stephen Holt


People also ask

Does the order of a primary key matter?

It matters because the order of primary keys matter in the database. Since primary keys are (usually) clustered, and always indices, whether the key is ordered as First Name, Last Name, SSN or SSN, Last Name, First Name, makes a huge difference.

Why is the choice of the primary key important?

Each database table needs a primary key because it ensures row-level accessibility. If you choose an appropriate primary key, you can specify a primary key value, which lets you query each table row individually and modify each row without altering other rows in the same table.

Does order matter with Superkey?

A set has no inherent order. This said, the key (a,b) is the same as the key (b,a) , because they contain the same elements. As to superkeys: Yes, that's just combinatorics.

Is primary key always sorted?

In SQL Server: no, by it's clustering key - which default to the primary key, but doesn't have to be the same. The primary key's main function is to uniquely identify each row in the table - but it doesn't imply any (physical) sorting per se.


1 Answers

It matters because the order of primary keys matter in the database. Since primary keys are (usually) clustered, and always indices, whether the key is ordered as First Name, Last Name, SSN or SSN, Last Name, First Name, makes a huge difference. If I only have the SSN when I'm querying the table, and the PK is the only index, I'll see GREAT performance with the latter, and a full table scan with the former.

like image 51
Bill Gregg Avatar answered Nov 15 '22 17:11

Bill Gregg