144

I am reading through the SQL Server 2008 bible and I am covering the views section. But the author really doesn't explain the purpose of views. What is a good use for views? Should I use them in my website and what are the benefits of them?

2
  • Could you please provide me the database files of that book "SQL Server 2008 Bible"? The author's website is dead and I can't reach him.
    – user9807720
    Nov 9, 2018 at 22:34
  • Does this answer your question? Why do you create a View in a database?
    – Ivar
    Nov 25, 2020 at 9:58

10 Answers 10

124

Another use that none of the previous answers seem to have mentioned is easier deployment of table structure changes.

Say, you wish to retire a table (T_OLD) containing data for active users, and instead use a new table with similar data (named T_NEW) but one that has data for both active and inactive users, with one extra column active.

If your system(s) have gazillion queries that do SELECT whatever FROM T_OLD WHERE whatever, you have two choices for the roll-out:

1) Cold Turkey - Change the DB, and at the same time, change, test and release numerous pieces of code which contained said query. VERY hard to do (or even coordinate), very risky. Bad.

2) Gradual - change the DB by creating the T_NEW table, dropping the T_OLD table and instead creating a VIEW called T_OLD that mimics the T_OLD table 100% (e.g the view query is SELECT all_fields_except_active FROM T_NEW WHERE active=1).

That would allow you to avoid releasing ANY code that currently selects from T_OLD, and do the changes to migrate code from T_OLD to T_NEW at leisure.

This is a simple example, there are others a lot more involved.

P.S. On the other hand, you probably should have had a stored procedure API instead of direct queries from T_OLD, but that's not always the case.

5
  • 3
    I was ignorant of the term "stored procedure API" and associated pros/cons and found this article helpful: codinghorror.com/blog/2005/05/… Dec 13, 2013 at 1:31
  • Sorry I'm late to the party, but what about performance. If I needed joins on the original table and I'll join the View instead, will it use the best execution plan?
    – Zikato
    Jun 22, 2018 at 10:57
  • @Zikato yes, if it is an indexed view
    – LinkBerest
    Feb 11, 2019 at 15:36
  • V Good Indication Oct 11, 2019 at 7:00
  • Is there a way to efficiently "select all_fields_except_active" without referencing all of the other columns? Jun 9, 2021 at 13:14
68

(Copied from the first tutorial that came up in a Google search (link now dead), but it has all of the benefits I would have typed manually myself.)

Views have the following benefits:

  • Security - Views can be made accessible to users while the underlying tables are not directly accessible. This allows the DBA to give users only the data they need, while protecting other data in the same table.
  • Simplicity - Views can be used to hide and reuse complex queries.
  • Column Name Simplication or Clarification - Views can be used to provide aliases on column names to make them more memorable and/or meaningful.
  • Stepping Stone - Views can provide a stepping stone in a "multi-level" query. For example, you could create a view of a query that counted the number of sales each salesperson had made. You could then query that view to group the sales people by the number of sales they had made.
5
  • 1
    Because I like your answer and don't see a lot of point adding another, can I suggest two additions to your list? Indexed Views can give performance boosts. Running updates against views rather than direct to tables can give higher confidence you won't incorrectly update that key production table :)
    – David Hall
    Apr 21, 2010 at 4:11
  • One more point in your list, most DBA's would like the use of view because they can tune one view and mostly(not always) all the queries using that view will be tunned. Apr 21, 2010 at 5:58
  • This is the 99% answer in my book. Oct 17, 2013 at 13:34
  • BTW @David broken link Oct 18, 2019 at 18:13
  • The last point, can't we use a temp table for that? Jun 15, 2020 at 15:16
24

Some reasons from Wikipedia:

Views can provide advantages over tables:

  1. Views can represent a subset of the data contained in a table
  2. Views can join and simplify multiple tables into a single virtual table
  3. Views can act as aggregated tables, where the database engine aggregates data (sum, average etc) and presents the calculated results as part of the data
  4. Views can hide the complexity of data; for example a view could appear as Sales2000 or Sales2001, transparently partitioning the actual underlying table
  5. Views take very little space to store; the database contains only the definition of a view, not a copy of all the data it presents
  6. Depending on the SQL engine used, views can provide extra security
  7. Views can limit the degree of exposure of a table or tables to the outer world
