TExcelTAD
Home › MySQL › MySQL Views

MySQL Views

A view is a saved SELECT statement with a name. You query it like a table, but it stores no data of its own: every time you use it, MySQL runs the underlying query against the current data.

sql
CREATE VIEW view_name AS
SELECT ...;

Views are useful to:

  • give a complex query (joins, calculations) a simple name,
  • present data in a friendlier shape (full_name instead of two columns),
  • hide columns or rows: give a reporting user access to a view without the salary column, not to the table.

Creating and using a view

mysql · try it yourself
CREATE VIEW order_totals AS
SELECT o.order_id,
       o.order_date,
       CONCAT(c.first_name, ' ', c.last_name) AS customer,
       o.status,
       ROUND(SUM(d.quantity * d.unit_price * (1 - d.discount)), 2) AS total
FROM orders AS o
JOIN customers     AS c ON c.customer_id = o.customer_id
JOIN order_details AS d ON d.order_id = o.order_id
GROUP BY o.order_id, o.order_date, c.first_name, c.last_name, o.status;

SELECT * FROM order_totals WHERE total > 30 ORDER BY total DESC;
+----------+------------+--------------+-----------+-------+
| order_id | order_date | customer     | status    | total |
+----------+------------+--------------+-----------+-------+
|        4 | 2025-01-27 | Ana Silva    | delivered | 59.00 |
|       15 | 2025-04-16 | Noah Fischer | delivered | 36.50 |
|       14 | 2025-04-08 | Ana Silva    | delivered | 35.21 |
|       10 | 2025-03-10 | Kofi Mensah  | delivered | 34.38 |
|        1 | 2025-01-05 | Ana Silva    | delivered | 33.80 |
|       19 | 2025-05-20 | Ben Carter   | shipped   | 32.45 |
|        5 | 2025-02-02 | Elena Rossi  | delivered | 32.30 |
+----------+------------+--------------+-----------+-------+

The view can be filtered, sorted, joined and aggregated like any table:

mysql · try it yourself
CREATE VIEW order_totals AS
SELECT o.order_id, o.customer_id, o.status,
       SUM(d.quantity * d.unit_price * (1 - d.discount)) AS total
FROM orders AS o
JOIN order_details AS d ON d.order_id = o.order_id
GROUP BY o.order_id, o.customer_id, o.status;

SELECT status, COUNT(*) AS orders, ROUND(AVG(total), 2) AS avg_total
FROM order_totals
GROUP BY status
ORDER BY status;
+------------+--------+-----------+
| status     | orders | avg_total |
+------------+--------+-----------+
| cancelled  |      2 |     18.20 |
| delivered  |     15 |     26.84 |
| processing |      3 |     21.13 |
| shipped    |      2 |     26.80 |
+------------+--------+-----------+

Views are always up to date

Because a view is just a stored query, changes to the base tables show up immediately:

mysql · try it yourself
CREATE VIEW low_stock AS
SELECT product_id, name, units_in_stock
FROM products
WHERE units_in_stock < 20 AND discontinued = 0;

SELECT * FROM low_stock;
UPDATE products SET units_in_stock = 5 WHERE product_id = 1;
SELECT * FROM low_stock;
+------------+----------------------+----------------+
| product_id | name                 | units_in_stock |
+------------+----------------------+----------------+
|          4 | Sparkling Water 6x1L |              0 |
|          7 | Chocolate Cake       |              8 |
|         20 | Laundry Pods (30)    |             12 |
+------------+----------------------+----------------+
+------------+----------------------+----------------+
| product_id | name                 | units_in_stock |
+------------+----------------------+----------------+
|          1 | Espresso Beans 1kg   |              5 |
|          4 | Sparkling Water 6x1L |              0 |
|          7 | Chocolate Cake       |              8 |
|         20 | Laundry Pods (30)    |             12 |
+------------+----------------------+----------------+

Changing and dropping views

mysql · try it yourself
CREATE VIEW uk_customers AS
SELECT first_name, last_name FROM customers WHERE country = 'UK';

CREATE OR REPLACE VIEW uk_customers AS
SELECT first_name, last_name, city FROM customers WHERE country = 'UK';

SELECT * FROM uk_customers ORDER BY last_name;

SELECT TABLE_NAME FROM information_schema.VIEWS WHERE TABLE_SCHEMA = 'shop';
DROP VIEW uk_customers;
DROP VIEW IF EXISTS uk_customers;
+------------+-----------+------------+
| first_name | last_name | city       |
+------------+-----------+------------+
| George     | Brown     | London     |
| Ben        | Carter    | London     |
| Farah      | Khan      | Manchester |
+------------+-----------+------------+
+--------------+
| TABLE_NAME   |
+--------------+
| uk_customers |
+--------------+

CREATE OR REPLACE VIEW (or ALTER VIEW) changes the definition; DROP VIEW removes the view but never touches the underlying data. SHOW FULL TABLES also lists views, marked with the type VIEW.

Updatable views

A simple view, one table without GROUP BY, DISTINCT, aggregates or UNION, is updatable: UPDATE, DELETE and INSERT on the view change the base table.

mysql · try it yourself
CREATE VIEW bakery AS
SELECT product_id, name, unit_price FROM products WHERE category_id = 2;

UPDATE bakery SET unit_price = unit_price + 0.20 WHERE name = 'Butter Croissant';
SELECT name, unit_price FROM products WHERE product_id = 6;
+------------------+------------+
| name             | unit_price |
+------------------+------------+
| Butter Croissant |       1.80 |
+------------------+------------+

Through such a view you could also update a row so that it no longer matches the view's WHERE (move a product out of the bakery). Adding WITH CHECK OPTION to the view definition forbids that: every row changed or inserted through the view must still be visible through it.

sql
CREATE VIEW bakery AS
SELECT product_id, name, category_id, unit_price FROM products WHERE category_id = 2
WITH CHECK OPTION;

UPDATE bakery SET category_id = 5 WHERE product_id = 6;
-- ERROR 1369 (HY000): CHECK OPTION failed 'shop.bakery'

Note: A view doesn't make queries faster by itself: MySQL merges the view's query into yours (or builds a temporary table for it) every time. MySQL has no materialized views; to store results, use a summary table filled with INSERT ... SELECT.

Test yourself

Does a view store a copy of the data?

  1. Yes, refreshed daily
  2. Yes, refreshed on every write
  3. No, it is a stored query run when you use it
  4. Only for updatable views

Which statement changes an existing view's definition?

  1. UPDATE VIEW
  2. CREATE OR REPLACE VIEW
  3. MODIFY VIEW
  4. RENAME VIEW

What does WITH CHECK OPTION do?

  1. Checks the view's syntax
  2. Rejects changes through the view that would make a row invisible in it
  3. Makes the view read-only
  4. Enables CHECK constraints