Is having a field in primary key constraint optimizes sorting of the table ?
Here's the schema of the table:
CREATE TABLE Persons (
Field1 long NOT NULL,
Field2 long NOT NULL,
Field3 long NOT NULL,
Field4 long NOT NULL,
Filed5 long NOT NULL,
CONSTRAINT PK_Person PRIMARY KEY (Field1 Asc,Field2 Asc,Field3 Asc,Field4 Asc));
The sorting query: Select * from Persons order by Field4
The field4
in primary key constraint doesn't provide any uniqueness with respect to values.
The only reason it's added is to optimize the sorting on field4
, since sorting on a column that does have an clustered index helps in optimization.
In short, Is having the field4
in primary key constraint helping with the optimization of the above sorting query, even though the primary key constraint is created using ascending order of field
1 then field2
then field3
and the field4
?
Best Answer
It could help some variations of your query. Take this setup for instance:
The query you gave as example:
There's a Sort operation to put things in the order you requested.
But this query has a different plan:
With equality predicates across the columns leading up to your chosen Sort order, the order of data in your index is supported.
I'm not sure how often you're truly selecting every column with no filter, but if you have more restrictive queries that index may work out for your needs.