Database Queries: A First Look at SQL · Lesson 32 of 112

Database Views

What you will learn

  • What a view is
  • How to create, use and drop a view
  • Why views are useful: simplicity and control
  • Why a view always shows current data

This lesson runs on the sample database you chose in lesson 4.1. It creates and drops a view in your browser's copy of the data. The examples build on each other from top to bottom, so run them in order; Reset data at the top starts again.

1. A saved query with a name

A join like the ones in lesson 4.5 is long. If you need it often, save it. A view is a query stored in the database under a name, which you can then use like a table:

CREATE VIEW order_details AS
SELECT oi.order_id, c.last_name AS customer, p.name AS product, oi.quantity,
       ROUND(oi.quantity * oi.unit_price, 2) AS total, o.order_date
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
JOIN customers c ON c.customer_id = o.customer_id
JOIN products p ON p.product_id = oi.product_id;
(done)
CREATE VIEW account_overview AS
SELECT a.account_id, c.full_name AS customer, a.account_type, a.status, a.balance_cents / 100.0 AS balance
FROM accounts a
JOIN customers c ON c.customer_id = a.customer_id;
(done)
CREATE VIEW student_grades AS
SELECT st.student_id, st.last_name AS student, c.code AS course, sec.term, e.grade, e.section_id
FROM enrollments e
JOIN students st ON st.student_id = e.student_id
JOIN sections sec ON sec.section_id = e.section_id
JOIN courses c ON c.course_id = sec.course_id;
(done)

No data is copied. The database stores only the query. Now the long join becomes a short one:

SELECT * FROM order_details WHERE order_id <= 3 ORDER BY order_id, product;
order_id  customer  product         quantity  total  order_date
--------  --------  --------------  --------  -----  ----------
       1  Wang      Camping mug            1   21.6  2025-04-23
       1  Wang      Pruning shears         1   29.5  2025-04-23
       1  Wang      Rain poncho            1  32.45  2025-04-23
       1  Wang      Storage box            1   24.0  2025-04-23
       2  Das       Board game             4   48.0  2024-01-21
       3  Bianchi   Day backpack           2    9.0  2025-05-03
(6 rows)
SELECT * FROM account_overview WHERE account_id <= 4 ORDER BY account_id;
account_id  customer       account_type  status  balance
----------  -------------  ------------  ------  -------
         1  Leo Kumar      checking      open     1924.0
         2  Hana Kim       savings       open     520.78
         3  Vera Banerjee  savings       open      627.8
         4  Olga Garcia    checking      closed    999.0
(4 rows)
SELECT * FROM student_grades WHERE student_id = 1 ORDER BY term, course;
student_id  student  course   term         grade  section_id
----------  -------  -------  -----------  -----  ----------
         1  Khan     ART101   2025-Spring   49.2          30
         1  Khan     CS301    2025-Spring   60.8          41
         1  Khan     LANG102  2026-Spring   NULL          19
(3 rows)

You can filter, sort and group a view like any table:

SELECT customer, ROUND(SUM(total), 2) AS spent FROM order_details GROUP BY customer ORDER BY spent DESC, customer LIMIT 5;
customer     spent
--------  --------
Zhang     11720.06
Cohen     10137.76
Bianchi    9078.46
Tanaka     8604.43
Nguyen     8400.13
(5 rows)
SELECT account_type, status, COUNT(*) AS accounts, ROUND(AVG(balance), 2) AS avg_balance FROM account_overview GROUP BY account_type, status ORDER BY account_type, status;
account_type  status  accounts  avg_balance
------------  ------  --------  -----------
checking      closed        21      1524.52
checking      frozen        11      1638.09
checking      open         284      1366.69
savings       closed         9      1246.62
savings       frozen         5      2077.82
savings       open         120      1351.75
(6 rows)
SELECT course, COUNT(*) AS students, ROUND(AVG(grade), 1) AS avg_grade FROM student_grades GROUP BY course ORDER BY avg_grade DESC, course LIMIT 5;
course  students  avg_grade
------  --------  ---------
ART101        64       76.3
HUM201        47       73.2
HUM301        55       73.1
ART202        77       72.8
SCI201        49       72.0
(5 rows)

