Creating Views (Virtual Tables)

tags: #sql

What is a view?

A view in SQL is a virtual table based on the result of a SELECT statement that is not necessarily populated i.e., it is NOT a physical table and does not store any data on its own and does not really exist or physically saved.

Views are created on a schema-level.

Why do we use views?

Views can also be used to restrict access to sensitive data in a database

Simplify Data

Customized View of Data

Enforce Some Real-world Rules

General Syntax

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

-- to view output of a view
SELECT * FROM view_name;

Example 1: Views of customer orders

CREATE VIEW customer_orders AS
SELECT c.customer_name, o.order_date, o.total_amount
FROM customers AS c
JOIN orders o ON c.customer_id = o.customer_id;

Example 2: Querying salary bonus of employees

CREATE VIEW employee_bonus AS
SELECT employee_name, salary, salary * 0.1 AS bonus
FROM employees;

Dropping Views

To remove VIEWS from the schema:

DROP VIEW [IF EXISTS] view_name;
Powered by Forestry.md