Faster fetching data from View or Table? - sql

hi we have a stored procedure which is scheduled for daily basis that fetches records from a table having huge data after filtering. my question is if i create a view on the table and fetch the data from the view will this be faster process or slower?

A standard view, it shouldn't make any difference as the inner SQL just gets expanded out into the query. Note, the same applies with inline table-valued user defined functions (think "parameterised view").
However, if you make it an indexed view, then you could see a performance improvement.

Just remember, a view is nothing but a select statement (indexed views are different). If you have:
SELECT * FROM TABLE
And that is in a procedure, if you put the same thing in a view and then did:
SELECT * FROM VIEW
Within a procedure, there is absolutely no difference between these two. But, if things get more complicated so that you're joining against a lot of tables, then it really depends on how they're being accessed.
For example, if you create a view that accesses 6 tables and then you write a query that only needs to pull data from 3 of those tables, you may benefit from a process called simplification that takes place within the optimization process and you'll see a plan that only references 3 tables. However, you might not. If not, then a query that you would write against the 3 tables will generally run faster than a plan against a view that accesses more than 3 tables.
If you start nesting views, having views that call views or join to views, then you may see a very serious performance degradation.
In general, if you're working with stored procedures, I would suggest you just write your queries against the tables directly. It won't hurt performance at all, and it could help you avoid issues with nested views and plan simplification.

just complementing #AdaTheDev answer:
the same applies with table-valued user defined functions
that's true for inline table-valued functions, but not 100% true for a multistatement table-valued function. This second type of function will use a lot more resources (memory) than the first one
About the index view, it can help, but bear in mind that it can drastically will increase your storage space

Related

Is there any benefit to using a TSQL view vs the equivalent stored procedure?

Off the top of my head, I know one major disadvantage of a view vs stored procedure. If stored procedure A references stored procedure B and B gets changed, A will work correctly. But if view A references view B and B gets changed, A will need to be updated to work correctly. IMHO this view behavior just sucks and opens the door to all sorts of subtle bugs.
Well, so how about advantages? Why do people use views at all if they could just always use equivalent stored procedures with names prefixed with vw for clarity?
You cant filter a stored proc without passing in parameters. In a view, you can query it just as you would a table, adding any where clauses as necessary.
SQL Views are used for lot other purposes.
1) Hide a few columns from the original tables and create a view allot permissions only to the view for certain set of users. I guess this is one major use of a view.
2) Combine 2 or more tables, have a derived column
3) Indexed views where unlike normal views have a allocated memory in contrast to that of a normal view where the execution plan shows the usage of main table. So you could actually use the indexed views work efficiently without referencing the main table.
If it's a choice between "select * from vwMyView" and "exec MyProc()", there's not a lot of difference. Both will return a result set that you can use however you'd like. One thing to note is that if you use a view, it can be joined to other tables, which may or may not apply to your situation.
If you want/need to filter the result set, you would want to use a view, as it's simple to add a where clause, where, with a proc, you would need to pass in parameters.
If you want/need to use an existing proc as part of your source, you would need to use a stored procedure, as a view cannot reference a stored procedure.
The "subtle bugs" you mention can occur with either method, though. If you have a view A reference view B, and the query that materializes view B changes (without changing the number of columns returned), anything that depends on view A may break. The same is true of the stored procs: if proc B changes the way its result set is created, proc A may no longer work correctly.
In general, you need to be careful when you have views reference views and procs referencing procs. In addition to the aforementioned issue, you can introduce some pretty serious performance problems.
From my point of view there are 2 major topics:
Caches plan of Stored procedure - this will benefit the execution of SP, although if the view is executed often its plan will also be in the cash.
View can be used in JOINs which can not be done by SP.

Is querying over a view slower than executing SQL directly?

