Is writing a query using Views a good strategy? - sql-server-2005

I just want to know whether it is correct to write a query by first creating it in a view.
Any suggestions?

A view is a macro and is expanded.
Views on top of views simply mean more work for the optimiser to unravel the complexity underneath.

Querying a view is generally ok, as sql sever optimiser is not easily fooled. But don't use scalar functions in your view or you'll get performance problems.

It depends on what you're doing in the views, and what you plan to do with them.
Creating views, and then layering them on top of one another (by referencing a view inside another view) generally isn't a good idea for instance. Using an ORDER BY in a view also is a general no-no, because if you join the view - the order by is getting executed but there's no need for it.

At the end of the day a view is just a sub query so its really no big deal.
SELECT *
FROM (
SELECT *
FROM myTable
WHERE a = 2
) a
is no different then
SELECT *
FROM myView
The plan gets cached so you don't really suffer any performance impacts and you get the flexibility of reusing your code else were.

I know that there is a school of thought that says that you ought to have a view-per-table and develop your code against your views instead of your tables. In this scenario, you can use evolutionary development methods and, as your modify your tables, develop new views for your new code without breaking the views that the old code relies on. I've never actually had a project that I thought would be complicated enough that I couldn't just update the code as the tables changed so I have never used this method.
As for writing queries into views there is one scenario under which I do this. They may be specific to my use of LINQ, however, so take this with a grain of salt. If I have a query that needs some complicated processing and returns a composite object based on more than one table, I will usually write a stored procedure or table-valued function to do the query. I've found it easiest to work with the LINQ designer if I also create a view that I can drag onto the design surface to create the class for the objects that the sp/function returns rather than having it auto-generate a class. It gives me more control over naming the class later if I choose.

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

What are the disadvantage of SQL views?

Recently I faced an interview and I was asked the above question.
I was dumb when I think about it.
Interviewer said:
All people are saying views have lots
of advantages but I find no
disadvantages, why so?
when table is not there view will not work.
dml is not possible if that is more than one table.
it is also database object so it will occupy the space.
When table is dropped view becomes inactive.. it depends on the table objects.
Querying from view takes more time than directly querying from the table
Most of the things I would say have already been covered, I would add this though.
Views are useful in many situations but making too much use of them can be a mistake because they tie your hands in terms of query structure. Often when your overall query contains several views within it (especially when views are layered), or when a view has been adapted for a slightly different purpose to what was originally intended, you find that there is a far better way of writing the query if you just expand the views and change the logic.
Like any tool, views can be misused particularly when you're not sure how they should be used properly.
Chris Mullins defines three basic view implementation rules:
The View Usage Rule
The Proliferation Avoidance Rule
The View Synchronization Rule
If you don't get these things right you get code maintenance problems, performance problems, security problems, etc.
The only disadvantage I can think of is that you may force the user to join several views to get the data in a way that is useful to them, as you now have largely static queries.
So, if the view was created one time and it is expected to never change, you may end up with a preponderance of views that creates a maze for the user to navigate through, so there should be some process to update views, to keep them useful as needs change.
1) when a table is dropped ,view will be affected.
2) If column name is renamed then view will show exception "Invalid column name" .
3)When view is created for large table ,it occupies some memory .
If you write some complex views, while querying simple data from view it will take more time.
It affects performance. Querying from view takes more time than directly querying from the table.
If view would join more than one table, you may not perform any DML
operations.
Table dependence- if you change table, you need to
updated view also.
A view permits the DBA (database administrator) to tightly control what goes in and comes out of a database.
In banking a view is often used to permanently keep track of every change made to the table. The real table typically contains additional columns that are not seen by "the view" such as:
last-modified (when the last change was made)
last-action (update/delete/add)
last-actioner (person who updated the row)
So when displaying the view of the table only the latest update or add of any row is displayed. However the table still contains every existing change and row deletion.
The major downside to a view is to the user of the table (the application programmer) who cannot directly change the underlying table (for performance reasons, for example). Additionally it does create more work for the database administrator. You might also consider the extra CPU burden placed upon the server - particularly if it is utilised by many clients.

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 !

What are views good for?