16

VIEWS can be used as reusable sections of SELECT/CODE, that can be included in other selects/queries to be joined on, and use various different filters, without having to recreate the entire SELECT every time.

This also places logic in a single location, so that you do not have to change it all over the code base.

Have a look at

Choice Between Stored Procedures, Functions, Views, Triggers, Inline SQL

The main beauty of a view is that it can be used like a table in most situations, but unlike a table, it can encapsulate very complex calculations and commonly used joins. It can also use pretty much any object in the db except for stored procedures. Views are most useful when you always need to join the same set of tables say an Order with an Order Detail to get summary calculation fields etc.

2
  • 7
    Be very careful about doing this. If you use views that call other views, you can create a huge performance mess.
    – HLGEM
    Sep 10, 2011 at 16:10
  • 1
    you can do so by creating a method & putting the SQL query inside method. This method can be reused every time. Then why view ???
    – ASharma7
    Sep 8, 2020 at 6:49
11

A view is an abstraction layer, and it does what any good abstraction layer does, including encapsulating the database schema and protecting you from the consequences of changing internal implementation details.

It's an interface.

2
  • 1
    As long as you don't stack views on views for further abstraction.
    – HLGEM
    Sep 10, 2011 at 16:10
  • I think I've effectively repudiated any kind of multilevel abstraction in relational databases. And I don't call stored procedures from stored procedures, either. :)
    – dkretz
    Sep 10, 2011 at 19:35
4

Here are some of many reasons of using view rather than table directly

  • Simplicity - Views can be used to hide complex queries.
  • Security - View can hide some important information from end user by creating view on some selected columns
  • Security - Secure table to change the structure of it by using VIEW.
  • Redundancy - Reduce redundant code in every procedures/query by using a common view.
  • Calculation - All the calculations can be done once in view query.
  • Meaningful Name - Table may have name for id like tbl_org_emp_id which can alias like [Employee No] or some meaningful name.

From imexploring.com

3

Here is one very common use of using views to constrain an entity by some criteria.

Table: USERS contains all users

View: ACTIVE_USERS contains all users excluding those who are suspended, banned, waiting to be activated and not meeting any criteria you may choose to define in the future as part of the active requirements. This makes it unnecessary to delete any rows from your USERS table should you choose not to because ACTIVE_USERS can always hide the unwanted rows.

This way, you can use the table in your user management pages but the rest of the application can use ACTIVE_USERS as they may be the only users that should be able to execute processes and access/modify data.

1
  • Even if it seems to be "common" as you have stated, where's the benefit of your view example over using SELECT ... FROM Users WHERE IsActive = false? Feb 12, 2021 at 10:14
2

Views can allow you to combine data from several different tables and format it (combine fields, give more meaningful field names, etc.) so that it's easier for end users. They are an abstraction of the database model. They can also be used to give users access to the data in the table without giving them direct access to the table itself.

1

A small list of common reasons/uses:

  • use them to change the format or 'look' of data (i.e. you might join a first and last name together)

    perform calculations or other lookups on data

    denormalize data (extract data from several tables in to one spot)

-4

The Views are evil! Avoid them if possible and use only for the reason mentioned by DVK - temporary data migration.

You should understand that in a database with a 100 tables it is hard to remember the purpose of every table. Now, if you add here another 300 views it will become a complete mess. Than the 'View lovers' tend to use nested views and then use the nested views in stored procedures. I personnaly work now with a database where there are Views nested in depth 4 times! So to understand a simpliest logic of a stored procedure I have to go through all the views first.

3
  • 8
    -1 Views are good. They can become evil if you use them inappropriately - but that's true about just anything. Sep 7, 2011 at 2:57
  • 1
    Views can be evil if used badly. People who use them badly the most frequently seem to be those who are using them to abstract things and then do as you say, call views that call views that call views to the point where you may need to materialize 10 million recrods before returning a result set of 3. Views directly calling tables can be very useful.
    – HLGEM
    Sep 10, 2011 at 16:14
  • @HGLEM is there a way to restrict view calls from other views? Jun 8, 2016 at 22:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.