runtime
63 / 88

lesson 63 Database engineering · advanced

Views: reusable query definitions

Define a reusable query as a view.

the idea

A normal view is a named query definition. It is reusable without storing a snapshot of the result. A view can simplify business logic, but it is not automatically faster or slower than the equivalent query. SQLite views are read-only unless INSTEAD OF triggers support writes.

tables in this lesson

The challenges use this data. Each column shows its type underneath; → marks a link to another table.

orders6 columns · 12 rows
idinteger · keycustomer_idintegerproduct_idintegerquantityintegerstatustextordered_attext
101112paid2025-01-01
102231paid2025-01-02
103121paid2025-01-05
104352pending2025-01-08
105445paid2025-02-01

showing 5 of 12 rows

products4 columns · 6 rows
idinteger · keynametextcategorytextpricereal
1NotebookStationery12
2Desk lampHome45
3KeyboardTech80
4Pen setStationery8
5HeadphonesTech120

showing 5 of 6 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
CREATE VIEW paid_orders AS
SELECT id,customer_id,quantity
FROM orders
WHERE status='paid';
SELECT *
FROM paid_orders;

Watch for: A view is an abstraction, not a guarantee of materialization or caching.

build it step by step

Each step changes one thing. Run them in order and watch the result change.

  1. Look at the rows a view will read. A view does not copy these rows. It saves a query, and selecting the view reads the current orders.

    step-1.sql
    SELECT id, customer_id, quantity, status
    FROM orders;
  2. Execute a complete script. All setup and the final result run together in one disposable database.

    step-2.sql
    CREATE VIEW paid_orders AS
    SELECT id,customer_id,quantity
    FROM orders
    WHERE status='paid';
    SELECT *
    FROM paid_orders;

challenge 1

Create view paid_orders exposing id, customer_id and quantity for paid orders. Return those columns by selecting the view.

Return idcustomer_idquantityany row ordertable changes are checked too

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.