Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ORDER BY honoured in SQL Server views?

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.

like image 790
Toby Allen Avatar asked May 05 '11 17:05

Toby Allen


People also ask

Can we use ORDER BY in views in SQL Server?

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.

Why can't we put ORDER BY inside the view?

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.

What does it mean by ORDER BY 1?

it means order by the very first column from the select list.

Why do we use ORDER BY 1 in SQL?

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.


2 Answers

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.

like image 118
Quassnoi Avatar answered Sep 20 '22 10:09

Quassnoi


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

like image 28
SQLMenace Avatar answered Sep 18 '22 10:09

SQLMenace