2. Why use views?

  • Simplicity: write the hard join once; everyone else queries a simple name.
  • Consistency: everyone uses the same definition of, say, "total".
  • Control: a view can show only some columns or rows, so a person can be given the view without the whole table (access rules are in chapter 8).
  • Stability: if tables are reorganised later, the view can be updated and programs using it keep working.

3. A view is always current

Because a view stores a query, not data, it reflects the latest data every time. Change a value in a real table and look at the view again:

SELECT order_id, product, quantity, total FROM order_details WHERE order_id = 1 ORDER BY product;
UPDATE order_items SET quantity = quantity + 1 WHERE order_id = 1;
SELECT order_id, product, quantity, total FROM order_details WHERE order_id = 1 ORDER BY product;
order_id  product         quantity  total
--------  --------------  --------  -----
       1  Camping mug            1   21.6
       1  Pruning shears         1   29.5
       1  Rain poncho            1  32.45
       1  Storage box            1   24.0
(4 rows)

order_id  product         quantity  total
--------  --------------  --------  -----
       1  Camping mug            2   43.2
       1  Pruning shears         2   59.0
       1  Rain poncho            2   64.9
       1  Storage box            2   48.0
(4 rows)

The view shows the new quantities and totals at once, without any extra work. (The view uses the price stored on each order line, unit_price, so a later change of the list price in products would not change old totals. That is how real shops keep the price at the time of sale; see chapters 5 and 15.)

SELECT account_id, customer, status FROM account_overview WHERE account_id = 1;
UPDATE accounts SET status = 'frozen' WHERE account_id = 1;
SELECT account_id, customer, status FROM account_overview WHERE account_id = 1;
account_id  customer   status
----------  ---------  ------
         1  Leo Kumar  open
(1 row)

account_id  customer   status
----------  ---------  ------
         1  Leo Kumar  frozen
(1 row)

The view shows the new status at once, without any extra work.

SELECT student, course, term, grade FROM student_grades WHERE student_id = 1 AND section_id = 30;
UPDATE enrollments SET grade = 100 WHERE student_id = 1 AND section_id = 30;
SELECT student, course, term, grade FROM student_grades WHERE student_id = 1 AND section_id = 30;
student  course  term         grade
-------  ------  -----------  -----
Khan     ART101  2025-Spring   49.2
(1 row)

student  course  term         grade
-------  ------  -----------  -----
Khan     ART101  2025-Spring  100.0
(1 row)

The view shows the new grade at once, without any extra work.

4. Views are usually read-only

INSERT INTO order_details VALUES (1, 'a', 'b', 1, 1, '2026-01-01');
OperationalError: cannot modify order_details because it is a view
INSERT INTO account_overview VALUES (9999, 'a', 'checking', 'open', 1.0);
OperationalError: cannot modify account_overview because it is a view
INSERT INTO student_grades VALUES (1, 'a', 'b', 'c', 1.0, 1);
OperationalError: cannot modify student_grades because it is a view

In SQLite you cannot insert into this view, because it joins several tables and the database cannot tell where each value should go. Change the real tables instead. (Other systems may allow changes through simple views; check their documentation.)

5. Dropping a view

SELECT type, name FROM sqlite_master WHERE type IN ('table', 'view') ORDER BY type DESC, name;
DROP VIEW order_details;
SELECT type, name FROM sqlite_master WHERE type IN ('table', 'view') ORDER BY type DESC, name;
type   name
-----  -------------
view   order_details
table  categories
table  customers
table  employees
table  order_items
table  orders
table  payments
table  products
table  reviews
table  suppliers
(10 rows)

type   name
-----  -----------
table  categories
table  customers
table  employees
table  order_items
table  orders
table  payments
table  products
table  reviews
table  suppliers
(9 rows)
SELECT type, name FROM sqlite_master WHERE type IN ('table', 'view') ORDER BY type DESC, name;
DROP VIEW account_overview;
SELECT type, name FROM sqlite_master WHERE type IN ('table', 'view') ORDER BY type DESC, name;
type   name
-----  ----------------
view   account_overview
table  accounts
table  audit_log
table  branches
table  cards
table  customers
table  loan_payments
table  loans
table  transactions
table  transfers
(10 rows)

