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.)
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.
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:
You could abstract that to a view:
and in the app code, simply have:
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 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.
Anytime you need [my_interface] != [user_interface].
Example:
TABLE A:
VIEW for TABLE A:
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.
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.
1) What is a view useful for?
2) Are there any situations in which it is tempting to use a view when you shouldn't use one?
3) Why would you use a view in lieu of something like a table-valued function or vice versa?
4) Are there any circumstances that a view might be useful that aren't apparent at first glance?