Is it okay to have a lot of database views? Is it okay to have a lot of database views? sql sql

Is it okay to have a lot of database views?

For the most part, it doesn't matter. Yes, SQL Server will have more choices when it parses SELECT * FROM table (it'll have to look in the system catalogs for 'table') but it's highly optimized for that, and provided you have sufficient RAM (most servers nowadays do), you won't notice a difference between 0 and 1,000 views.

However, from a people-perspective, trying to manage and figure out what "hundreds" of views are doing is probably impossible, so you likely have a lot of duplicated code in there. What happens if some business rules change that are embedded in these redundant views?

The main point of views is to encapsulate business logic into a pseudo table (so you may have a person table, but then a view called "active_persons" which does some magic). Creating a view for each report is kind of silly unless each report is so isolated and unique that there is no ability to re-use.

A view is a query that you run often with preset parameters. If you know you will be looking at the same data all the time you can create a view for ease of use and for data binding.

That being said, when you select from a view the view defining query is run along with the query you are running.

For example, if vwCustomersWhoHavePaid is:

Select * from customers where paid = 1

and the query you are running returns the customers who have paid after August first is formatted like this:

Select * from vwCustomersWhoHavePaid where datepaid > '08/01/08'

The query you are actually running is:

Select * from (Select * from customers where paid = 1) where datepaid > '08/01/08'

This is something you should keep in mind when creating views, they are a way of storing data that you look at often. It's just a way of organizing data so it's easier to access.

The views are only going to take up cpu/memory resources when they are called.

Anyhow, best practice would be to consolidate what can be consolidated, remove what can be removed, and if it's literally only used by your reports, choose a consistent naming standard for the views so they can easily be grouped together when looking for a particular view.

Also, unless you really need transactional isolation, consider using the NOLOCK table hint in your queries.

-- Kevin Fairchild