views:

3374

answers:

12

Is a

select *  from myView

faster than the query itself to create the view (in order to have the same resultSet):

select * from ([query to create same resultSet as myView])

?

It's not totally clear to me if the view uses some sort of caching making it faster compared to a simple query.

Any help would be appreciated!

+24  A: 

Yes, views can have a clustered index assigned and, when they do, they'll store temporary results that can speed up resulting queries.

Update: At least three people have voted me down on this one. With all due respect, I think that they are just wrong; Microsoft's own documentation makes it very clear that Views can improve performance.

First, simple views are expanded in place and so do not directly contribute to performance improvements - that much is true. However, indexed views can dramatically improve performance.

Let me go directly to the documentation:

After a unique clustered index is created on the view, the view's result set is materialized immediately and persisted in physical storage in the database, saving the overhead of performing this costly operation at execution time.

Second, these indexed views can work even when they are not directly referenced by another query as the optimizer will use them in place of a table reference when appropriate.

Again, the documentation:

The indexed view can be used in a query execution in two ways. The query can reference the indexed view directly, or, more importantly, the query optimizer can select the view if it determines that the view can be substituted for some or all of the query in the lowest-cost query plan. In the second case, the indexed view is used instead of the underlying tables and their ordinary indexes. The view does not need to be referenced in the query for the query optimizer to use it during query execution. This allows existing applications to benefit from the newly created indexed views without changing those applications.

This documentation, as well as charts demonstrating performance improvements, can be found here.

Update 2: the answer has been criticized on the basis that it is the "index" that provides the performance advantage, not the "View." However, this is easily refuted.

Let us say that we are a software company in a small country; I'll use Lithuania as an example. We sell software worldwide and keep our records in a SQL Server database. We're very successful and so, in a few years, we have 1,000,000+ records. However, we often need to report sales for tax purposes and we find that we've only sold 100 copies of our software in our home country. By creating an indexed view of just the Lithuanian records, we get to keep the records we need in an indexed cache as described in the MS documentation. When we run our reports for Lithuanian sales in 2008, our query will search through an index with a depth of just 7 (Log2(100) with some unused leaves). If we were to do the same without the VIEW and just relying on an index into the table, we'd have to traverse an index tree with a search depth of 21!

Clearly, the View itself would provide us with a performance advantage (3x) over the simple use of the index alone. I've tried to use a real-world example but you'll note that a simple list of Lithuanian sales would give us an even greater advantage.

Note that I'm just using a straight b-tree for my example. While I'm fairly certain that SQL Server uses some variant of a b-tree, I don't know the details. Nonetheless, the point holds.

Update 3: The question has come up about whether an Indexed View just uses an index placed on the underlying table. That is, to paraphrase: "an indexed view is just the equivalent of a standard index and it offers nothing new or unique to a view." If this was true, of course, then the above analysis would be incorrect! Let me provide a quote from the Microsoft documentation that demonstrate why I think this criticism is not valid or true:

Using indexes to improve query performance is not a new concept; however, indexed views provide additional performance benefits that cannot be achieved using standard indexes.

Together with the above quote regarding the persistence of data in physical storage and other information in the documentation about how indices are created on Views, I think it is safe to say that an Indexed View is not just a cached SQL Select that happens to use an index defined on the main table. Thus, I continue to stand by this answer.