Scenario:
I have 3 tables needing to be joined together, a where clause to limit the result set, and only a few columns from each table being selected. Simple. However, the query to do this isn't very pretty, and when using an ORM between the database and the application, its like trying to put a square peg into a round hole.
My way to get around this is to create a view that embraces the query and now my application model maps directly to a view in the database; no more crazy mapping the ORM layer.
Question:
Assuming no other factors come into play here, will the query against the view incur any additional performance penalties that I wouldn't have hit if I executed the SQL statement directly? - This is not an indexed view, assume the same where clause, keep this simple.
I am being led to believe that a view suffers from extra overhead of "being built". My understanding is that with all else the same, the two should have identical performance.
Please clarify. Thanks!
From MSDN:
View resolution
When an SQL statement references a nonindexed view, the parser and query optimizer analyze the source of both the SQL statement and the view and then resolve them into a single execution plan. There is not one plan for the SQL statement and a separate plan for the view.
There should not be any different performance. Views helps you organize, not any performance enhancement. Unless you are using indexed views.
Only the definition of a nonindexed view is stored, not the rows of the view. The query optimizer incorporates the logic from the view definition into the execution plan it builds for the SQL statement that references the nonindexed view.
In Oracle, the performance is the same. A view is really a named sql statement. But fancier.
When you start nesting views, and joining views with other table or views, things get complicated real quick. If Oracle can't push your filters down the view to the table, it often has to materialize (build a temp table of) parts of the query, and this is when you get the bad performance.

what is the difference (system resource wise) between using views and temporary tables?

what is the difference (system resource wise) between using views and temporary tables? I have a complex report that will be built from numerous tables. I am trying to determine if I should use a series of views or temp tables (SQL 2008). Is there a difference?
A view is just an alias for the query.
A temporary table materializes the resultset.
Views, being just aliases, don't take time to be filled, but they may be less performant when being selected from.
Temporary tables take some time (and effort) to be populated but can be more efficient.
Note that SQL Server optimizer can create a temporary table in runtime from a view (which you will see in the query statistics and plan as Worktable in tempdb), index it and populate it with the rows, and even add the missing rows on demand (these operations are called Eager Spool and Lazy Spool)
This makes the view rewinding much more efficient: instead of reevaluating the whole view each time its results are needed, the results are stored in a temporary table either all at once (as in Eager Spool), or incrementally (as in Lazy Spool).
SQL Server, though, can materialize views by creating clustered indexes on them, though not all views can be indexed (to be indexable, the view must meet certain conditions described here).
View is just a "fixed" SELECT statement with a name. If you have complex query, or in other case, if you want to show only partial data from the table you use view. Views exists in the database you have created it in.
Temporary table is the table like any others, but it is stored in tempdb database and is deleted after you finish stored procedure, etc. (local table). There can be seen only in the scope of the procedure you use it in. There are also global temporary tables, which can be seen outside the procedure.
chances are that an indexed view would probably work for you more than inserting data into temp table/s. also, instead of using a series of views you'd be better of consolidating into one view. it's much easier to manage and will most likely improve performance. also, the right indexes on your source tables will also improve performance.

SQL-Server Performance: What is faster, a stored procedure or a view?

