A view in MySQL is a virtual table created from a SELECT query that provides a way to look at data in one or more underlying tables. A view does not store data itself but dynamically generates data from the base tables whenever the view is queried. Views help in simplifying complex queries, enhancing security, and ensuring data abstraction.
CREATE VIEW view_name AS
SELECT columns
FROM table_name
WHERE condition;
Creating a view that shows the first name, last name, and department of employees:
CREATE VIEW employee_view AS
SELECT first_name, last_name, department
FROM employees;
Now, querying employee_view will return the first name, last name, and department of employees.
SELECT * FROM employee_view;
Views allow you to encapsulate complex SQL queries into simple, reusable queries. This reduces the need for users to write complicated SQL and ensures consistency.
A complex query with multiple joins and filters can be simplified using a view.
CREATE VIEW sales_summary AS
SELECT customers.customer_name, SUM(orders.total_amount) AS total_sales
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id
GROUP BY customers.customer_name;
Now, to get the total sales per customer, simply run:
SELECT * FROM sales_summary;
Some views allow you to insert, update, or delete rows, but this is only possible under certain conditions. The view must be simple, typically derived from a single table without aggregation, GROUP BY, or DISTINCT clauses.
Assuming a view is created from a single table:
CREATE VIEW simple_employee_view AS
SELECT employee_id, first_name, last_name, department
FROM employees;
You can update data through this view:
UPDATE simple_employee_view
SET department = 'Sales'
WHERE employee_id = 5;
This will update the department column in the employees table where employee_id = 5.
You can modify an existing view using the CREATE OR REPLACE VIEW statement.
CREATE OR REPLACE VIEW employee_view AS
SELECT first_name, last_name, department, hire_date
FROM employees;
This will replace the previous definition of employee_view.
To remove a view, use the DROP VIEW statement.
DROP VIEW IF EXISTS employee_view;
To list all views in a database, use the following query:
SHOW FULL TABLES IN database_name WHERE TABLE_TYPE = 'VIEW';
To see the SQL definition of a view:
SHOW CREATE VIEW view_name;