In Oracle, a View is a virtual table created from the result of a SQL query. It does not store data itself; instead, it stores the SQL statement. Whenever you query the view, Oracle retrieves the latest data from the underlying base table(s).
Syntax
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example
Suppose you have an EMPLOYEES table:
| EMP_ID | NAME | SALARY | DEPT |
|---|---|---|---|
| 101 | Alice | 50000 | HR |
| 102 | Bob | 60000 | IT |
Create a view that shows only IT employees:
CREATE VIEW it_employees AS
SELECT emp_id, name, salary
FROM employees
WHERE dept = 'IT';
Query the view:
SELECT * FROM it_employees;
Output:
| EMP_ID | NAME | SALARY |
|---|---|---|
| 102 | Bob | 60000 |
Advantages of Views
- Simplifies complex SQL queries.
- Restricts access to selected rows or columns for security.
- Hides the complexity of joins and calculations.
- Always displays the latest data from the base tables.
Other useful commands
Display a view:
SELECT * FROM view_name;
Replace an existing view:
CREATE OR REPLACE VIEW view_name AS
SELECT ...
FROM ...;
Delete a view:
DROP VIEW view_name;