441

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JohnIdol
  • 48,899
  • 61
  • 158
  • 242

17 Answers17

817

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.

E_net4
  • 27,810
  • 13
  • 101
  • 139
Mark Brittingham
  • 28,545
  • 12
  • 80
  • 110
  • 6
    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 Jan 13 '09 at 14:14
  • 1
    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 Jan 13 '09 at 14:18
  • 1
    People - RTFM; as Charles said - ever ordinary SQL queries get plan caching. – keithwarren7 Jan 13 '09 at 14:19
  • 32
    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 Jan 13 '09 at 16:17
  • 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 Jan 13 '09 at 16:30
  • 1
    @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 Jan 13 '09 at 16:35
  • 1
    i.e., It's not the "view" in an indexed view that generates the increased performance, it's the "index". – Charles Bretana Jan 13 '09 at 16:37
  • 2
    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 Jan 13 '09 at 16:51
  • 12
    @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 Jan 13 '09 at 17:36
  • 228
    /applaud @Mark for standing his ground and rationally arguing this one out – annakata Jan 13 '09 at 17:38
  • @Mark, actually, the index is no smaller when created in a view than it is if created on it's own. – Charles Bretana Jan 13 '09 at 17:50
  • @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 Jan 13 '09 at 17:51
  • @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 Jan 13 '09 at 17:55
  • 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 Jan 13 '09 at 18:00
  • 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 Jan 13 '09 at 18:01
  • 1
    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 Jan 13 '09 at 18:32
  • 1
    @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 Jan 13 '09 at 19:00
  • 3
    @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 Jan 13 '09 at 19:02
  • 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 Jan 13 '09 at 19:04
  • 3
    @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 Jan 13 '09 at 19:37
  • 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 Jan 13 '09 at 20:01
  • 2
    @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 Jan 13 '09 at 20:27
  • @Mark, Right on.. Thx for taking the time and effort of "listening" carefully. – Charles Bretana Jan 13 '09 at 20:27
  • @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 Jan 13 '09 at 20:31
  • 9
    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 Jan 13 '09 at 20:34
  • 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 Jan 14 '09 at 00:04
  • http://www.w3schools.com/sql/sql_view.asp : "Note: A view always shows up-to-date data! The database engine recreates the data, using the view's SQL statement, every time a user queries a view." So there seems to be no cache, and it update every time we query the view... – David 天宇 Wong Feb 03 '13 at 09:34
  • @MarkBrittingham If what you say is true, and the index created is somehow limited to only the data present in the view at the moment, is the index structure recreated every time you insert or delete data? – Asad Saeeduddin Feb 20 '14 at 23:27
  • 1
    Wow controversial answer! I agree it is correct, but it could be improved by adding a note about the potential negative performance impacts of indexed views as well. I believe they have all the negatives of regular indexes (space requirements, and decreased insert performance) as well as some unexpected behavior with schemabinding (it makes changing underlying tables more complicated) – rjdevereux Dec 29 '14 at 15:03
  • Good example of Lithuanian market and answered my doubts about view vs table. – saganas Jan 30 '15 at 17:03
  • That should probably read, _"Yes, **if** you can index the view..."_ That's a pretty big caveat. Not all views _can_ be indexed. – canon Mar 10 '15 at 20:46
  • Good example, but indexed views are expensive enough in terms of real money, they are only available in Enterprise edition? – Akash Kava Sep 07 '15 at 05:59
  • 2
    @MarkBrittingham For a demonstration of using Index Views and their effect to prove your words you can include the results from https://www.simple-talk.com/sql/learn-sql-server/sql-server-indexed-views-the-basics/ Also it worth mentioning that Index Views can sometimes be counter productive: http://sqlblog.com/blogs/alexander_kuznetsov/archive/2009/06/02/be-ready-to-drop-your-indexed-view.aspx – Saber Mar 14 '17 at 07:14
  • Masterfully explained and defended @MarkBrittingham – abydal Feb 07 '18 at 22:45
  • 2
    The only complaint I have with StackOverflow is that you can only upvote once. I have been debating this point for years, and no matter how many benchmark tests you run, or how many queries you compare, many refuse to believe it -- its like debating climate change with someone that doesn't believe in science. If one query runs in a 1 minute using sub-queries, and the other in under 1 sec using views, the debate is over. Thank you @MarkBrittingham for articulating the points so well! – Shanemeister Apr 26 '18 at 13:58
  • I'm sure using views will outrun using queries only in most of your test scenarios. But the right answer is a "(most) probably" and not a definite "yes"! Data must be collected when you use a view at least once after every update on the table (especially when you hit records that are in the view). This will run a query on the table for the view and then there will be the actual query on the view. In worst case those 2 queries might be slower than just one query on the updated table. – Bitterblue May 24 '18 at 14:48
  • 1
    I ran into an issue tonight where I execute a query against a view that's as simple as `SELECT * FROM MyView`. It took 2 minutes and 34 seconds to run. If I run the underlying query of the view, it runs in 2 seconds. Another more complex query that is referencing the view also runs slowly, but when I replace the referenced view in the query with a nested select, it runs much faster. Why do you think this is happening? My general experience is that using views makes queries easier to read or to reuse but do not improve performance. – Jim Berg Jun 09 '18 at 04:06
  • Microsoft document down (https://www.microsoft.com/technet/prodtechnol/sql/2005/impprfiv.mspx) – gies0r Apr 28 '19 at 19:08
  • @MarkBrittingham I'm assuming that all you said hold true for a oracle database as well. Is it? Because other answers seem to have a conflict with yours. – Eswar Jun 25 '19 at 12:53
  • 1
    This may speed up read-intensive workloads, but may also slow down write-intensive workloads (probably a rare case though). As always, benchmark your particular case. – atablash Jun 27 '19 at 07:49
  • 1
    This is good piece of information. Maybe simplified as "Views enable you to create clustered indexes on multiple tables" – toraman Dec 12 '20 at 13:28
  • Is a view faster than a simple query: sometimes but most of the time it's identical and there is a real problem with people thinking it's a magic fixing wand. – Nick.Mc Nov 14 '22 at 04:10
61

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.
Community
  • 1
  • 1
BradC
  • 39,306
  • 13
  • 73
  • 89
  • 4
    totally disagree... reading from a view allows the SQL to be rewritten.. and it's generally FASTER to read from a view (than from a dump of the view). – Aaron Kempf Jan 09 '13 at 20:23
  • @AaronKempf, I'd love to see some reference on that, that hasn't been my experience. When I search for "view SQL rewritten", all the results I get refer to Oracle, not SQL server, e.g. http://docs.oracle.com/cd/E14072_01/server.112/e10810/qrbasic.htm – BradC Jan 09 '13 at 21:18
  • I was just doing some benchmarking on it yesterday, I was stunned.. basically if I take a dump from a view (into a table) any query that I run is SLOWER.. because most queries pass through the view like butter and get rewritten by the query optimizer.. At least that's what I assume. I'll try to write a blog entry on it soon, the benchmarking was quite fascinating stuff.. Basically views help performance tremendously. – Aaron Kempf Jan 10 '13 at 20:58
  • @AaronKempf Not sure that's even the same scenario as the original question (which is about a query vs putting that identical query in a view). Anyway, I can't see how materializing a view into a table would make it SLOWER (that's exactly what an indexed view does), unless your new table doesn't have good indexes. – BradC Jan 10 '13 at 21:37
  • for example.. I have a CONSTANT in a view, and I can demonstrate it is ~99 times faster to hit this CONSTANT instead of the data behind the view – Aaron Kempf Jan 22 '13 at 14:40
  • 11 years later, I've still not found many good candidates for Indexed Views given the "few [small] caveats".. :| – user2864740 Dec 11 '20 at 22:21
16

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.

Community
  • 1
  • 1
Ryan Guill
  • 13,558
  • 4
  • 37
  • 48
  • 2
    another reason for views is to assist access control in role based models – annakata Jan 13 '09 at 14:32
  • 1
    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 Jan 13 '09 at 14:38
14

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
  • 143,358
  • 22
  • 150
  • 216
8

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 Jan 13 '09 at 18:42
  • i have experience with nested view (view in view) and there was very bad performance. When all views was rewrited to sub selects, performance was many times faster, so maybe there is a place to some serious testing. – Muflix Feb 12 '17 at 17:10
  • It sounds like you aren't running the same SQL ('rewriting views'). There could also be some caching involved. – Nick.Mc Nov 14 '22 at 04:13
6

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Otávio Décio
  • 73,752
  • 17
  • 161
  • 228
  • 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 Nov 14 '09 at 21:14
  • is a materialized view and a view the same thing ? i think they are but materiallized view is stored in a disk and a view might just be in memory right ? – j2emanue Sep 20 '20 at 18:20
4

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
E.J. Brennan
  • 45,870
  • 7
  • 88
  • 116
2

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.

Dasboot
  • 21
  • 1
2

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
  • 129,880
  • 21
  • 220
  • 259
  • 1
    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 Jan 13 '09 at 14:18
1

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+

1

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

JosephStyons
  • 57,317
  • 63
  • 160
  • 234
1

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.

Ian
  • 257
  • 1
  • 2
  • 11
1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
kta
  • 19,412
  • 7
  • 65
  • 47
  • How we are writing/designing the query is very important. – kta Oct 07 '11 at 09:28
  • 1
    I have found using CTE's to limit the data returning from a table and then doing all the work/joins, etc off the CTE's has dramatically improved performance in many cases – MattE May 15 '19 at 17:02
0

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
  • 14,094
  • 8
  • 53
  • 74
0

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.

0

No. view is just a short form of your actual long sql query. But yes, you can say actual query is faster than view command/query.

First view query will tranlate into simple query then it will execute, so view query will take more time to execute than simple query.

You can use sql views when you are using joins b/w multiple tables, to reuse complicated query again and again in simple manners.

Billu
  • 2,733
  • 26
  • 47
-2

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

JohnH
  • 105