SQL views. do i need to use it to increase performance? - sql

i mostly need to know
- views and their purpose ?
- do they increase performance of an application ?
- in what kind of cicumstance will I need to use views?

As this is homework you should probably be doing research.
A quick Google yields plenty of links, one of which is http://www.techotopia.com/index.php/An_Introduction_to_MySQL_Views.
MySQL views are essentially a way to
package up SELECT statements into
re-usable virtual tables whereby the
data can be retrieved simply by
referencing the view, rather than
having to repeat the associated SELECT
statement.
The official site documentation is quite informative and readable too.
See: the MySQL FAQ page on Views and the Using Views documentation.

Views provide an abstraction layer over your tables.
They can be used to prevent access to certain sensitive columns (such as salary).
They are often used to encapsulate logic for reporting.

in what kind of cicumstance will I
need to use views?
If you're repeatedly using the same SELECT statement that uses lots of JOINs and/or function calls, a view makes it simpler to use.

Related

Updating Views vs. Triggers

I am studying for a final exam, and came across this question:
Explain why updating views is not recommended. Explain how triggers can be used to support view updates.
I have looked on the web, and read a couple chapters from the book to no avail.
I have seen points made to where views can help make life easier, but none arguing against them.
Is this a possible answer?
One could use the INSTEAD OF clause in a TRIGGER statement in order to circumvent the updating of a table. This would allow for the update of multiple tables that could be represented by one view.
So, my questions are:
1.) Why are updating views not recommended?
2.) How can triggers be used as a solution to the problem?
There are many restrictions on inherently updatable views.
This can be both frustrating and fragile, as future evolution of your view and/or schema might made the view no longer inherently updatable -- so breaking code that relies on this feature.
At the expense of few lines of code, using an INSTEAD OF trigger will have the benefit of both reducing the above concern and to allow you to update a non-inherently updatable views. You can use an INSTEAD OF trigger on an inherently updatable view to override the default behavior.
When researching views, be sure to rely on relatively recent data as views have changed over the years so older opinions on the subject may not be valid. When views were first made updateable, the restrictions were many and control of the operation was little or nonexistent.
With the ability to write triggers on views in many systems, the restrictions have fallen away and control is precise. We can now determine exactly what happens to all the data during DML to views. It is now to the point where I disallow direct access to tables by applications. All DML originating from apps have to go thru views (or stored procedures, but they are not as good as view triggers). The benefits are so vast I don't see why it hasn't become a universal standard.
Indeed, many people's "views" on views (unfortunately, many people who are in charge of databases) seem to be stuck in the 1990's. Some don't want any views at all in their database. Some allow views but don't allow using them for DML. Many insist on giving them special names ("VW_name", "name_View" or similar) which breaks an extremely useful wall of abstraction for your data. Data abstraction is not a strong point of databases, so grab it where you can.

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

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.