Creating Tables and Constraints · Lesson 47 of 64

SQL Views

What you will learn

  • What a view is and how to create one
  • Why a view always shows the current data
  • How a view can hide a join or a summary
  • How to replace and drop a view, and what you cannot do with it

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). The views you create exist only in your browser's copy of the data; Reset data removes them. Run the cells from top to bottom. (Database Fundamentals, lesson 4.7, introduces views; this lesson goes a step further.)

1. A saved query

A view is a query saved under a name. It stores no rows: every time you read the view, the database runs the saved query. You use it like a table:

CREATE VIEW lib_order_details AS
SELECT o.order_id, o.order_date, o.status, c.first_name, c.last_name
FROM orders AS o
JOIN customers AS c ON c.customer_id = o.customer_id;
SELECT * FROM lib_order_details ORDER BY order_id LIMIT 4;
order_id  order_date  status     first_name  last_name
--------  ----------  ---------  ----------  ---------
       1  2025-04-23  delivered  Dana        Wang
       2  2024-01-21  delivered  Ugo         Das
       3  2025-05-03  delivered  Jin         Bianchi
       4  2026-08-18  paid       Sara        Nair
(4 rows)
CREATE VIEW lib_account_details AS
SELECT a.account_id, a.account_type, a.status, a.balance_cents, c.full_name, b.name AS branch
FROM accounts AS a
JOIN customers AS c ON c.customer_id = a.customer_id
JOIN branches AS b ON b.branch_id = a.branch_id;
SELECT * FROM lib_account_details ORDER BY account_id LIMIT 4;
account_id  account_type  status  balance_cents  full_name      branch
----------  ------------  ------  -------------  -------------  ---------
         1  checking      open           192400  Leo Kumar      Central
         2  savings       open            52078  Hana Kim       Riverside
         3  savings       open            62780  Vera Banerjee  Airport
         4  checking      closed          99900  Olga Garcia    Central
(4 rows)
CREATE VIEW lib_section_details AS
SELECT s.section_id, s.term, c.code, c.title, t.name AS teacher
FROM sections AS s
JOIN courses AS c ON c.course_id = s.course_id
JOIN teachers AS t ON t.teacher_id = s.teacher_id;
SELECT * FROM lib_section_details ORDER BY section_id LIMIT 4;
section_id  term         code     title                   teacher
----------  -----------  -------  ----------------------  -------------
         1  2025-Autumn  MATH101  Foundations of Algebra  Liam Patel
         2  2025-Spring  MATH201  Geometry                Bruno Bianchi
         3  2025-Autumn  MATH201  Geometry                Sven Silva
         4  2026-Spring  MATH201  Geometry                Kira Perez
(4 rows)

The view hides the join. Anyone who reads SELECT * FROM lib_order_details (or the view of your database) gets the combined columns without writing the ON conditions. That makes queries shorter and the join in one place, where it can be fixed once.

2. A view is always current

Because the view runs its query each time, it shows the latest data. Change a row in the underlying table and the view changes:

UPDATE orders SET status = 'cancelled' WHERE order_id = 1;
SELECT order_id, status FROM lib_order_details WHERE order_id = 1;
order_id  status
--------  ---------
       1  cancelled
(1 row)
UPDATE accounts SET status = 'frozen' WHERE account_id = 1;
SELECT account_id, status FROM lib_account_details WHERE account_id = 1;
account_id  status
----------  ------
         1  frozen
(1 row)
UPDATE sections SET term = '2026-Autumn' WHERE section_id = 1;
SELECT section_id, term FROM lib_section_details WHERE section_id = 1;
section_id  term
----------  -----------
         1  2026-Autumn
(1 row)

3. Views for summaries

A view can hold a GROUP BY, so a report is one short query away:

CREATE VIEW lib_orders_per_status AS
SELECT status, COUNT(*) AS orders FROM orders GROUP BY status;
SELECT * FROM lib_orders_per_status ORDER BY status;
status     orders
---------  ------
cancelled     171
delivered    1877
paid          186
pending       135
shipped       231
(5 rows)
CREATE VIEW lib_accounts_per_type AS
SELECT account_type, status, COUNT(*) AS accounts, SUM(balance_cents) AS total_cents FROM accounts GROUP BY account_type, status;
SELECT * FROM lib_accounts_per_type ORDER BY account_type, status;
account_type  status  accounts  total_cents
------------  ------  --------  -----------
checking      closed        21      3201500
checking      frozen        12      1994300
checking      open         283     38621500
savings       closed         9      1121962
savings       frozen         5      1038909
savings       open         120     16220959
(6 rows)
CREATE VIEW lib_sections_per_term AS
SELECT term, COUNT(*) AS sections, SUM(capacity) AS seats FROM sections GROUP BY term;
SELECT * FROM lib_sections_per_term ORDER BY term;
term         sections  seats
-----------  --------  -----
2025-Autumn        13    380
2025-Spring        16    480
2026-Autumn         1     25
2026-Spring        11    325
(4 rows)

