views:

122

answers:

4

We have a (large) SELECT query, that can take ~30 seconds to run. I am told that when placed in a view, it takes less than 5 seconds to run.

My assumption is that SQL Server caches query plans for queries that don't change, so why the massive improvement in performance here?

Just to be clear, this really is just a case of taking something like:

select * from table /* Lots of joins, where clauses */

and making it a view:

create view myfirstview as select * from table /* Lots of joins, most of the where clauses */
select * from myfirstview where /* The rest of the where clauses (i.e. the ones that can change) */
+1  A: 

Maybe what was told to you is Indexed Views. Materialized Views is the standard term

Michael Buen
They are the same thing, no? And it's not the default in SQL Server
gbn
Hahah I was about to tell you "look at gbn's answer for more insight, he knows what I mean" And then, I see your answer. Ok, I also knew that the default of view is the macro expansion, critical systems adheres to the rule that "you don't pay for what you don't use", and RDBMS is no exception. As any self-respecting DBAs or application developers are aware that indexed/materialized views can cause deadlock http://sqlblog.com/blogs/alexander_kuznetsov/archive/2009/06/02/be-ready-to-drop-your-indexed-view.aspx, they will not presume that indexed/materialized is the default
Michael Buen
+3  A: 

No, a view that is not indexed/materialised is expanded like a macro.

There is no special "view" magic despite what you have been told.

gbn
+4  A: 

"I am told"..... have you checked and verified that yourself?

I'd be surprised, quite honestly.... a "regular" view is just a SQL statement that's stored - no caching, nothing

Unless they're talking about an indexed view ("materialized" view) which is really a system-maintained table in the end - the data is stored on disk like for a normal table.

This is no longer really a view - even though it's still called a view ;-) Those indexed views (with a clustered index) can be extremely fast - since they store the actual data that makes up the view like a table would.

marc_s
Just to add that it also depends on the edition. EE will automatically consider an indexes view during optimization. SE will **not**. To make SE (and lower) use the actual indexed view, the query must add the `WITH (NOEXPAND)` hint.
Remus Rusanu
+1  A: 

I would wager that the person who told you this did a test something like this:

First, time how long the SELECT by itself takes Next, time how long the VIEW takes

The problem is that the SELECT causes SQL Server to read a bunch of data in from disk. Once in memory, the query will execute faster. You would notice a similar improvement if you just ran the SELECT twice, or if you reversed the order of the two queries above.

For a true apples-to-apples comparison, run the following commands before each query:

CHECKPOINT
DBCC DROPCLEANBUFFERS
RickNZ