Sub topic 14
Limitations and common pitfalls
This chapter assumes you can write joins and aggregates, you know how CREATE VIEW, CREATE OR REPLACE VIEW and DROP VIEW work, and you have seen GRANT, WITH CHECK OPTION and materialized views. Examples use the employees and departments tables from earlier chapters and PostgreSQL syntax. Where other systems differ, the text says so.
Views fail quietly more often than they fail loudly. A view can return fewer rows than you expect, keep an old column list, or reject a write for a reason that is not obvious from the error. Each section below names one pitfall, shows how it appears, and gives a fix.
An inner join silently drops rows
employee_directory uses an inner JOIN. An employee with no department disappears from it:
INSERT INTO employees (id, name, salary, status, department_id)
VALUES (3, 'Cara', 5200, 'active', NULL);
SELECT * FROM employee_directory WHERE id = 3;The query returns no rows. The row exists in employees, but d.id = e.department_id is never true when department_id is NULL. Every query against the view inherits this filter, and nobody sees it unless they read the definition.
The fix is to choose the join type on purpose:
CREATE OR REPLACE VIEW employee_directory AS
SELECT e.id,
e.name,
d.name AS department
FROM employees e
LEFT JOIN departments d ON d.id = e.department_id;The column list is unchanged, so the replacement succeeds. Employees without a department now appear with department set to NULL.
SELECT * freezes the column list
Many systems expand * once, when the view is created. PostgreSQL and MySQL both do this. Later column additions never reach the view:
CREATE VIEW employee_snapshot AS
SELECT * FROM employees;
ALTER TABLE employees ADD COLUMN hire_date DATE;
SELECT * FROM employee_snapshot; -- hire_date is not in the resultSome systems, such as SQLite, re-expand * each time the view is used, so the same code behaves differently there. List the columns you need and the behavior is the same everywhere. Explicit lists also stop a new sensitive column from leaking through a view that was meant to hide it.
Changing a view with CREATE OR REPLACE has rules
CREATE OR REPLACE VIEW is not a free rewrite. In PostgreSQL the new query must produce the existing columns with the same names, types and order. You may only add new columns at the end. Renaming a column, removing one, or changing its type fails with an error. In that case, drop the view and create it again, after dealing with its dependents (next section).
Other systems use different syntax. SQL Server uses CREATE OR ALTER VIEW, and older versions have only ALTER VIEW. Keep view definitions in version-controlled migration scripts, not in memory.
Dependencies block drops and alterations
A view that reads another view depends on it. Create one:
CREATE VIEW engineering_staff AS
SELECT id, name
FROM employee_directory
WHERE department = 'Engineering';Now DROP VIEW employee_directory; fails in PostgreSQL because engineering_staff depends on it. Adding CASCADE drops both views:
DROP VIEW employee_directory CASCADE;CASCADE is useful and dangerous. It removes every dependent view, and it can also remove grants held on them. Look at the dependency list before you use it.
The same protection applies to base tables. PostgreSQL refuses to drop or retype a column that a view uses. Other systems behave differently. MySQL accepts the change, and the view then fails at query time. Oracle marks the view invalid until it recompiles. Run your migrations on a test copy to see which behavior your system has.
Nested views hide cost and errors
Each layer of nesting is expanded into the layer above it. A query three views deep can contain joins that the person writing it never saw. Two problems follow:
- A view that joins an already-joined view can repeat a join to the same table. This slows the query and can multiply rows if a join key is not unique.
- When something breaks, the error points to the outermost view. You have to read each definition downward to find the cause.
Keep nesting to one or two levels. For a complicated chain, check the plan with EXPLAIN and decide whether to flatten the views into one definition.
ORDER BY in a view does not guarantee order
A view is a relation, and relations have no inherent order. An ORDER BY in a view definition may be ignored when the outer query joins, groups or filters. SQL Server rejects ORDER BY in a view unless it is paired with TOP or OFFSET. Order in the outer query instead:
SELECT *
FROM employee_directory
ORDER BY name;Not every view accepts writes
A view is automatically updatable only when each row maps to exactly one row in one base table. These features usually break that mapping:
- joins across several tables
DISTINCT,GROUP BY,HAVINGand aggregate functionsUNION,INTERSECTandEXCEPT- window functions
- computed columns, such as
salary / 12inemployee_summary
Trying to write through employee_directory shows the failure:
UPDATE employee_directory SET name = 'Anna' WHERE id = 1;PostgreSQL reports cannot update view "employee_directory" and explains that views that do not select from a single table or view are not automatically updatable. Update the base table directly. If you need writes through a complex view, PostgreSQL offers INSTEAD OF triggers and rules, and Oracle and SQL Server offer INSTEAD OF triggers. Those are advanced tools, so treat them as a last resort.
Two quieter write problems affect views that are updatable.
The first is rows that vanish. A view without WITH CHECK OPTION accepts an update that moves a row out of the view:
CREATE VIEW active_unchecked AS
SELECT id, name, status
FROM employees
WHERE status = 'active';
UPDATE active_unchecked SET status = 'inactive' WHERE id = 1;The update succeeds, and the row is no longer visible through the view. WITH CHECK OPTION prevents this, as shown in the earlier chapter.
The second is hidden required columns. active_unchecked leaves out salary, which is NOT NULL with no default. An insert through the view fails:
INSERT INTO active_unchecked (id, name, status)
VALUES (10, 'Dev', 'active');The error is a not-null violation on salary, even though the statement never mentioned that column. A view that omits a required column cannot be used for inserts unless the column has a default.
The diagram summarizes how to check whether a write is possible.
Views and security have limits
GRANT SELECT ON employee_directory TO analyst works because the view runs with the privileges of its owner, not the caller. This has two consequences:
- If the owner loses access to a base table, the view stops working for everyone.
- A view owned by a powerful role can expose more than you meant if its definition is loose.
PostgreSQL 15 and later lets you reverse this behavior per view:
CREATE VIEW employee_names
WITH (security_invoker = true) AS
SELECT id, name
FROM employees;With security_invoker, the caller needs privileges on employees too. A view that filters rows with WHERE is also not a complete row-level security system. Functions that run before the filter can sometimes leak values from hidden rows. For strict isolation, use the row-level security feature of your database and use views for convenience.
Performance does not come for free
A plain view stores no data and no cache. Every query re-runs the underlying query. Most simple views are merged into the outer query, so the optimizer can use indexes on the base tables. Merging often fails when the view contains DISTINCT, aggregates, window functions or LIMIT. In those cases the optimizer may compute the whole view first and filter afterward. A query like SELECT * FROM v WHERE id = 5 can then scan an entire table. Check with EXPLAIN before assuming the filter is pushed down.
Materialized views fix repeated cost by storing results, and they add their own problems:
- The data is stale until you refresh it.
- A plain
REFRESH MATERIALIZED VIEWblocks readers in PostgreSQL.REFRESH MATERIALIZED VIEW CONCURRENTLYavoids this, and it requires a unique index on the materialized view. - The syntax and availability differ by system. MySQL has no materialized views, and SQL Server uses indexed views.
Find the problem in the catalog
When a view behaves strangely, read its definition and its dependencies instead of guessing. In PostgreSQL and MySQL:
SELECT table_name, view_definition
FROM information_schema.views
WHERE table_schema = 'public';
SELECT view_name, table_name
FROM information_schema.view_table_usage
WHERE view_schema = 'public';The first query shows the stored query text, so you can see whether * was expanded and which join type was used. The second lists the tables each view reads. It only includes tables owned by the current role, so it can be incomplete. For a full dependency graph in PostgreSQL, use the system catalogs pg_depend and pg_rewrite.
Pitfall summary
| Pitfall | Symptom | Fix |
|---|---|---|
| Inner join on nullable key | Rows missing from the view | Use `LEFT JOIN` where needed |
| `SELECT *` in definition | New columns do not appear | List columns explicitly |
| `CREATE OR REPLACE` with new column order | Error about column names or types | Append new columns, or drop and recreate |
| Dependent views | `DROP` refused, or `CASCADE` removes more than expected | Inspect dependencies first |
| `ORDER BY` in definition | Order not guaranteed | Order in the outer query |
| Non-updatable view | Write rejected | Write the base table or use `INSTEAD OF` |
| Missing `WITH CHECK OPTION` | Updated rows vanish from the view | Add the option |
| Omitted `NOT NULL` column | Insert fails on a column you never named | Include the column or give it a default |
| Owner privileges | Breakage when owner loses access | Use `security_invoker` where available |
Exercise
A view is defined as CREATE VIEW staff AS SELECT * FROM employees;. A week later someone adds a bonus column to employees, and a query against staff does not return it. Why, and what should the view definition have looked like?
Show answer
In PostgreSQL and MySQL, * is expanded into a fixed column list when the view is created, so later table columns are not added. The definition should list the columns explicitly, for example SELECT id, name, email, salary, status, department_id FROM employees. To include bonus now, replace the view with a definition that lists it. In PostgreSQL, appending the new column at the end allows CREATE OR REPLACE VIEW.
Exercise
You create CREATE VIEW high_paid AS SELECT id, name, status FROM employees WHERE salary > 5000; and then run INSERT INTO high_paid (id, name, status) VALUES (20, 'Eli', 'active');. The insert fails. Name two reasons it would fail or misbehave, and explain how to correct each.
Show answer
First, salary is NOT NULL with no default, and the view does not include it, so the insert fails with a not-null violation. Include salary in the view, or give the column a default. Second, even if salary were included, the view has no WITH CHECK OPTION, so a row with a salary of 5000 or less would be accepted but would not be visible through the view. Add WITH CHECK OPTION so such inserts are rejected.