BIT202 ยท 2082 ยท 5 marks
What is the view? How can you create a view in SQL? Illustrate with an example.
What is the view? How can you create a view in SQL? Illustrate with an example. [5]
Quick answer
A view is a virtual table that is derived from one or more base tables (or other views) using a SQL query. It does not physically store data itself; instead, it stores the query definition, and the data is retrieved dynamically whenever the view is accessed.
Views in SQL
What is a View?
Key characteristics of a view:
- It behaves like a table (can be queried using SELECT)
- It simplifies complex queries
- It provides data security by restricting access to specific rows/columns
- It provides logical data independence
Creating a View in SQL
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example
Consider a base table:
Employee table:
| EmpID | EmpName | Department | Salary |
|---|---|---|---|
| 101 | Alice | IT | 60000 |
| 102 | Bob | HR | 45000 |
| 103 | Carol | IT | 70000 |
| 104 | David | Finance | 50000 |
Step 1: Create a View
Suppose we want to create a view that shows only IT department employees without exposing their salary:
CREATE VIEW IT_Employees AS
SELECT EmpID, EmpName, Department
FROM Employee
WHERE Department = 'IT';
Step 2: Query the View
SELECT * FROM IT_Employees;
Output:
| EmpID | EmpName | Department |
|---|---|---|
| 101 | Alice | IT |
| 103 | Carol | IT |
Dropping a View
DROP VIEW IT_Employees;
Summary
| Feature | Description |
|---|---|
| Virtual Table | Does not store data physically |
| Based on Query | Defined using SELECT statement |
| Security | Hides sensitive columns (e.g., Salary) |
| Simplicity | Simplifies repeated complex queries |
A view thus acts as a saved query that can be treated as a table, providing security, simplicity, and abstraction over the underlying data.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.