SQL

SQL - Views

A SQL view is a virtual table that is based on the result set of a SELECT query. Views provide a way to simplify complex queries, encapsulate logic, and enhance security by restricting access to specific data. Here’s a detailed tutorial on how to create, use, and manage views in SQL.

Basic Syntax

CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

Examples

1. Creating a Simple View

Assume you have a table named employees with columns first_name, last_name, department, and salary.

Create a view that shows only employees from the Engineering department:


CREATE VIEW engineering_employees AS
SELECT first_name, last_name, salary
FROM employees
WHERE department = 'Engineering';

2. Creating a View with Aggregation

Create a view that shows the total salary expense for each department:


CREATE VIEW department_salaries AS
SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department;

3. Using Views

Once a view is created, you can query it just like a regular table:


SELECT * FROM engineering_employees;


SELECT * FROM department_salaries;