Mark Brittingham
Ryan's point is a good one: the point of a view isn't to improve performance (despite the small improvement I point out). It is to simplify other queries or standardize access to data.
Mark Brittingham
Query plans are stored in the plan cache for both views and ordinaary SQL queries, based on query/view parameters. For both, they are dropped from the cache when they have been unused for a long enoujgh period and the space is needed. After which, if the same query is issued, it is recompiled.
Charles Bretana
People - RTFM; as Charles said - ever ordinary SQL queries get plan caching.
keithwarren7
Yes, indexed views can dramatically improve performance. But indexed views are not just "views", and generally speaking, normal "view" aren't faster than their associated queries.
BradC
Brad, I think that the reason that many ppl don't use indexed views is that they simply don't know about them. This is a shame: they're very useful! So, technically, you are correct. Nonetheless, I think my answer is a good one - especially given SO's role as a mutual help environment.
Mark Brittingham
@Mark, an indexed view DOES increase performance, but NOT because it's a view. It increases performance because it's indexed. In fact, if an indexed view exists, you get teh same performance boost from an ordinary SQL statement that can use that index, even if it references the table, not the view.
Charles Bretana
i.e., It's not the "view" in an indexed view that generates the increased performance, it's the "index".
Charles Bretana
Charles - keep in mind the caching of data as well. For example, if I index a set of fields in a table, I gain an advantage. If I create a *View* with a subset of the dataset and then create an index, I get the advantage of both the Index AND the view - because the index is now smaller.
Mark Brittingham
@Charles - it doesn't matter if it's the index, the fact that a view can leverage the index and a raw query can't is enough
annakata
/applaud @Mark for standing his ground and rationally arguing this one out
annakata
@Mark, actually, the index is no smaller when created in a view than it is if created on it's own.
Charles Bretana
@annkata, That's unfortunately, exactly my point. a raw query CAN access and leverage any index, even one created with an indexed view, just as the view can.
Charles Bretana
@Mark, an "indexed view" is just stored SQL (the view), and an index (as defined by the create index statement) which is dependant only on the columns defined in the index, completely independant of the view it was defined on. You could equivilently create an index and an unindexed View
Charles Bretana
Thanks annakata - I don't mind backing off or admitting I'm wrong. I've had to do it enough that I'm well-practiced!
Mark Brittingham
Charles - can you provide documentation of your assertion that the View only uses the index on the underlying table? My understanding is that the index is created on the subset of data extracted for the view - thus my explanation.
Mark Brittingham
I have updated the response to reflect some additional research. Sorry Charles, I think it is pretty clear that you are incorrect on this one so I continue to stand by my answer.
Mark Brittingham
Oh, man, I've gotten 8 downvotes on this one! I'm amazed that people would downvote so quickly without at least having Charles' courage to argue their point.
Mark Brittingham
@Mark, No problem, I'm sorry if I misunderstand your comment, but if I read you correctly, you misunderstood me. I didn't say that it ONLY uses the index on the underlying table, I said that the index you are creating is an independant object from the view, and can be used by ANY query on the Tbl
Charles Bretana
@Mark, you can test this for yourself, Create your indexed view, run a query using the view, and examine the query execution plan. It will clearly show the index being used. Then run the same query using Direct SQL From the table, not the view. The execution plan will be same, using same index.
Charles Bretana
i.e. Select * from View Where [Columns defined in index on View] - To make query sargable and allow use of index. Then Select * From Table Where [Same predicates here as above]Execution plans will be identical. with identical performance
Charles Bretana
@Charles - then I think we agree. In fact, this is probably the basis for MS's claim that the indexed "view" will be used by queries that don't even use the View itself. Good catch and you are right - I did misinterpret you. Sorry!
Mark Brittingham
But if the view didn't exist and therefore the index didn't exist, the raw query wouldn't be able to use it. And which DBs are capable of this index sharing?
annakata
@annakata, My point was, you can create the index independently, "Create Index MyIndexname On TableName (ColumnA, ColumnB, etc.)" and get exactly the same performance increase on ALL SQL queries without creating a View
Charles Bretana
@Mark, Right on.. Thx for taking the time and effort of "listening" carefully.
Charles Bretana
@Annakata, the ONLY reason for creatingt an Indexed view is if you need the performance increase of a SECOND CLUSTERED index, and cannot replace an existing clustered index (on the table) with the "correct" clustered index for the query you are trying to tune. con't ...
Charles Bretana
Since a table can only have one clusterdee index, and you CAN create a separate clustered index on a view, (since the fields in the clustered index are independently persisted in the index pages), this is a cheat (work-arounnd?) that allows you to get TWO clustered indices on one Table.
Charles Bretana
AnnaKata - on a *completely* different topic...are you a fan of Portal - the game? I ask this because of your profile image/icon.
Mark Brittingham
+2  A: 

I cannot speak from experience with sqlserver, but for most databases the answer would be no. The only potential benefit that you get, performance wise, from using a view is that it could potentially create some access paths based on the query. But the main reason to use a view is to simplify a query or to standardize a way of accessing some data in a table. Generally speaking you won't get a performance benefit. I may be wrong though.

