You can't. Relational databases have no concept of ordering the rows in a table. If you want ordered output, you must use an ORDER BY
clause. This is a fundamental fact and is not something you can work around.
In SQL Server 2000, in (essentially) error, Microsoft allowed views to have an ORDER BY
clause, which did order the output. However, in SQL Server 2005 this was changed because it was never really right to operate that way.
You could try the SELECT TOP (2147483647) * FROM dbo.Blah B ORDER BY B.Col;
trick, but that won't cut it in later versions of SQL Server, either. The ordering behavior of TOP
is a side effect, not a main effect, and shouldn't be relied on in a view. Do it right and put sorting where it should be: in the presentation layer or in the final, outer query that is submitted to the database (ala SELECT Columns FROM dbo.View ORDER BY X;
).
A little more on not ordering rows in a table: yes, there are clustered indexes, but you can't rely on the data returning ordered for several reasons:
- A nonclustered index may be used to satisfy the query, so the clustered index's ordering will have no impact on the output rowset's ordering.
- There may be no clustered index at all on the table.
- While each clustered index page's rows are less than the next page and greater than the previous page, the rows inside each page are not themselves ordered.
- Parallelism can change the order that rows are produced as one stream may return faster or slower than others.
- During query execution, if another process is already reading some of the rows that will satisfy the current query, that data may be borrowed for the current query out of order in order to save reads (after which the current query will fetch only the remaining rows it is missing).
There is one simple, reliable, and required way to get an ordered rowset: ORDER BY
.