A view in SQL is a virtual table that is based on the result of a query.
It does not store data itself, but rather displays data stored in one or more tables.
You can think of a view as a saved query that you can treat like a table.
🔹 Why use Views?
- To simplify complex queries.
- To provide security by restricting access to specific columns or rows.
- To present data in a specific format without changing the underlying tables.
✅ Example
Suppose we have a table called Employees:
EmpID | Name | Department | Salary | City |
---|---|---|---|---|
1 | Alice | HR | 4000 | New York |
2 | Bob | IT | 6000 | Chicago |
3 | Carol | IT | 7000 | Dallas |
4 | David | Finance | 5000 | New York |
1. Creating a View
CREATE VIEW IT_Employees AS
SELECT EmpID, Name, Salary
FROM Employees
WHERE Department = 'IT';
2. Using the View
SELECT * FROM IT_Employees;
Result:
EmpID | Name | Salary |
---|---|---|
2 | Bob | 6000 |
3 | Carol | 7000 |
3. Updating Data Through a View
If the view is updatable (depends on DBMS and query), you can modify the underlying table:
UPDATE IT_Employees
SET Salary = 7500
WHERE EmpID = 2;
This will update Bob’s salary in the original Employees
table.