What are SQL Views?
An SQL View is a virtual table whose content is based on the result-set of an SQL statement. It's like a saved query that you can treat as if it were a table. Views do not store data themselves; they dynamically retrieve data from the underlying base tables when queried.
Key Benefits:
- Simplification: Complex queries can be encapsulated into a view, making them easier to write and understand.
- Security: You can grant users access to a view without granting them access to the underlying tables, limiting what data they can see.
- Data Abstraction: Views can hide the complexity of table structures and provide a consistent interface even if the underlying tables change.
- Consistency: Ensure that data is presented uniformly across different parts of an application.
Creating a View
The basic syntax for creating a view is:
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Let's consider a sample scenario with two tables:
Scenario: Employee and Department Tables
Imagine we have an `employees` table and a `departments` table:
-- employees table
-- employee_id, first_name, last_name, department_id, salary
-- departments table
-- department_id, department_name
We want to create a view that shows employee names along with their department names.
Example: Creating an 'EmployeeDepartment' View
CREATE VIEW EmployeeDepartment AS
SELECT
e.employee_id,
e.first_name,
e.last_name,
d.department_name
FROM
employees e
JOIN
departments d ON e.department_id = d.department_id;
This statement creates a view named EmployeeDepartment
.
Querying a View
Once a view is created, you can query it just like you would query a regular table:
Example: Selecting from the View
SELECT * FROM EmployeeDepartment;
This will return all columns from the view.
SELECT first_name, last_name, department_name
FROM EmployeeDepartment
WHERE department_name = 'Sales';
This query filters the results to show only employees in the 'Sales' department.
Modifying and Dropping Views
Modifying a View
To modify an existing view, you can use the OR REPLACE
clause (supported by many but not all SQL dialects) or drop and recreate it.
-- Standard SQL (may vary)
CREATE OR REPLACE VIEW EmployeeDepartment AS
SELECT
e.employee_id,
e.first_name,
e.last_name,
d.department_name,
e.salary -- Added salary for demonstration
FROM
employees e
JOIN
departments d ON e.department_id = d.department_id;
Dropping a View
To remove a view, use the DROP VIEW
statement:
DROP VIEW view_name;
Example: Dropping the View
DROP VIEW EmployeeDepartment;