TExcelTAD
Home › SQL › SQL Views

SQL Views

A view is a saved query that you can use like a table. It stores no data of its own: each time you select from it, the database runs the underlying query against the current data.

sql
CREATE VIEW view_name AS
SELECT columns
FROM tables
WHERE condition;

Creating and using a view

Order lines with product names and line totals are needed in many reports. Save the join once:

sql · try it yourself
CREATE VIEW order_lines AS
SELECT oi.order_id,
       p.name AS product,
       oi.quantity,
       p.price,
       ROUND(oi.quantity * p.price, 2) AS line_total
FROM order_items AS oi
JOIN products AS p ON p.product_id = oi.product_id;

SELECT * FROM order_lines WHERE order_id = 22 ORDER BY product;
order_id | product         | quantity | price | line_total
---------+-----------------+----------+-------+-----------
22       | Cast Iron Pan   | 2        | 38    | 76
22       | Chocolate Cake  | 3        | 22    | 66
22       | Power Bank      | 3        | 29.5  | 88.5
22       | Sparkling Water | 4        | 4.6   | 18.4
(4 rows)

Now any query can build on order_lines — filter it, group it, join it:

sql · try it yourself
CREATE VIEW order_lines AS
SELECT oi.order_id, p.name AS product, oi.quantity,
       ROUND(oi.quantity * p.price, 2) AS line_total
FROM order_items AS oi
JOIN products AS p ON p.product_id = oi.product_id;

SELECT order_id, COUNT(*) AS lines, ROUND(SUM(line_total), 2) AS order_total
FROM order_lines
GROUP BY order_id
ORDER BY order_total DESC
LIMIT 5;
order_id | lines | order_total
---------+-------+------------
31       | 4     | 489.5
14       | 1     | 447
13       | 1     | 267
19       | 4     | 263.95
27       | 3     | 251.3
(5 rows)

Views always show current data

Because a view is just a query, changes to the base tables appear in it immediately:

sql · try it yourself
CREATE VIEW out_of_stock AS
SELECT product_id, name FROM products WHERE stock = 0;

SELECT * FROM out_of_stock ORDER BY product_id;

UPDATE products SET stock = 0 WHERE product_id = 8;
UPDATE products SET stock = 12 WHERE product_id = 4;

SELECT * FROM out_of_stock ORDER BY product_id;
product_id | name
-----------+----------------
4          | Sparkling Water
14         | Avocados
(2 rows)

1 row affected.

1 row affected.

product_id | name
-----------+---------------
8          | Chocolate Cake
14         | Avocados
(2 rows)

Why use views?

Benefit Example
Reuse Write a complex join once, query it many times
Simplicity Analysts query customer_summary instead of four tables
Security Grant access to a view that hides salary instead of the full table (server databases)
Stable interface Rename or split tables; keep the view's columns the same
sql · try it yourself
CREATE VIEW staff_directory AS
SELECT e.first_name || ' ' || e.last_name AS name,
       e.title,
       m.first_name || ' ' || m.last_name AS manager
FROM employees AS e
LEFT JOIN employees AS m ON m.employee_id = e.manager_id;   -- no salary column

SELECT * FROM staff_directory WHERE title LIKE '%Manager%' OR manager IS NULL ORDER BY name;
name        | title              | manager
------------+--------------------+-----------
Grace Holt  | CEO                | NULL
Lin Zhou    | Operations Manager | Grace Holt
Victor Ames | Sales Manager      | Grace Holt
(3 rows)

Changing and dropping views

Task SQLite Others
Create if missing CREATE VIEW IF NOT EXISTS v AS … same (MySQL: CREATE OR REPLACE VIEW)
Replace DROP VIEW v; then CREATE VIEW v AS … CREATE OR REPLACE VIEW v AS … (MySQL, PostgreSQL), ALTER VIEW (SQL Server)
Remove DROP VIEW v; same

Can you write through a view?

In SQLite, views are read-only (unless you add INSTEAD OF triggers). In MySQL, PostgreSQL and SQL Server, simple views over one table can be updated directly.

sql · try it yourself
CREATE VIEW cheap_products AS SELECT product_id, name, price FROM products WHERE price < 3;
UPDATE cheap_products SET price = 2 WHERE product_id = 10;
Error: cannot modify cheap_products because it is a view

Note: A materialized view (PostgreSQL, Oracle; "indexed view" in SQL Server) does store its result and must be refreshed. In SQLite you can get the same effect with CREATE TABLE … AS SELECT.

Test yourself

Does a regular view store a copy of the data?

  1. Yes, at creation time
  2. No, it runs its query each time it is used
  3. Only the first 100 rows
  4. Only in SQLite

How do you change an existing view in SQLite?

  1. ALTER VIEW
  2. CREATE OR REPLACE VIEW
  3. DROP VIEW and CREATE VIEW again
  4. UPDATE VIEW