![]() |
VOOZH | about |
The SQL CREATE VIEW statement creates a virtual table based on a SELECT query. It does not store data itself but displays data from one or more tables when accessed.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
The CREATE VIEW statement in SQL is used to create a virtual table based on the result of a query. Views help simplify complex queries and enhance security by restricting access to specific columns or rows.
Consider the table products having three columns product_id, product_name and price. Suppose we have to create a view that contains only products whose prices are greater than $100.
👁 productQuery:
CREATE VIEW expensive_products AS
SELECT product_id, product_name, price
FROM products
WHERE price > 100;
Output:
Assume that we have two tables employees and departments. We need to build a view combining information about both tables in order to show each employee’s name along with their department name:
Query:
CREATE VIEW employee_department_info 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;
Employees table:
Departments table:
Query:
CREATE VIEW employee_department_info 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;
Output:
Explanation:
Now, when we query the employee_department_info view, we get a list of employees along with their department names.