type   name
-----  -------------
table  accounts
table  audit_log
table  branches
table  cards
table  customers
table  loan_payments
table  loans
table  transactions
table  transfers
(9 rows)
SELECT type, name FROM sqlite_master WHERE type IN ('table', 'view') ORDER BY type DESC, name;
DROP VIEW student_grades;
SELECT type, name FROM sqlite_master WHERE type IN ('table', 'view') ORDER BY type DESC, name;
type   name
-----  --------------
view   student_grades
table  assignments
table  attendance
table  courses
table  departments
table  enrollments
table  sections
table  students
table  submissions
table  teachers
(10 rows)

type   name
-----  -----------
table  assignments
table  attendance
table  courses
table  departments
table  enrollments
table  sections
table  students
table  submissions
table  teachers
(9 rows)

DROP VIEW removes only the saved query. The tables and all the data are untouched. (sqlite_master is SQLite's own list of what exists in the database.)

Worked example: a safe view for one job

Someone needs only a few columns of a table and should not see the rest. Create a view with only those columns:

The delivery person needs names and cities of active customers, nothing about phones, emails or orders:

CREATE VIEW delivery_list AS
SELECT first_name, last_name, city FROM customers WHERE is_active = 1;
SELECT * FROM delivery_list ORDER BY last_name, first_name LIMIT 5;
first_name  last_name  city
----------  ---------  ------
Amir        Abdi       Cairo
Isla        Abdi       Lagos
Jin         Abdi       Dhaka
Paulo       Abdi       Pune
Ugo         Abdi       Lisbon
(5 rows)

The branch counter needs names, account type and status, but should not see balances:

CREATE VIEW counter_list AS
SELECT a.account_id, c.full_name AS customer, a.account_type, a.status
FROM accounts a
JOIN customers c ON c.customer_id = a.customer_id;
SELECT * FROM counter_list ORDER BY account_id LIMIT 5;
account_id  customer       account_type  status
----------  -------------  ------------  ------
         1  Leo Kumar      checking      frozen
         2  Hana Kim       savings       open
         3  Vera Banerjee  savings       open
         4  Olga Garcia    checking      closed
         5  Amir Singh     checking      open
(5 rows)

The school website shows the course catalogue, but not who teaches what or how many students attend:

CREATE VIEW public_catalogue AS
SELECT code, title, credits FROM courses;
SELECT * FROM public_catalogue ORDER BY code LIMIT 5;
code    title             credits
------  ----------------  -------
ART101  Drawing                 2
ART201  Music                   2
ART202  Drama                   2
CS101   Computing Basics        3
CS201   Programming             4
(5 rows)

The view hides the other columns (and, in the shop, the customers who are not active). This is how views support control: you give access to the view, not to the table behind it. (Names and data are made up.)

Common mistakes

  • Thinking a view stores a copy of the data. It stores only the query.
  • Stacking views on views on views, which becomes slow and hard to understand.
  • Trying to insert into a view. Change the underlying tables.
  • Forgetting that a view depends on its tables. If a table or column is removed, the view breaks.

Key takeaways

  • A view is a saved query with a name, used like a table.
  • It stores no data and always shows current data.
  • Views simplify complex queries and can limit what people see.
  • Views are usually read-only; dropping a view does not delete data.

Practice

1. Write a statement creating a view with only some of the rows of a table.

Show answer

CREATE VIEW cheap_products AS SELECT * FROM products WHERE price < 5;

Show answer

CREATE VIEW open_accounts AS SELECT * FROM accounts WHERE status = 'open';

Show answer

CREATE VIEW big_courses AS SELECT * FROM courses WHERE credits >= 4;

2. Does a view take extra space to store the data?

Show answer

No. It stores only the query, not a copy of the data.

3. If a value in a table changes, does a view that uses it show the old or the new value?

Show answer

The new value, because the query runs again each time the view is used.

4. What does DROP VIEW do to the data in the tables?

Show answer

Nothing. It removes only the saved query.

5. Name two reasons to use a view.

Show answer

For example: to hide a complicated join behind a simple name, and to give someone access to only some columns or rows.

6. Why can you not insert a row into a view that joins several tables?

Show answer

SQLite cannot know which table each value belongs to; you change the underlying tables instead.