tags:

views:

96

answers:

3

I've created a sql view and I need to sort the results of select by using the ORDER BY on 4 fields, but I'm getting message that ORDER BY cannot be used in views unless I use TOP. Can someone explain why TOP is needed, and does someone have a workaround for sorting in a sql view?

Thanks.

A: 

If using SQL Server, you can do

select top 100 percent * 
from MyTable 
order by MyColumn

Of course you shouldn't use an * in your view, I just used it here for brevity.

RedFilter
since 2005 the sql optimizer removes this order by so this doens't work! be careful with that.
Mladen Prajdic
Do you have a reference?
RedFilter
sure! directly from the sql server query optimizer team:http://blogs.msdn.com/queryoptteam/archive/2006/03/24/560396.aspx
Mladen Prajdic
Thanks, haven't used that since SQL 2000 days - I agree with some of the comments on that page that ORDER BY should be illegal since not always honoured.
RedFilter
The "Top 100 percent" worked. And it seems like the hotfix is in since it is sorting properly by the 4 fields.Thanks for all the help responses.Erwin
Erwin
if it's working it's purely by chance. don't be surprised when sometime in the future your logic based on this breaks.
Mladen Prajdic
+6  A: 

you don't need to sort a view. a view is like a table so you sort it when you select from it:

select * from yourView order by yourColumns
Mladen Prajdic
*The* correct answer
gbn
+1  A: 

There is no guarantee the output of the view will be ordered

Only the outermost ORDER BY applies for result sets: not any inner ones. So only this ORDER BY can be guaranteed to work:

SELECT col1, col2, FROm MyView ORDER BY col2

You can add it to views or derived tables and it forces "intermediate materialisation" because the results have to be ordered. However, for SQL Server 2005 and above, you have to use TOP 2000000000 not TOP 100 PERCENT (except for that HF that Daniel Vassallo mentioned!)

Someone will use your view with a different order to that internally at some point too.

gbn