A view is a virtual table produced from executing a stored query on the database. Views don’t store any data as they retrieve the result set through a query. Users can interact with views similarly as they would with a normal table when retrieving data however limitations do exist when writing back to the result-set. Views can be used to simplify access to database result sets and provide more security options to administrators when granting access. More information can be found at CREATE VIEW (Transact-SQL)
1. Simplicity
2. Security
3. Flexibility
1. Performance
2. Dependencies
3. Update Restrictions
In some cases, you can update the tables through a SQL view depending on its complexity. You can only update views with a single base table otherwise it may choose the incorrect base table to update
INSERT INTO vwProductsNorthwind VALUES (@ItemName, @ItemCost);UPDATE vwProductsNorthwind SET Cost = @ItemCost WHERE Id = @ItemId;DELETE vwProductsNorthwind WHERE Id = @ItemId;
Figure: Example of an updatable view using a single base table
More complex views, such as a multi-table view can be used after the where clause in another update statement.
-- Create the products by category viewCREATE VIEW vwProductsByCategoryASSELECT p.Id, p.Name, p.Cost, p.OnSale, p.CategoryIdFROM Products pJOIN Categories cON p.CategoryId = c.Id-- Set all products from a particular category to be on saleUPDATE ProductsSET OnSale = @OnSaleWHERE Id IN ( SELECT Id FROM vwProductsByCategory WHERE CategoryName = @CategoryName )
Figure: Using a multi-table view after the when clause
So your business has an employees table as shown below that has detailed information about their name, birthdate, home phone, address and photo. This information is suitable for the payroll department but what you want to display employees names and photos on the website for public viewing. Or what If you want contact information such as extension number and country to be available on the company intranet?
Figure: Northwind traders employees table
You could create separate tables for each department, only supplying the required fields for each. This would also need an additional system to sync between the tables to ensure the information was kept up to date.
❌ Figure: Bad example – Using tables and duplicating data
CREATE VIEW vwIntranetEmployees ASSELECT EmployeeID, LastName, FirstName, Title, TitleOfCourtesy, Country, Extension, Photo, PhotoPathFROM Employees;CREATE VIEW vwWebsiteProfiles ASSELECT EmployeeID, LastName, FirstName, Title, TitleOfCourtesy, Photo, PhotoPathFROM Employees;
✅ Figure: Good example – Using views from the base table containing the source data
Creating views of the employee table allows you to update the data in one source location such as payroll and all other departments will see the changes. It prevents the problem of stale data and allows more control over access to the data.