Sub topic 4
Using views to simplify and abstract queries
This chapter assumes you can write SELECT queries with WHERE, GROUP BY and JOIN, and that you have created a view with CREATE VIEW as shown in the earlier chapters. It uses the departments and employees tables from the sample schema. Here you will use views for two jobs: hiding query complexity and putting a stable interface between applications and table structure.
The problem views solve
Suppose three reports need the number of active employees and the payroll for each department. Without a view, each report carries its own copy of the same join, filter and aggregation. The copies drift apart over time. One report forgets the status filter, another uses an inner join and silently drops empty departments. Everyone then sees different numbers for "headcount".
A view gives the definition one home. Every report selects from that view, and the logic is written, reviewed and fixed in one place.
CREATE VIEW department_stats AS
SELECT d.id AS department_id,
d.name AS department,
COUNT(e.id) AS headcount,
COALESCE(SUM(e.salary), 0) AS total_salary
FROM departments d
LEFT JOIN employees e
ON e.department_id = d.id
AND e.status = 'active'
GROUP BY d.id, d.name;Several decisions are now fixed in the view:
- The
LEFT JOINkeeps departments that have no employees. - The
status = 'active'condition sits in theONclause, not inWHERE. AWHEREfilter one.statuswould remove the empty departments again, because theirecolumns are NULL. COUNT(e.id)counts only matched employees, so an empty department gets 0 instead of 1.COALESCEturns the NULL sum of an empty department into 0.
A report now reads like a query against a plain table:
SELECT department, headcount
FROM department_stats
WHERE headcount >= 5
ORDER BY total_salary DESC;What a view hides
A view can hide several kinds of detail from the people who query it:
| Hidden detail | Example | Benefit to the caller |
|---|---|---|
| Joins | `employee_directory` joins two tables | Callers do not need to know the foreign keys |
| Aggregation | `department_stats` groups and sums | Callers filter finished numbers |
| Calculations | `salary / 12` as `monthly_salary` | One formula, one name |
| Business rules | `status = 'active'` | "Active" means the same thing everywhere |
| Awkward names | `d.name AS department` | Readable, non-clashing columns |
Because the definition is just a query, you can build it in steps. Start with the SELECT, check that it returns what you expect, and only then wrap it in CREATE VIEW. Name the columns with aliases or a column list as described in the earlier chapter on naming. A caller should never need to guess which of two name columns they received.
Encoding a business definition once
Terms such as "active employee", "current customer" and "overdue invoice" are business rules, and they tend to be repeated in many queries. Put each one in a view:
CREATE VIEW current_staff AS
SELECT id, name, department_id
FROM employees
WHERE status = 'active';Queries that need current staff join to current_staff and never mention status at all. If the rule changes, for example to exclude employees on leave, you edit one view.
Insulating applications from schema changes
A view is also an interface. Applications and reports query the view's columns, and the view maps them onto whatever the tables look like today. When the tables change, you rewrite the view and the callers keep working.
Say the team decides to replace the text column status with a boolean is_active. You migrate the table, then redefine the view with the same output columns:
ALTER TABLE employees ADD COLUMN is_active BOOLEAN NOT NULL DEFAULT TRUE;
UPDATE employees SET is_active = (status = 'active');
CREATE OR REPLACE VIEW current_staff AS
SELECT id, name, department_id
FROM employees
WHERE is_active;Every query that selects from current_staff returns the same columns as before. The change is invisible to them.
This only works for changes that the view can absorb. If a caller needs a column that no longer exists in any form, the interface has to change too. A view reduces the cost of schema changes. It does not remove that cost.
Pitfall: `SELECT *` in a view definition
A view written with SELECT * looks like it should follow its table. In PostgreSQL and MySQL it does not. The database expands * into an explicit column list when you create the view and stores that list.
CREATE VIEW staff_all AS
SELECT * FROM employees;
ALTER TABLE employees ADD COLUMN phone VARCHAR(30);
-- staff_all still returns only the columns that existed when it was created.
SELECT * FROM staff_all;The new phone column does not appear. Dropping a referenced column can also break the view, or the database may refuse the ALTER TABLE. List the columns you want explicitly. The view then states its contract and does not depend on how the engine expands *.
Pitfall: `ORDER BY` inside a view
Do not rely on an ORDER BY in a view definition to sort the results. A query on a view is an ordinary query, and the outer query decides the final order. Some systems reject ORDER BY in a view, some ignore it, and some honor it only in simple cases. Sort in the query that uses the view:
SELECT department, total_salary
FROM department_stats
ORDER BY total_salary DESC;The exception is a view that needs ORDER BY together with LIMIT (or FETCH FIRST), such as a "top 10" view. There the sort decides which rows are in the view, and it is kept.
Pitfall: simple-looking, expensive views
A view makes a query look cheap. SELECT * FROM department_stats is one short line, but the database still runs the full join and aggregation every time. A view does not store results. Someone who does not read the definition might join department_stats to several other large tables without realizing how much work each call does. The performance chapter covers how the database expands views into the calling query. For now, keep two habits:
- Check the definition of a view before you build a large query on it.
- Keep views focused. A view that joins ten tables serves one report well and is wasteful for every other caller.
Choosing what belongs in a view
A view is a good fit when:
- Several queries repeat the same join, filter or calculation.
- A business rule needs one authoritative definition.
- You want callers to depend on a stable set of columns, not on the table layout.
A view is a poor fit when it would serve only one query, or when its logic depends on parameters, such as a date range chosen at call time. A view cannot take parameters. Callers filter its output with WHERE, and the database generally pushes those filters down into the view's query. For logic that really needs inputs, look at functions or procedures in your database.
Exercise
The query below is meant to be the body of a view that shows every department with its count of active employees, including departments with none. It returns no row for empty departments. What is wrong, and how do you fix it? SELECT d.name AS department, COUNT(e.id) AS headcount FROM departments d LEFT JOIN employees e ON e.department_id = d.id WHERE e.status = 'active' GROUP BY d.name;
Show answer
The WHERE e.status = 'active' filter runs after the join. For an empty department, e.status is NULL, so the row is removed and the department disappears from the result. Move the condition into the join: LEFT JOIN employees e ON e.department_id = d.id AND e.status = 'active' and delete the WHERE clause. Empty departments then stay in the result with COUNT(e.id) equal to 0. Grouping by d.id as well as d.name is also safer, in case two departments share a name.
Exercise
A view is created with CREATE VIEW staff_all AS SELECT * FROM employees;. You then add a column to employees. In PostgreSQL or MySQL, will SELECT * FROM staff_all include the new column? How would you write the view to avoid surprises?
Show answer
No. The database expands * into a fixed column list when the view is created, so the new column is missing until you redefine the view. Write the columns out explicitly, for example SELECT id, name, email, salary, status, department_id FROM employees, and add new columns to the view deliberately with CREATE OR REPLACE VIEW.