I would come up with a moderately more complicated example and time it yourself to see.

Ryan Guill
another reason for views is to assist access control in role based models
annakata
You are wrong about the performance improvements. I did not explain enough to convince some people in my original comment but MS has explicit documentation on how to use views to improve performance. See my (now heavily downvoted) response below.
Mark Brittingham
+2  A: 

It may be faster if you createa materialized (WITH SCHEMABINDING) view. Non materialized views execute just like the regular query.

Otávio Décio
schemabinding has little to do with performance, it binds the schema of the view to the underlying table so it stays in sync and is a pre-req for indexed views.
Sam Saffron
+1  A: 

My understanding is that a while back, a view would be faster because SQL Server can stored an execution plan and then just use it instead of trying to figure one out on the fly. I think the performance gains nowadays is probably not as great as it once was, but I would have to guess there would be some marginal improvement to use the view.

EJB
This was my understanding: used to matter, doesn't any more
annakata
Doesn't from a performance standpoint - does as a means of access restriction. But that would be another topic. ;)
AnonJr
oh sure, *lots* of good reasons to be using views, not a single one to use raw queries :P
annakata
+2  A: 

I would expect the two queries to perform identically. A view is nothing more than a stored query definition, there is no caching or storing of data for a view. The optimiser will effectively turn your first query into your second query when you run it.

Tony Andrews
If the view is a small set of fields and those fields are then covered with an index is SQL Server clever enough to use that covering index when fulfilling the second form of query?
AnthonyWJones
A: 

There is no practical different and if you read BOL you will find that ever your plain old SQL SELECT * FROM X does take advantage of plan caching etc.

keithwarren7
A: 

It may help to review this question.

David Santamaria
+8  A: 

In SQL Server at least, Query plans are stored in the plan cache for both views and ordinary SQL queries, based on query/view parameters. For both, they are dropped from the cache when they have been unused for a long enough period and the space is needed for some other newly submitted query. After which, if the same query is issued, it is recompiled and the plan is put back into the cache. So no, there is no difference, given that you are reusing the same SQL query and the same view with the same frequency.

Obviously, in general, a view, by it's very nature (That someone thought it was to be used often enough to make it into a view) is generally more likely to be "reused" than any arbitrary SQL statement.

Charles Bretana
A: 

There should be some trivial gain in having the execution plan stored, but it will be negligible.

JosephStyons
A: 

The purpose of a view is to use the query over and over again. To that end, SQL Server, Oracle, etc. will typically provide a "cached" or "compiled" version of your view, thus improving its performance. In general, this should perform better than a "simple" query, though if the query is truly very simple, the benefits may be negligible.

Now, if you're doing a complex query, create the view.

+1  A: 

Definitely a view is better than a nested query for SQL Server. Without knowing exactly why it is better (until I read Mark Brittingham's post), I had run some tests and experienced almost shocking performance improvements when using a view versus a nested query. After running each version of the query several hundred times in a row, the view version of the query completed in half the time. I'd say that's proof enough for me.

Thanks Jordan...glad to hear that all this theory works out in the *real* world.
Mark Brittingham
+12  A: 

Generally speaking, no. Views are primarily used for convenience and security, not for speed improvements.

That said, SQL Server 2000 and above do have a special feature called Indexed Views that can greatly improve performance, but you have to create indexed views following a very specific set of guidelines.

There is an important reference in Books Online in regards to view resolution.

Here is an article that describes the benefits and creation of indexed views:

For many years, Microsoft® SQL Server™ has supported the ability to create virtual tables known as views. Historically, these views served these main purposes:

  • To provide a security mechanism that restricts users to a certain subset of data in one or more base tables.

  • To provide a mechanism that allows developers to customize how users can logically view the data stored in base tables.

With SQL Server 2000, the functionality of SQL Server views was expanded to provide system performance benefits. It is possible to create a unique clustered index on a view, as well as nonclustered indexes, to improve data access performance on the most complex queries. In SQL Server 2000 and 2005, a view that has a unique clustered index is referred to as an indexed view.

BradC