What is faster in SQL Server 2005/2008, a Stored Procedure or a View?
EDIT:
As many of you pointed out, I am being too vague. Let me attempt to be a little more specific.
I wanted to know the performance difference for a particular query in a View, versus the exact same query inside a stored procedure.
(I still appreciate all of the answers that point out their different capabilities)
Stored Procedures (SPs) and SQL Views are different "beasts" as stated several times in this post.
If we exclude some [typically minor, except for fringe cases] performance considerations associated with the caching of the query plan, the time associated with binding to a Stored Procedure and such, the two approaches are on the whole equivalent, performance-wise. However...
A view is limited to whatever can be expressed in a single SELECT statement (well, possibly with CTEs and a few other tricks), but in general, a view is tied to declarative forms of queries. A stored procedure on the other can use various procedural type constructs (as well as declarative ones), and as a result, using SPs, one can hand-craft a way of solving a given query which may be more efficient than what SQL-Server's query optimizer may have done (on the basis of a single declarative query). In these cases, an SPs may be much faster (but beware... the optimizer is quite smart, and it doesn't take much to make an SP much slower than the equivalent view.)
Aside from these performance considerations, the SPs are more versatile and allow a broader range of inquiries and actions than the views.
Unfortunately, they're not the same type of beast.
A stored procedure is a set of T-SQL statements, and CAN return data. It can perform all kinds of logic, and doesn't necessarily return data in a resultset.
A view is a representation of data. It's mostly used as an abstraction of one or more tables with underlying joins. It's always a resultset of zero, one or many rows.
I suspect your question is more along the lines of:
Which is faster: SELECTing from a view, or the equivalent SELECT statement in a stored procedure, given the same base tables performing the joins with the same where clauses?
This isn't really an answerable question in that an answer will hold true in all cases. However, as a general answer for an SQL Server specific implementaion...
In general, a Stored Procedure stands a good chance of being faster than a direct SQL statement because the server does all sorts of optimizations when a stored procedure is saves and executed the first time.
A view is essentially a saved SQL statement.
Therefore, I would say that in general, a stored procedure will be likely to be faster than a view IF the SQL statement for each is the same, and IF the SQL statement can benefit from optimizations. Otherwise, in general, they would be similar in performance.
Reference these links documentation supporting my answer.
http://www.sql-server-performance.com/tips/stored_procedures_p1.aspx
http://msdn.microsoft.com/en-us/library/ms998577.aspx
Also, if you're looking for all the ways to optimize performance on SQL Server, the second link above is a good place to start.
In short, based on my experience in some complex queries, Stored procedure gives better performance than function.
But you cannot use results of stored procedure in select or join queries.
If you don't want to use the result set in another query, better to use SP.
And rest of the details and differences are mentioned by people in this forum and elsewhere.
I prefer stored procedures due to Allow greater control over data, if you want to build a good, secure modular system then use stored procedures, it can run multiple sql-commands, has control-of-flow statements and accepts parameters. Everything you can do in a view you can do in a stored procedure. But in a stored procedure, you can do with much more flexibility.
I believe that another way of thinking would be to use stored procedures to select the views. This will make your architecture a loosely coupled system. If you decide to change the schema in the future, you won't have to worry 'so' much that it will break the front end.
I guess what I'm saying is instead of sp vs views, think sp and views :)
Stored procedures and views are different and have different purposes. I look at views as canned queries. I look at stored procedures as code modules.
For example let's say you have a table called tblEmployees with these two columns (among others): DateOfBirth and MaleFemale.
A view called viewEmployeesMale which filters out only male employees can be very useful. A view called viewEmployeesFemale is also very useful. Both of these views are self describing and very intuitive.
Now, lets say you need to produce a list all male employees between the ages of 25 and 30. I would tend to create a stored procedure to produce this result. While it most certainly could be built as a view, in my opinion a stored procedure is better suited for dealing with this. Date manipulation especially where nulls are a factor can become very tricky.
I know I'm not supposed to turn this into a "discussion", but I'm very interested in this and just thought I'd share my empirical observations of a specific situation, with particular reference to all the comments above which state that an equivalent SELECT statement executed from within a Stored Procedure and a View should have broadly the same performance.
I have a view in database "A" which joins 5 tables in a separate database (db "B"). If I attach to db "A" in SSMS and SELECT * from the view, it takes >3 minutes to return 250000 rows. If I take the select statement from the design page of the view and execute it directly in SSMS, it takes < 25 seconds. Putting the same select statement into a stored procedure gives the same performance when I execute that procedure.
Without making any observations on the absolute performance (db "B" is an AX database which we are not allowed to touch!), I am still absolutely convinced that in this case using an SP is an order of magnitude faster than using a View to retrieve the same data, and this applies to many other similar views in this particular case.
I don't think it's anything to do with creating a connection to the other db, unless by using a view it somehow can never cache the connection whereas the select does, because I can switch between the 2 selects in the same SSMS window repeatedly and the performance of each query remains consistent. Also, if I connect directly to db "B" and run the select without the dbname.dbo.... refs, it takes the same time.
Any thoughts anyone?
Views:
We can create index on views (not possible in stored proc)
it's easy to give abstract views(only limited column access of multiple table ) of
table data to other DBA/users
Store Procedure:
We can pass parameters to sp(not possible in views)
Execute multiple statement inside procedure (like insert, update,delete operations)
A couple other considerations: While performance between an SP and a view are essentially the same (given they are performing the exact same select), the SP gives you more flexibility for that same query.
The SP will support ordering the result set; i.e., including an ORDER BY statement. You cannot do so in a view.
The SP is fully compiled and requires only an exec to invoke it. The view still requires a SELECT * FROM view to invoke it; i.e., a select on the compiled select in the view.
Found a detailed performance analysis: https://www.scarydba.com/2016/11/01/stored-procedures-not-faster-views/
Compile Time Comparison:
There is a difference in the compile time between the view by itself and the stored procedures (they were almost identical). Let’s look at performance over a few thousand executions:
View AVG: 210.431431431431
Stored Proc w/ View AVG: 190.641641641642
Stored Proc AVG: 200.171171171171
This is measured in microsends, so the variation we’re seeing is likely just some disparity on I/O, CPU or something else since the differences are trivial at 10mc or 5%.
What about execution time including compile time, since there is a
difference:
Query duration View AVG: 10089.3226452906
Stored Proc AVG: 9314.38877755511
Stored Proc w/ View AVG: 9938.05410821643
Conclusion:
With the exception of the differences in compile time, we see that views actually perform exactly the same as stored procedures, if the query in question is the same.