4. Views and safety

A view can show only some columns or rows, for example hiding personal details (Database Fundamentals, lesson 8.4):

CREATE VIEW lib_public_customers AS SELECT customer_id, first_name, city FROM customers;
SELECT * FROM lib_public_customers ORDER BY customer_id LIMIT 3;
customer_id  first_name  city
-----------  ----------  -----
          1  Vik         Leeds
          2  Wanda       Leeds
          3  Dana        Cairo
(3 rows)
CREATE VIEW lib_public_customers AS SELECT customer_id, full_name, city FROM customers;
SELECT * FROM lib_public_customers ORDER BY customer_id LIMIT 3;
customer_id  full_name    city
-----------  -----------  -------
          1  Chen Park    Lima
          2  Rafi Uddin   Manila
          3  Grace Kamau  Toronto
(3 rows)
CREATE VIEW lib_public_students AS SELECT student_id, first_name, last_name FROM students;
SELECT * FROM lib_public_students ORDER BY student_id LIMIT 3;
student_id  first_name  last_name
----------  ----------  ---------
         1  Vera        Khan
         2  Elena       Haque
         3  Chloe       Garcia
(3 rows)

In SQLite this limits what your own code asks for; it is not a wall against someone who can open the file. Server databases can enforce it with privileges.

5. What you cannot do to a view

A view has no rows of its own, so you cannot normally insert into it or update it in SQLite: it is read-only. Try it:

UPDATE lib_orders_per_status SET orders = 0 WHERE status = 'paid';
OperationalError: cannot modify lib_orders_per_status because it is a view
UPDATE lib_accounts_per_type SET accounts = 0 WHERE status = 'open';
OperationalError: cannot modify lib_accounts_per_type because it is a view
UPDATE lib_sections_per_term SET sections = 0 WHERE term = '2025-Spring';
OperationalError: cannot modify lib_sections_per_term because it is a view

Change the underlying tables instead. Views do not store data, so they cannot get out of date, but a view over a heavy query is slow every time: it is not a saved result (a saved result is a copy table; Database Fundamentals, lesson 11.3 compares the two).

6. Replace and drop

SQLite has no CREATE OR REPLACE VIEW. To change a view, drop it and create it again. IF EXISTS avoids an error when it is not there:

DROP VIEW IF EXISTS lib_example;
CREATE VIEW lib_example AS SELECT 1 AS n;
DROP VIEW lib_example;
CREATE VIEW lib_example AS SELECT 2 AS n;
SELECT * FROM lib_example;
n
-
2
(1 row)
DROP VIEW IF EXISTS lib_example;
CREATE VIEW lib_example AS SELECT 1 AS n;
DROP VIEW lib_example;
CREATE VIEW lib_example AS SELECT 2 AS n;
SELECT * FROM lib_example;
n
-
2
(1 row)
DROP VIEW IF EXISTS lib_example;
CREATE VIEW lib_example AS SELECT 1 AS n;
DROP VIEW lib_example;
CREATE VIEW lib_example AS SELECT 2 AS n;
SELECT * FROM lib_example;
n
-
2
(1 row)

Dropping a view never touches the data.

Worked example: a view for a monthly report

The same long query is pasted into three reports.

Step Do
1 write the query once and check its result
2 CREATE VIEW monthly_sales AS <the query>
3 the reports use SELECT ... FROM monthly_sales
4 when the logic changes, drop and recreate the view in one place

All three reports are corrected together. The query is made up.

Common mistakes

  • Treating a view as a saved result. It re-runs its query every time.
  • Trying to update a view in SQLite.
  • Stacking views on views until nobody knows what runs.
  • Dropping a table that a view uses.
  • Using a view as a security wall in SQLite.

Key takeaways

  • CREATE VIEW name AS SELECT ... saves a query; it stores no rows and always shows current data.
  • Views hide joins and complexity, and can show only some columns.
  • A view is read-only in SQLite; change the tables.
  • To change a view, drop it and create it again.

Practice

1. What does a view store?

Show answer

Only the query, not the rows.

2. If you change a row in the table, does the view change?

Show answer

Yes, because the view runs its query on the current data each time.

3. Why use a view for a long join?

Show answer

The join is written once, queries become short, and a fix is made in one place.

4. How do you change an existing view in SQLite?

Show answer

DROP VIEW it and CREATE VIEW it again.

5. Can you UPDATE a view in SQLite?

Show answer

Not normally: it has no rows of its own. Update the underlying tables.

6. Is a view faster than the query it contains?

Show answer

No. It runs the same query each time; it is a shortcut for writing, not for speed.