Is a view faster than a simple query?

SqlSql ServerPerformance

Sql Problem Overview


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.

Sql Solutions


Solution 1 - Sql

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

Microsoft's own documentation makes it very clear that Views can improve performance.

First, most views that people create are simple views and do not use this feature, and are therefore no different to querying the base tables directly. 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.

Solution 2 - Sql

Generally speaking, no. Views are primarily used for convenience and security, and won't (by themselves) produce any speed benefit.

That said, SQL Server 2000 and above do have a feature called Indexed Views that can greatly improve performance, with a few caveats:

  1. Not every view can be made into an indexed view; they have to follow a specific set of guidelines, which (among other restrictions) means you can't include common query elements like COUNT, MIN, MAX, or TOP.
  2. Indexed views use physical space in the database, just like indexes on a table.

This article describes additional benefits and limitations of indexed views:

> You Can… > > * The view definition can reference one or more tables in the > same database. > * Once the unique clustered index is created, additional nonclustered > indexes can be created against the view. > * You can update the data in the underlying tables – including inserts, > updates, deletes, and even truncates. > > You Can’t… > > * The view definition can’t reference other views, or tables > in other databases. > * It can’t contain COUNT, MIN, MAX, TOP, outer joins, or a few other > keywords or elements. > * You can’t modify the underlying tables and columns. The view is > created with the WITH SCHEMABINDING option. > * You can’t always predict what the query optimizer will do. If you’re > using Enterprise Edition, it will automatically consider the unique > clustered index as an option for a query – but if it finds a “better” > index, that will be used. You could force the optimizer to use the > index through the WITH NOEXPAND hint – but be cautious when using any > hint.

Solution 3 - Sql

EDIT: I was wrong, and you should see Marks answer above.

I cannot speak from experience with SQL Server, 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.

Solution 4 - Sql

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.

Solution 5 - Sql

It may be faster if you create a materialized view (with schema binding). Non-materialized views execute just like the regular query.

Solution 6 - Sql

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.

Solution 7 - Sql

My understanding is that a while back, a view would be faster because SQL Server could store 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.

Solution 8 - Sql

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.

Solution 9 - Sql

It all depends on the situation. MS SQL Indexed views are faster than a normal view or query but indexed views can not be used in a mirrored database invironment (MS SQL).

A view in any kind of a loop will cause serious slowdown because the view is repopulated each time it is called in the loop. Same as a query. In this situation a temporary table using # or @ to hold your data to loop through is faster than a view or a query.

So it all depends on the situation.

Solution 10 - Sql

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

Solution 11 - Sql

In my finding, using the view is a little bit faster than a normal query. My stored procedure was taking around 25 minutes (working with a different larger record sets and multiple joins) and after using the view (non-clustered), the performance was just a little bit faster but not significant at all. I had to use some other query optimization techniques/method to make it a dramatic change.

Solution 12 - Sql

Select from a View or from a table will not make too much sense.

Of course if the View does not have unnecessary joins, fields, etc. You can check the execution plan of your queries, joins and indexes used to improve the View performance.

You can even create index on views for faster search requirements. http://technet.microsoft.com/en-us/library/cc917715.aspx

But if you are searching like '%...%' than the sql engine will not benefit from an index on text column. If you can force your users to make searches like '...%' than that will be fast

referred to answer on asp forums : https://forums.asp.net/t/1697933.aspx?Which+is+faster+when+using+SELECT+query+VIEW+or+Table+

Solution 13 - Sql

Against all expectation, views are way slower in some circumstances.

I discovered this recently when I had problems with data which was pulled from Oracle which needed to be massaged into another format. Maybe 20k source rows. A small table. To do this we imported the oracle data as unchanged as I could into a table and then used views to extract data. We had secondary views based on those views. Maybe 3-4 levels of views.

One of the final queries, which extracted maybe 200 rows would take upwards of 45 minutes! That query was based on a cascade of views. Maybe 3-4 levels deep.

I could take each of the views in question, insert its sql into one nested query, and execute it in a couple of seconds.

We even found that we could even write each view into a temp table and query that in place of the view and it was still way faster than simply using nested views.

What was even odder was that performance was fine until we hit some limit of source rows being pulled into the database, performs just dropped off a cliff over the space of a couple of days - a few more source rows was all it took.

So, using queries which pull from views which pull from views is much slower than a nested query - which makes no sense for me.

Solution 14 - Sql

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.

Solution 15 - Sql

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.

Solution 16 - Sql

I ran across this thread and just wanted to share this post from Brent Ozar as something to consider when using availability groups.

Brent Ozar bug report

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnIdolView Question on Stackoverflow
Solution 1 - SqlMark BrittinghamView Answer on Stackoverflow
Solution 2 - SqlBradCView Answer on Stackoverflow
Solution 3 - SqlRyan GuillView Answer on Stackoverflow
Solution 4 - SqlCharles BretanaView Answer on Stackoverflow
Solution 5 - SqlOtávio DécioView Answer on Stackoverflow
Solution 6 - SqlJordanView Answer on Stackoverflow
Solution 7 - SqlE.J. BrennanView Answer on Stackoverflow
Solution 8 - SqlTony AndrewsView Answer on Stackoverflow
Solution 9 - SqlDasbootView Answer on Stackoverflow
Solution 10 - SqlJosephStyonsView Answer on Stackoverflow
Solution 11 - SqlktaView Answer on Stackoverflow
Solution 12 - SqlMohammad Reza ShahrestaniView Answer on Stackoverflow
Solution 13 - SqlIanView Answer on Stackoverflow
Solution 14 - Sqlkeithwarren7View Answer on Stackoverflow
Solution 15 - SqlCAReedView Answer on Stackoverflow
Solution 16 - SqlJohnHView Answer on Stackoverflow