In SQL, views provide a powerful way to encapsulate complex queries, simplify data access, and enhance security. A view is a virtual table based on the result set of a SQL query. It does not store data itself but acts as a lens to query the underlying data.
A view is a saved SQL query that represents a virtual table. It contains no data of its own but retrieves data from one or more tables when queried. Think of it as a window to your data.
Instead of writing long and complex queries repeatedly, you can encapsulate the logic in a view.
Restrict access to specific rows or columns without exposing the full table.
Easily present summarized data, such as totals or averages.
To create a view, use the CREATE VIEW
statement.
CREATE VIEW view_name AS
SELECT columns
FROM table_name
WHERE condition;
Create a view to show employees in the “Sales” department.
CREATE VIEW SalesEmployees AS
SELECT EmployeeID, EmployeeName, Department
FROM Employees
WHERE Department = 'Sales';
SalesEmployees
view retrieves only employees from the “Sales” department.
SELECT * FROM SalesEmployees;
EmployeeID | EmployeeName | Department |
---|---|---|
1 | John Smith | Sales |
2 | Jane Doe | Sales |
You can query a view just like a table.
Retrieve employees with IDs greater than 1 from the SalesEmployees
view.
SELECT * FROM SalesEmployees WHERE EmployeeID > 1;
EmployeeID | EmployeeName | Department |
---|---|---|
2 | Jane Doe | Sales |
If the view is updatable, you can use it to update the underlying tables.
Update the department of an employee using the view.
UPDATE SalesEmployees
SET Department = 'Marketing'
WHERE EmployeeID = 2;
Employees
table reflects the updated department for EmployeeID 2.To remove a view, use the DROP VIEW
statement.
DROP VIEW SalesEmployees;
SalesEmployees
view is deletedAn indexed view stores the view’s result set physically to improve performance.
CREATE UNIQUE CLUSTERED INDEX idx_SalesView ON SalesEmployees(EmployeeID);
Views that refer to themselves.
Example: Create a view to retrieve hierarchical data (e.g., reporting managers).
CREATE VIEW ManagerHierarchy AS
SELECT EmployeeID, ManagerID
FROM Employees
WHERE ManagerID IS NOT NULL;
Use views to restrict access to sensitive columns.
CREATE VIEW EmployeeNames AS
SELECT EmployeeName
FROM Employees;
Views are an essential feature of SQL, offering a virtual representation of data that simplifies queries, enhances security, and promotes maintainability. Happy Coding!❤️