I'm just trying to get a general idea of what views are used for in RDBMSes. That is to say, I know what a view is and how to make one. I also know what I've used them for in the past.
But I want to make sure I have a thorough understanding of what a view is useful for and what a view shouldn't be useful for. More specifically:
What is a view useful for?
Are there any situations in which it is tempting to use a view when you shouldn't use one?
Why would you use a view in lieu of something like a table-valued function or vice versa?
Are there any circumstances that a view might be useful that aren't apparent at first glance?
(And for the record, some of these questions are intentionally naive. This is partly a concept check.)
In a way, a view is like an interface. You can change the underlying table structure all you want, but the view gives a way for the code to not have to change.
Views are a nice way of providing something simple to report writers. If your business users want to access the data from something like Crystal Reports, you can give them some views in their account that simplify the data -- maybe even denormalize it for them.
1) What is a view useful for?
IOPO In One Place Only•Whether you consider the data itself or the queries that reference the joined tables, utilizing a view avoids unnecessary redundancy. •Views also provide an abstracting layer preventing direct access to the tables (and the resulting handcuffing referencing physical dependencies). In fact, I think it's good practice1 to offer only abstracted access to your underlying data (using views & table-valued functions), including views such as CREATE VIEW AS SELECT * FROM tblData1I hafta admit there's a good deal of "Do as I say; not as I do" in that advice ;)
2) Are there any situations in which it is tempting to use a view when you shouldn't use one?
Performance in view joins used to be a concern (e.g. SQL 2000). I'm no expert, but I haven't worried about it in a while. (Nor can I think of where I'm presently using view joins.)Another situation where a view might be overkill is when the view is only referenced from one calling location and a derived table could be used instead. Just like an anonymous type is preferable to a class in .NET if the anonymous type is only used/referenced once. • See the derived table description in http://msdn.microsoft.com/en-us/library/ms177634.aspx
3) Why would you use a view in lieu of something like a table-valued function or vice versa?
(Aside from performance reasons) A table-valued function is functionally equivalent to a parameterized view. In fact, a common simple table-valued function use case is simply to add a WHERE clause filter to an already existing view in a single object.
4) Are there any circumstances that a view might be useful that aren't apparent at first glance?
I can't think of any non-apparent uses of the top of my head. (I suppose if I could, that would make them apparent ;)
Views can be used to provide security (ie: users can have access to views that only access certain columns in a table), views can provide additional security for updates, inserts, etc. Views also provide a way to alias column names (as do sp's) but views are more of an isolation from the actual table.
In a sense views denormalize. Denormalization is sometimes necessary to provide data in a more meaningful manner. This is what a lot of applications do anyway by way of domain modeling in their objects. They help present the data in a way that more closely matches a business' perspective.
In addition to what the others have stated, views can also be useful for removing more complecated SQL queries from the application.
As an example, instead of in an application doing:
sql = "select a, b from table1 union
select a, b from table2";
You could abstract that to a view:
create view union_table1_table2_v as
select a,b from table1
union
select a,b from table2
and in the app code, simply have:
sql = "select a, b from union_table1_table2_v";
Also if the data structures ever change, you won't have to change the app code, recompile, and redeploy. you would just change the view in the db.
Views hide the database complexity. They are great for a lot of reasons and are useful in a lot of situations, but if you have users that are allowed to write their own queries and reports, you can use them as a safeguard to make sure they don't submit badly designed queries with nasty cartesian joins that take down your database server.
The OP asked if there were situations where it might be tempting to use a view, but it's not appropriate.
What you don't want to use a view for is a substitute for complex joins. That is, don't let your procedural programming habit of breaking a problem down into smaller pieces lead you toward using several views joined together instead of one larger join. Doing so will kill the database engine's efficiency since it's essentially doing several separate queries rather than one larger one.
For example, let's say you have to join tables A, B, C, and D together. You may be tempted to make a view out of tables A & B and a view out of C & D, then join the two views together. It's much better to just join A, B, C, and D in one query.
Views can centralize or consolidate data. Where I'm at we have a number of different databases on a couple different linked servers. Each database holds data for a different application. A couple of those databases hold information that are relavent to a number of different applications. What we'll do in those circumstances is create a view in that application's database that just pulls data from the database where the data is really stored, so that the queries we write don't look like they're going across different databases.
The responses so far are correct -- views are good for providing security, denormalization (although there is much pain down that road if done wrong), data model abstraction, etc.
In addition, views are commonly used to implement business logic (a lapsed user is a user who has not logged in in the last 40 days, that sort of thing).
Views save a lot of repeated complex JOIN statements in your SQL scripts. You can just encapsulate some complex JOIN in some view and call it in your SELECT statement whenever needed. This would sometimes be handy, straight forward and easier than writing out the join statements in every query.
A view is simply a stored, named SELECT statement. Think of views like library functions.
I wanted to highlight the use of views for reporting. Often, there is a conflict between normalizing the database tables to speed up performance, especially for editing and inserting data (OLTP uses), and denormalizing to reduce the number of table joins for queries for reporting and analysis (OLAP uses). Of necessity, OLTP usually wins, because data entry must have optimal performance. Creating views, then, for optimal reporting performance, can help to satisfy both classes of users (data entry and report viewers).
I remember a very long SELECT which involved several UNIONs. Each UNION included a join to a price table which was created on the fly by a SELECT that was itself fairly long and hard to understand. I think it would have been a good idea to have a view that to create the price table. It would have shortened the overall SELECT by about half.
I don't know if the DB would evaluate the view once, or once each time in was invoked. Anyone know? If the former, using a view would improved performance.
Anytime you need [my_interface] != [user_interface].
Example:
TABLE A:
id
info
VIEW for TABLE A:
Customer Information
this is a way you might hide the id from the customer and rename the info to a more verbose name both at once.
The view will use underlying index for primary key id, so you won't see a performance loss, just better abstraction of the select query.