Difference between a inline function and a view

I am a newbie in using functions and it appears to me that an inline function is very similar to a view. Am I correct?
Also, can I have UPDATE statements within a function?
After reading many of the answers here, I'd like to note that there is a big difference between an inline table-valued function and any other kind of function (scalar or multi-line TVF).
An inline TVF is simply a parameterized view. It can be expanded and optimized away just like a view. It is not required to materialize anything before "returning results" or anything like that (although, unfortunately, the syntax has a RETURN.
A big benefit I've found of an inline TVF over a view is that it does force required parameterization whereas with a view, you have to assume that the caller will appropriately join or restrict the usage of the view.
For example, we have many large fact tables in DW with a typical Kimball star model. I have a view on a fact table-centered model, which called without any restriction, will return hundreds of millions of rows. By using an inline TVF with appropriate parameterization, users are unable to accidentally ask for all the rows. Performance is largely indistinguishable between the two.
No difference. They are both expanded/unnested into the containing query.
Note: indexed views are considered differently but still may be expanded, and multi-valued table functions are black boxes to the containing query.
Tony Rogerson: VIEWS - they offer no optimisation benefits; they are simply inline macros - use sparingly
Adam Machanic: Scalar functions, inlining, and performance: An entertaining title for a boring post
Related SO question: Does query plan optimizer works well with joined/filtered table-valued functions?
Scary DBA (at the end)
Finally, writes to tables are not allowed in functions
Edit, after Eric Z Beard's comment and downvote...
The question and answers (not just mine) are not about scalar udfs. "Inline" means "inline table valued functions". Very different concepts...
Update: Looks like I missed the "inline" part. However, I'm leaving the answer here in case someone wants to read about difference between VIEWs and regular functions.
If you only have a function that does SELECT and output the data, then they are similar. However, even then, they are not the same because VIEWs can be optimized by the engine. For example, if you run SELECT * FROM view1 WHERE x = 10; and you have index on table field that maps to X, then it will be used. On the other hand, function builds a result set prior to searching, so you would have to move WHERE inside it - however, this is not easy because you might have many columns and you cannot ORDER BY all of those in the same select statement.
Therefore, if you compare views and functions for the same task of giving a "view" over data, then VIEWs are a better choice.
BUT, functions can do much more. You can do multiple queries without needing to join tables with JOINS or UNIONs. You can do some complex calculations with the results, run additional queries and output data to the user. Functions are more like stored procedures that are able to return datasets, then they are like views.
Nobody seems to have mentioned this aspect.
You can't have Update statements in an inline function but you can write Update statements against them just as though they were an updatable view.
One big difference is that a function can take parameters whereas a VIEW cannot.
I tend to favour VIEWs, being a Standard and therefore portable implementation. I use functions when the equivalent VIEW would be meaningless without a WHERE clause.
For example, I have a function that queries a relatively large valid-time state table ('history' table). If this was a VIEW and you tried to query it without a WHERE clause you'd get a whole lot of fairly data (eventually!) Using a function establishes a contract that if you want the data then you must supply a customer ID, a start date and an end date and the function is how I establish this contact. Why not a stored proc? Well, I expect a user to want to JOIN the resultset to further data (tables, VIEWs, functions, etc) and a function is IMO the best way of doing this rather then, say, requiring the user to write the resultset to a temporary table.
Answering your question about updates in a function (msdn):
The only changes that can be made by
the statements in the function are
changes to objects local to the
function, such as local cursors or
variables. Modifications to database
tables, operations on cursors that are
not local to the function, sending
e-mail, attempting a catalog
modification, and generating a result
set that is returned to the user are
examples of actions that cannot be
performed in a function.
A view is a "view" of data that is returned from a query, almost a pseudo-table. A function returns a value/table usually derived from querying the data. You can run any sql statement in a function provided the function eventually returns a value/table.
A function allows you to pass in parameters to create a more specific view. Lets say you wanted to have grab customers based on state. A function would allow you to pass in the state you are looking for and give you all the customers by that state. A view can't do that.
A function performs a task, or many tasks. A view retrieves data via a query. What ever fits in that query is what you are limited too. In a function I can update, select, create table variables, delete some data, send an email, interact with a CLR that I create, etc. Way more powerful than a lowly view!