Are there performance differences between views and in-line table functions? - sql

I'm currently torn between a design decision between using a view and an in-line table function, where the argument in favor of the view is that it's a simple SELECT, but the argument for the table function is consistency, as we already have hundreds of objects in the database that do require parameters, and thus, use a table function.
Given that we have a table, dbo.Data, a view, dbo.vData, and an in-line table function, dbo.tfData():
Our scenario is that we already have several table functions for the same table along the lines of dbo.tfDataFilterBy(parameter), so having consistency when querying is a definite plus. Performance is a significant factor in which direction we would go.
The new view and table function both just do a simple SELECT * FROM dbo.Data. I've tested some basic scenarios selects, joins, and aggregates and the execution plans are identical as far as I can tell. However, are there any edge cases that can potentially produce a different execution plan between the two of them, perhaps with a lot of complex joins, sub-queries, or anything else we might throw at it?

The two are defined in different manners, but the sql engine builds them from the base tables in much the same way.(Hence your execution plans being the same)
Keep in mind, views can in fact update the underlying base tables, so be careful with that difference.
See: https://www.red-gate.com/simple-talk/sql/learn-sql-server/sql-view-basics/
for some good info on uses of views.
If you reuse a view a lot across your application(s), you could define it as an indexed view. SQL server then materializes the view as a table. This creates some overhead with maintaining the index when you make updates to your table, but the indexed view could improve read performance substantially. Also, in Enterprise Edition, the optimizer can use the indexed view if it meets the requirements of a query even if it is not referenced directly.
An occasion in favor of table functions would be one where you need to change the definition of the table very slightly on a regular basis, you would not want to maintain multiple views that are so close in definition. Also, a table function can take a parameter that can be used in your predicates to change the output without changing the function, with views you would need different views defined with different predicates.
These are not the only differences, but are probably the two most influential when deciding which to use.
More directly related to performance: there should not be much difference in execution plan UNLESS you utilize a view enough that the optimizer materializes the table from the definition.

Related

Is it bad to call views inside a View in sql

I have created 8 different views and i am using all these views inside a view.
So i was wondering before i go any further with this idea. i want to know does it affects performance too badly or not.
No, it's fine. In many cases I personally consider it preferable to writing one view with a giant and difficult to understand definition. In my opinion, using multiple views allows you to:
Encapsulate discrete logic in individual views.
Re-use logic in the individual views without having to repeat the logic (eliminating update problems later).
Name your logic so that it's easier for the next programmer to understand what you were trying to accomplish.
Views get "compiled" away during execution plan creation. Therefore there is only a very small penalty for using them: The extra time it takes SQL Server to look up the definition. Usually this delay is not measurable.
That means using views for the purposes mentioned by Larry Lustig is perfectly fine and encourage-able.
HOWEVER: Make sure that you do not introduce unnecessary JOINs using this technique. While SQL Server has mechanisms to eliminate unneeded tables from a query it quickly gives up if the query becomes to complex. Executing those additional JOINs can cause a significant slowdown. This is the reason that many companies have a no-view-rule in place.
So: Use views, but make sure to not misuse them.
It's not bad for performance just for being a view. It may add some complexity to maintain, and cause additional consideration when you want to change the schema of the underlying tables. If you were using views and they joined to the same tables, I think that would be less efficient than joining to the table once in one view.
I favour using nested views, with each view encapsulating and naming some cross section of data.
As for performance, it can actually improve performance if the alternative required that same data to be queried multiple times: A nested view is a bit like a temporary table - fired once.
The best, and recommended, way to discover performance implications is to try both options and examine the explain output.
The pure fact of querying a view from within a view does not have any negative performance implications. It is not different from querying a table from within a view.

Is there a reason not to use views in Oracle?

