I am using SQL Server 2008 and I have a situation where I have view that within my application code I always order by a date contained therein, so I was wondering about efficiency etc.
I came across this blog post SQL Server – Order a View that explains that it is possible to order a view so instead of:
CREATE VIEW v
AS
SELECT a,b,d FROM t
GO
SELECT a,b,d FROM v ORDER BY d
I could do:
CREATE VIEW v
AS
SELECT TOP(100) PERCENT a,b,d FROM t ORDER BY d
GO
SELECT a,b,d FROM v
and get the same result.
My question is, which of the above is the more efficient?
If I want it to be as fast as possible would I be better off with the second approach or does it make no difference and sql server will work it all out the same regardless?
complementing Remus answer, if you have a view
vlike your that contains:SELECT a,b,d FROM tonce you do
SELECT a,b,d FROM v ORDER BY dyou are actually doing
SELECT a,b,d FROM t ORDER BY dbecause a regular (non-indexed) view exists only as s SQL statement on the DB, so once SQL sees select * from view, it replaces with the view definition before generating the execution plan that will be run