I am using MS SQL server 2005
I have a table with 3 columns where I store user-message mapping like:
msg_for msg_from msg_id
bob bob 1
bob john 1
bob steve 1
bob bob 2
bob john 2
bob bob 3
bob john 3
bob steve 3
The PK is on 3 columns and msg_id is FK to messages table that stores the messages
The above is the physical storage I see according to the PK on 3 columns
Now my query MUST return the messages for a given user having latest msg at top (order by msg_id DESC)
bob john 3
bob steve 3
bob john 2
bob steve 2
bob john 1
bob steve 1
This mapping table has millions of rows. I see 95% of the cost is to SORT the result.
Is it possible to have the PK or some other way store data physically like this (avoid SORT)?
msg_for msg_from msg_id
bob bob 3
bob john 3
bob steve 3
bob bob 2
bob john 2
bob bob 1
bob john 1
bob steve 1
Thanks
Yes.
When you set up the Primary Key (or any index) you can define this
SQL Server can scan in either direction so it only makes sense if you want to control the sort order combination for multiple columns.
Edit: You say in the comments that the problem query is
The issue here isn’t one of Ascending, Descending.
To give an analogy. Phone books are listed in surname, forename order but if you needed to know the lexicographically last 10 forenames in the directory you would need to scan the whole book. This would be unavoidable regardless of whether or not within each section forenames were listed in ascending or descending order.
Similarly the composite index keys would need to be
msg_for, msg_id, msg_fromto satisfy this query optimally notmsg_for, msg_from, msg_idWith this latter order it will still need to scan the whole section of the index satisfying themsg_for = @user_namecriteria as it cannot know if there will be a latermsg_idstill to come belonging to a latermsg_fromAdditionally regardless in which directionmsg_idis sorted in their individual sub sections a sequential scan of themsg_for = @user_namepart of the index will still require a sort as it they are fragmented by being in subsections according tomsg_from.