T-SQL: Order By ColA, ColB --means--> Create Index ... (ColA, ColB), right? [SQL Server 2005]

Using the table below if I wish to have the most efficient two-level Order By as such:
select * from Simple order by ColA, ColB
The composite index should be ColA, ColB, right?  Or is it ColB, ColA?
CREATE INDEX SimpleIndex ON Simple (ColA,ColB);
create table Simple (
  PK int,
  ColA int,
  ColB int
);

Open in new window

LVL 2
ZuZuPetalsAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
EvilPostItConnect With a Mentor Commented:
Yes you are correct. You will effectivly be running through the index from begining to end and pulling the relevant information.
0
 
Raja Jegan RConnect With a Mentor SQL Server DBA & ArchitectCommented:
Simply depends upon the usage and Cardinality of the columns.
If ColB is used most in WHERE clauses to uniquely identify records, then order should be ColB, ColA else you can have it as ColA, ColB
0
 
ZuZuPetalsAuthor Commented:
@rrjegan17: So, for Order By ONLY, is the index ordering irrelevant? Let's say I never use the columns in a WHERE clause... is the index ColA,ColB the exact same as ColB, ColA?  Or, does index order matter for the Order By?
0
 
EvilPostItConnect With a Mentor Commented:
No if you were to test this you would see in the query plan that an index scan is used on both clustered and nonclustered indexes.

If you were to use a where clause it would be a seek.
0
 
Raja Jegan RConnect With a Mentor SQL Server DBA & ArchitectCommented:
>> So, for Order By ONLY, is the index ordering irrelevant?

Yes, it would be used in ORDER BY along with columns involved in WHERE clause.
Say if you have WHERE ColB = ? referenced in your query, then Index with order ColB, ColA would be used whereas ColA, ColB would not be used at all.

>> Let's say I never use the columns in a WHERE clause... is the index ColA,ColB the exact same as ColB, ColA?  

Yes, if it is not used in both ORDER BY and WHERE conditions, then it is exactly the same.
Hope that clarifies.
0
All Courses

From novice to tech pro — start learning today.