← Learning Hub
Intermediate

Views and Indexes

As databases grow, two things matter: reusing complex queries and keeping them fast. A view saves a query under a name so everyone uses the same logic. An index is like the index at the back of a book - it lets the database find rows without reading the whole table.

Views: saved queries

A view is a query saved under a name. You use it like a table. It keeps long queries in one place and lets people see only the columns they should.

Example
CREATE VIEW order_totals AS
SELECT o.id AS order_id, c.name, o.status, SUM(oi.qty * oi.price) AS total
FROM orders o
JOIN customers c    ON c.id = o.customer_id
JOIN order_items oi ON oi.order_id = o.id
GROUP BY o.id, c.name, o.status;

SELECT * FROM order_totals WHERE total > 1000 ORDER BY total DESC;

-- Result:
-- order_id | name        | status    | total
-- ---------+-------------+-----------+------
-- 104      | Neha Singh  | cancelled | 3999
-- 107      | Ravi Kumar  | shipped   | 2798
-- 105      | Arjun Mehta | delivered | 2097
-- 103      | Asha Verma  | shipped   | 1997
-- 101      | Asha Verma  | delivered | 1595
-- 102      | Ravi Kumar  | delivered | 1499
▶ Try it yourself

Indexes: fast searching

Without an index, the database reads every row to find matches - fine for 8 rows, slow for 8 million. An index is like the index at the back of a book: it jumps straight to the right rows.

Example
CREATE INDEX idx_orders_customer ON orders(customer_id);
CREATE INDEX idx_orders_status_date ON orders(status, order_date);
CREATE UNIQUE INDEX idx_customers_email ON customers(email);
  • Add indexes on columns used in WHERE, JOIN ... ON and ORDER BY.
  • Primary keys are indexed automatically.
  • Indexes make reads faster but writes (INSERT/UPDATE) a little slower, and take space - don't index everything.
  • EXPLAIN (or EXPLAIN QUERY PLAN in SQLite) shows whether a query uses an index.
Example
CREATE INDEX idx_orders_customer ON orders(customer_id);
EXPLAIN QUERY PLAN SELECT * FROM orders WHERE customer_id = 1;

-- Result:
-- id | parent | notused | detail
-- ---+--------+---------+--------------------------------------------------------------
-- 3  | 0      | 61      | SEARCH orders USING INDEX idx_orders_customer (customer_id=?)
▶ Try it yourself
A query that wraps the column in a function, like WHERE UPPER(name) = 'ASHA', usually can't use a normal index on name.
Key points
  • A view is a saved query you can select from.
  • Indexes speed up searches on the indexed columns.
  • Indexes cost space and slow writes slightly - add them where needed.

📝 Test yourself

1. What is a view?
2. What is the downside of many indexes?
3. Fill in the statement that makes an index:
CREATE idx_city ON customers(city);