Sub topic 10
How the Database Runs a Query Against a View
This chapter assumes you can write SELECT queries with joins and GROUP BY, and that you have created a view with CREATE VIEW. It uses the employees and departments tables from earlier chapters. The examples use PostgreSQL syntax, and the chapter notes where other systems differ.
A view stores a query, not rows
A regular view has no rows of its own. The database keeps only the text or parsed form of its SELECT. When you query the view, the database rewrites your query so it uses that stored SELECT, and then plans and runs the combined result.
Take this view:
CREATE VIEW active_employees AS
SELECT id, name, salary, department_id
FROM employees
WHERE status = 'active';You then write:
SELECT name, salary
FROM active_employees
WHERE salary > 6000;The database treats the view as a subquery. Conceptually it runs this:
SELECT name, salary
FROM (
SELECT id, name, salary, department_id
FROM employees
WHERE status = 'active'
) AS active_employees
WHERE salary > 6000;The first step is called view expansion (some systems call it view resolution). The view disappears and only a query on base tables remains. Because expansion happens every time you run the query, the result always reflects the current table data.
Merging: the usual fast path
Once the view is expanded, the optimizer tries to flatten the subquery into the outer query. This is called view merging, or subquery pull-up. For active_employees the merged form is:
SELECT name, salary
FROM employees
WHERE status = 'active'
AND salary > 6000;After merging, the optimizer sees one query with both conditions. It can pick any index on status or salary and apply its usual join and filter strategies. In this case the view costs nothing at run time. It is a naming convenience.
When merging is blocked
The optimizer can only merge a subquery when doing so cannot change the result. These constructs usually prevent it:
- Aggregates and
GROUP BY DISTINCTLIMIT,OFFSET, orFETCH FIRST- Window functions
- Set operations such as
UNION(some systems still handleUNION ALLspecially) - Volatile functions such as
random(), in some systems
Consider an aggregate view:
CREATE VIEW department_salary_view AS
SELECT department_id,
SUM(salary) AS total_salary
FROM employees
GROUP BY department_id;The view must compute its sums before an outer query can filter on them. The optimizer cannot fold it into a plain scan of employees. It plans the view as its own step and then combines it with the outer query.
Even then, the outer WHERE clause is not always applied at the end. Many optimizers perform predicate pushdown, which moves a condition from the outer query into the view's query when that is safe:
SELECT total_salary
FROM department_salary_view
WHERE department_id = 3;A condition on department_id is safe to push down because it is the grouping column. Filtering the rows first and then grouping gives the same answer for department 3, and it avoids summing every other department. PostgreSQL, Oracle, SQL Server, and recent MySQL versions all do this in common cases.
A condition on the aggregate output is different:
SELECT department_id
FROM department_salary_view
WHERE total_salary > 100000;This condition cannot be applied before the sums exist. The database must aggregate all departments and then filter. That is correct, but it costs more than the first query.
Here is a second blocking case, a view with LIMIT:
CREATE VIEW top_paid AS
SELECT id, name, salary
FROM employees
ORDER BY salary DESC
LIMIT 10;If you run SELECT * FROM top_paid WHERE name LIKE 'A%', the database must find the ten top-paid employees first and then filter those ten. Pushing name LIKE 'A%' inside would return the top ten among employees whose names start with A. That is a different result, so a correct optimizer will not do it.
Seeing what the optimizer did
Use EXPLAIN to check. In PostgreSQL:
EXPLAIN
SELECT name, salary
FROM active_employees
WHERE salary > 6000;For a merged view, the plan shows a scan of employees only, with both conditions in the filter or index condition. The name active_employees does not appear. For an unmerged view, the plan contains a separate node for the subquery, such as a Subquery Scan over an aggregate node. Plan details differ by database and version, so read your own system's output instead of expecting a particular shape.
MySQL's explicit algorithm setting
MySQL lets you state the strategy in the view definition:
CREATE ALGORITHM = MERGE VIEW active_employees_merge AS
SELECT id, name, salary, department_id
FROM employees
WHERE status = 'active';
CREATE ALGORITHM = TEMPTABLE VIEW department_salary_temp AS
SELECT department_id,
SUM(salary) AS total_salary
FROM employees
GROUP BY department_id;MERGE folds the view into the outer query. TEMPTABLE runs the view into a temporary table first, which can hold locks for less time but cannot use the base table's indexes for outer conditions. The default, UNDEFINED, lets MySQL choose, and it picks MERGE when it can. If you ask for MERGE on a view that cannot be merged, MySQL falls back to TEMPTABLE with a warning. Most other systems have no such setting. The optimizer decides.
Nested views multiply the work
A view built on another view expands recursively. If view_c selects from view_b, which selects from view_a, then a query on view_c expands into all three definitions. If every layer is simple, merging flattens the whole stack and the cost is the same as a handwritten query. Problems appear when:
- One layer contains an aggregate or
DISTINCT, which blocks merging at that point. - Several layers each join the same table, so the final query joins it more times than the author intended.
- A layer selects columns the outer query never uses, and the optimizer cannot remove the join that supplies them.
Join removal is possible in narrow cases. For example, PostgreSQL can drop a LEFT JOIN when no column from the joined table is used and the join key is unique there. An inner join, such as the one in employee_directory, is usually kept, because it can filter rows even when you select none of the department's columns.
Other things the expansion model explains
- Column lists are fixed at creation. In PostgreSQL and MySQL,
SELECT *in a view is expanded to the real column list when you create the view. If you later add a column toemployees, the view does not show it until you recreate the view. ORDER BYinside a view is unreliable. SQL treats a table as an unordered set, and the outer query may reorder or merge away the inner sort. PutORDER BYin the outer query. Some systems reject it in a view unlessLIMITorTOPis also present.- Indexes belong to base tables. You cannot create an index on a regular view. Index the columns in the underlying tables that the view's joins and filters use.
- Statistics come from base tables. Row estimates for a view are derived from table statistics. A stale
ANALYZE(or equivalent) gives poor plans for view queries, as it does for any other query. - Permissions are checked at the view level. In PostgreSQL the view owner's privileges apply to the base tables by default, which is why you can grant access to a view without granting access to its tables.
When expansion cost matters: materialize
If a view contains heavy work, such as large aggregates, and many queries read it, expansion repeats that work on each call. Options, in order of effort:
- Make sure base tables have indexes that support the view's joins and filters.
- Rewrite the view to avoid the blocking construct, if the logic allows it.
- Store the result with a materialized view, covered in the next chapters. Reads become fast, but the data is stale until refreshed.
Exercise
A view is defined as SELECT department_id, COUNT(*) AS headcount FROM employees GROUP BY department_id. For each query, say whether the optimizer can usually push the condition into the view before aggregating: (a) WHERE department_id = 2, (b) WHERE headcount > 5.
Show answer
(a) Yes. department_id is the grouping column, so filtering rows first gives the same counts for that department and avoids counting the rest. (b) No. headcount exists only after aggregation, so the database must count every department and then filter the results.
Exercise
You add a hire_date column to employees. A view employee_all was created with SELECT * FROM employees in PostgreSQL. Will SELECT hire_date FROM employee_all work? Why or why not?
Show answer
No. PostgreSQL expands * into the column list when the view is created, so the stored definition does not include hire_date. You must recreate the view, for example with CREATE OR REPLACE VIEW, to include the new column.
Exercise
You run EXPLAIN on a query against a view and on the equivalent query against the base tables, and the plans are identical. What does that tell you about the view?
Show answer
The optimizer merged the view into the outer query, so the view adds no run-time cost. It acts only as a name for the underlying query.