SQL Views

What is a View?

A view is a virtual table in a database that is based on the result set of a SQL query. It does not store data physically but provides a way to simplify complex queries and improve data security by restricting access to specific rows and columns of a table.

Advantages of Using Views

  • Data abstraction: Hides complexity from users.
  • Improved security: Restricts access to sensitive data.
  • Reusable queries: Simplifies complex queries for ease of use.
  • Consistent data presentation: Provides a consistent view of data.

Syntax of Creating a View

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

This syntax creates a view based on the specified SQL query.

Example of a View

Here’s an example of a view that shows the employees with their department names:

CREATE VIEW EmployeeDepartment AS
SELECT Employees.name, Departments.department_name
FROM Employees
JOIN Departments ON Employees.department_id = Departments.id;

This view combines data from the Employees and Departments tables to provide a list of employees along with their department names.

Managing Views

You can perform the following operations on views:

  • Updating a View: You can modify an existing view using the CREATE OR REPLACE VIEW command.
  • Dropping a View: You can remove a view from the database using the DROP VIEW command.

Practice Exercise

Create a view for a sample table that simplifies a complex query or combines data from multiple tables.