In this answer to What are the downsides of using SqlServer Views?, hyprsleepy suggests the ORDER BY
clause is not honoured in views in SQL Server.
Could anyone explain why this is the case?
Edit: Thanks for the answers, but I'm not sure thats the issue. I know you cant add an Order By Clause to a view and I dont have a problem with that, you just add it to the SELECT
statement when calling the view, but my impression from the other question was that using an Order By Clause in a SELECT
statement on a view will not give the correct results every time.
The ORDER BY clause is not valid in views, inline functions, derived tables, and subqueries, unless either the TOP or OFFSET and FETCH clauses are also specified. When ORDER BY is used in these objects, the clause is used only to determine the rows returned by the TOP clause or OFFSET and FETCH clauses.
Views behave like tables whose contents are determined by the results of a query. Tables don't have order; they're just bags of rows. Therefore, views don't have order either.
it means order by the very first column from the select list.
The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.
SQL Server
developers assume that any set operation may change the order of the records so there is no point to use ORDER BY
in the intermediate set definitions and it only makes sense in the final statements.
The views may be used in joins or other operations which invalidates their orders.
Since you cannot use the view by itself, i. e. you don't write vMyView
, you rather write SELECT * FROM vMyView
, despite the fact that the view is a SELECT
per se, you can (and should) append the ORDER BY
clause to the SELECT
statement as well if you need an order.
This is quite a sane assumption and in fact it makes the code more clear.
Take a look at Create a sorted view in SQL Server 2005 and SQL Server 2008
There is a way to do it but it is not supported, just issue an order by when selecting from the view
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With