I have recently noticed that nobody uses views in my company (and it's a big company).
I want to create a few views largely because they make my queries simpler to the eye, and these views are on somewhat big tables that don't get very frequent updates (once a day).
My alternative is to create a type table of type record an populate it each time a SP is called. Is this better than using a view? (my guess is no)
PS: database is oracle 10g and
EDIT:
- yes i have asked around but no one could give me a reason.
- both the views and the queries that will be using them are heavy on joins.
Aesthetics doesn't have a place in SQL, or coding in general, when there's performance implications.
If the optimizer determines that predicate pushing can occur, a view will be as good as directly querying the table(s) the view represents. And as Justin mentions, because a view is a macro that expands into the underlying query the view represents -- a soft parse (re-use of the query from cache) is very likely because the cache check needs to match queries exactly.
But be aware of the following:
layering views (one view based on another) is a bad practice -- errors won't be encountered until the view is run
joining views to other tables and or views is highly suspect -- the optimizer might not see things as well if the underlying query is in place of the view reference. I've had such experiences, because the views joined to were doing more than what the query needed -- sometimes, the queries from all the views used were condensed into a single query that ran much better.
I recommend creating your views, and comparing the EXPLAIN plans to make sure that you are at least getting identical performance. I'd need to see your code for populating a TYPE before commenting on the approach, but it sounds like a derived table in essence...
It's possible you would benefit from using materialized views, but they are notorious restricted in what they support.
It certainly sounds like creating some views would be helpful in this case.
Have you asked around to see why no one uses views? That seems quite odd and would certainly tend to indicate that you're not reusing your SQL very efficiently. Without views, you'd tend to put the same logic in many different SQL statements rather than in a single view which would make maintenance a pain.
One reason not to use views which may or may not be valid... is that they have the potential to create complexity where there isn't any
For example I could write
CREATE VIEW foo as <SOME COMPLEX QUERY>
then later I could write
CREATE Procedure UseFoo as
BEGIN
SELECT
somefields
FROM
x
INNER JOIN foo
.....
So now I'm creating to objects that need to be deployed, maintained, version controlled etc...
Or I could write either
CREATE Procedure UseFoo as
BEGIN
WITH foo as (<SOME COMPLEX QUERY>)
SELECT
somefields
FROM
x
INNER JOIN foo
.....
or
CREATE Procedure UseFoo as
BEGIN
SELECT
somefields
FROM
x
INNER JOIN <SOME COMPLEX QUERY> foo
.....
And now I only need to deploy, maintain, and version control a single object.
If <SOME COMPLEX QUERY> only exists in one context maintaining two separate objects creates an unnecessary burden. Also after deployment any changes to requires evaluating things that rely on UseFoo. When two object you need to visit anything that evaluating on UseFoo and Foo
Of course on the other hand if Foo represents some shared logic the evaluation is required anyway but you only have to find and change a single object.
It has been my experience that when you have a large/complex database and some complex queries and no views, it is just because the users just don't know what views are, or how to use them. Once I explained the benifits of using a view, most people used them with out any problems.
From your description, I would just make a view, not a new table.
Views are great for hiding complexity -- if your users can just run the views you create as-is (as opposed to writing a query against the view), this is good.
But views also come with performance issues -- if your users know how to write sql, and they understand the tables they're using, it might be better to let them keep doing that.
Consider also that stored procedures are less prone to (the same) performance issues that views are.
here is a link to and a snippet from a nice article that describes views as well as how to tune them for better peformance.
Uses of Views
Views are useful for providing a horizontal or vertical subset of data
from a table (possibly for security reasons) ; for hiding the
complexity of a query; for ensuring that exactly the same SQL is used
throughout your application; and in n-tier applications to retrieve
supplementary information about an item from a related table......
http://www.smart-soft.co.uk/Oracle/oracle-tuning-part4-vw-use.htm

Are MySql Views Dynamic and Efficient?

I'm looking to create a view of a table which will highlight data that meets a specific criteria. For example, if I have a table with integer values, I want my view to show the rows which have a value greater than 100. I know how to achieve this by creating a view on a table, however is the view dynamic? I have tested this in MySQL and it seems to be true. But if my table has over 1000 rows, is this efficient? Will the view still update "dynamically" to any changes in the original table?
Basically, there are basically 2 types of views in MySQL.
Merge Views
This type of view basically just re-writes your queries with the view's SQL. So it's a short-hand for writing the queries yourself. This offers no real performance benefit, but make writing complex queries easier and making maintenance easier (since if the view definition changes, you don't need to change 100 queries against the view, only the one definition).
Temptable Views
This type of view creates a temporary table with the query from the view's SQL. It has all the benefits of the merge view, but also reduces lock time on the view's tables. Therefore on highly loaded servers it could have a fairly significant performance gain.
There's also the "Undefined" view type (the default), which let's MySQL pick what it thinks is the best type at query time...
But note something important to note, is that MySQL does not have any support for materialized views. So it's not like Oracle where a complex view will increase the performance of queries against it significantly. The queries of the views are always executed in MySQL.
As far as the efficiency, Views in MySQL do not increase or decrease efficiency. They are there to make your life easier when writing and maintaining queries. I have used views on tables with hundreds of millions of rows, and they have worked just fine...
mysql does not use indexes on temp tables...so it can badly affect your performance.

View or User Defined Function?

I have a scenario where I combine two tables into one (using UNION) and also JOIN data from some other tables.
I can do this either with a VIEW or a UDF/User Defined Function.
Considering that I have no view so far at all in my database, but quite a few UDF's for fulltext search and the like, I'm tempted to use a UDF for this scenario as well to keep it "clean".
However, this is entirely subjective and I wondered if there is a better objective reason to go for either a VIEW or a UDF in this scenario.
I did compare query plans for both and they are the exact same so I don't believe there is a performance penalty or advantage for using either one.
Is there other reason to choose one over the other or does it not matter?
I would always use features in order of sophistication. A view is relatively straightforward in terms of performance profile and security management. I would probably use it first.
I'm assuming you are talking about an inline table-valued UDF, which will pretty much have identical performance characteristics. Security on a UDF is a little different and you cannot have instead of triggers to be able to do "inserts" on the view. A benefit of the UDF would be that you can force parameters to be supplied, thereby ensuring usage patterns are as expected, whereas a view can be queried without any criteria (perhaps accidentally).
If you did end up wanting to have a UDF for parameterization, you could layer it on top of the view (so no code duplication) and you should find that the performance is not affected significantly, because the optimizer can combine views and inline TVF fairly successfully.
One advantage i see by using this scenario as view is to index them and use them as "indexed views" where unlike a traditional view there is physical file that is created and therefore querying is faster where there are considerable amount of rows in it. The very effect of using this is to bypass the joins and unions for all the rows instead only build them for new rows.
As our friend Cade suggested, you cud use a view inside a UDF to keep it clean and it isn't a lot different.
Hope this helps !

Is a view faster than a simple query?

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.
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.
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:
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.
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.
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.
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.
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.
It may be faster if you create a materialized view (with schema binding). Non-materialized views execute just like the regular query.
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.
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.
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.
There should be some trivial gain in having the execution plan stored, but it will be negligible.
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.
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+
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.
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.
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.
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.
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