Do database views affect query performance?

28,578

Solution 1

I have always considered Views to be like a read-only Stored Procedures. You give the database as much information as you can in advance so it can pre-compile as best it can.

You can index views as well allowing you access to an optimised view of the data you are after for the type of query you are running.

Solution 2

Although a certain query running inside a view and the same query running outside of the view should perform equivalently, things get much more complicated quickly when you need to join two views together. You can easily end up bringing tables that you don't need into the query, or bringing tables in redundantly. The database's optimizer may have more trouble creating a good query execution plan. So while views can be very good in terms of allowing more fine grained security and the like, they are not necessarily good for modularity.

Solution 3

It depends on the RDBMS, but usually there isn't optimization going on, and it's just a convenient way to simplify queries. Some database systems use "materialized views" however, which do use a caching mechanism.

Solution 4

Usually a view is just a way to create a common shorthand for defining result sets that you need frequently.

However, there is a downside. The temptation is to add in every column you think you might need somewhere sometime when you might like to use the view. So YAGNI is violated. Not only columns, but sometimes additional outer joins get tacked on "just in case". So covering indexes might not cover any more, and the query plan may increase in complexity (and drop in efficiency).

YAGNI is a critical concept in SQL design.

Solution 5

Generally speaking, views should perform equivalently to a query written directly on the underlying tables.

But: there may be edge cases, and it would behoove you to test your code. All modern RDBMS systems have tools that will let you see the queryplans, and monitor execution. Don't take my (or anybody else's) word for it, when you can have the definitive data at your fingertips.

Share:
28,578
Morten Christiansen
Author by

Morten Christiansen

I'm a software developer at UVdata in Denmark. I work on all sorts of interesting .NET technologies at work and in my spare time with a focus on the web. I have a passion for the craft/art of software development and love to explore the intricacies of good software design and code practices.

Updated on July 09, 2022

Comments

  • Morten Christiansen
    Morten Christiansen almost 2 years

    Are database views only a means to simplify the access of data or does it provide performance benefits when accessing the views as opposed to just running the query which the view is based on? I suspect views are functionally equivalent to just the adding the stored view query to each query on the view data, is this correct or are there other details and/or optimizations happening?