Sub topic 1
What a View Is and Why It Exists
Prerequisites
This chapter assumes you can do the following:
- Write
SELECTqueries withWHERE,ORDER BYandGROUP BY. - Combine tables with
JOIN. - Create tables and insert rows with
CREATE TABLEandINSERT. - Describe what database users and privileges are, at a basic level.
The examples use two tables, departments and employees. Later chapters query them through views.
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255),
salary NUMERIC(10, 2) NOT NULL,
status VARCHAR(20) NOT NULL,
department_id INTEGER REFERENCES departments (id)
);The working model
A view is a named query stored in the database. You read from it as you would from a table, but it holds no rows of its own. When you select from a view, the database takes the stored query and runs it against the underlying tables. The tables a view reads from are called base tables.
A view is sometimes called a virtual table. It has columns, and you can filter it, join it and sort it. What it lacks is storage: the data stays in the base tables, and the view is only a definition.
The following diagram shows how a query against a view reaches the data.
View versus base table
The two differ in several ways that matter in practice.
| Aspect | Base table | View |
|---|---|---|
| Stores rows | Yes | No (regular view) |
| Defined by | Column definitions | A `SELECT` statement |
| Reflects current data | It is the data | Yes, at each query |
| Can have its own privileges | Yes | Yes |
| Accepts `INSERT`, `UPDATE`, `DELETE` | Always | Only in some cases |
Because a regular view stores nothing, it can never be out of date. Each time you query it, it reads the current contents of the base tables. Later chapters cover materialized views, which do store their result and can therefore go stale.
Why views exist
Views solve four recurring problems. Each one comes up in real schemas.
Repeating complex queries
Suppose many reports need employees together with their department name. Without a view, every report repeats the same join. With a view, the join is written once and given a name.
CREATE VIEW employee_directory AS
SELECT e.id,
e.name,
d.name AS department
FROM employees e
JOIN departments d ON d.id = e.department_id;
SELECT * FROM employee_directory WHERE department = 'Engineering';The alias department is needed because both tables have a column called name. A view cannot have two columns with the same name.
If the join logic changes later, you fix it in one place. Every query that uses the view picks up the change.
Hiding structure
A view gives callers a stable shape even when the tables underneath change. You can rename a column in a base table and adjust the view to keep presenting the old name. Callers that only use the view keep working. This is a form of abstraction: the view is the interface, and the tables are the implementation.
Restricting access
The employees table holds salary and email. Some users should see names and departments but nothing more. A view can expose only selected columns, and privileges can be granted on the view without granting them on the tables.
GRANT SELECT ON employee_directory TO analyst;After this grant, the analyst role can read employee_directory. The role sees only the three columns the view exposes, not salary or email. The exact rules depend on the database's view security model. Some systems check privileges as the view's owner, and others as the caller. Check your system's documentation before relying on this for protection.
Giving queries readable names
A long query with several joins and calculations is hard to read inside a larger statement. Naming it as a view lets the outer query say what it wants in a few words. This is the same reason you name a function in a program.
What a view does not do
Views are often assumed to do more than they do. Keep these points in mind.
- A regular view does not cache results. It does not make a slow query faster. The database still runs the underlying query each time.
- A view is not a copy of the data. Deleting a view never deletes rows from base tables.
- A view is not always writable. Whether you can insert, update or delete through a view depends on its definition. A later chapter covers the rules.
- A view is not automatically a security boundary. It limits what a caller can select through it, but the protection depends on correct privileges and on how your database evaluates them.
How the database uses the definition
When you run a query against a view, the database combines the stored definition with your query. Most systems expand the view into the outer query, then optimize the whole thing as one statement. The optimizer can then push your WHERE condition down into the view's query and use indexes on the base tables.
For example, this query:
SELECT name FROM employee_directory WHERE department = 'Engineering';is treated roughly as if you had written the join yourself and added the filter:
SELECT e.name
FROM employees e
JOIN departments d ON d.id = e.department_id
WHERE d.name = 'Engineering';The exact plan varies by system. Some views, such as those with certain aggregates or set operations, cannot be expanded this simply, and the database may compute the view's result first. A later chapter covers this in detail.
Common mistakes at this stage
These errors appear often when people first use views.
- Using
SELECT *in the definition. In many systems the column list is fixed when the view is created. Columns added to the base table later do not appear in the view. Naming columns explicitly makes the view's shape clear. - Duplicate column names. A join of two tables that both have
nameoridfails unless you alias the columns. - Assuming the view protects data on its own. A view hides columns only from users who lack access to the base tables. If the user can query
employeesdirectly, the view hides nothing from them. - Forgetting that views depend on tables. Dropping or changing a base table that a view uses can break the view or be blocked by the database. Behavior varies by system.
- Adding an
ORDER BYand relying on it. Ordering inside a view definition is not guaranteed to carry through to queries that use the view. PutORDER BYin the outer query.
Summary of the model
A view is a stored SELECT with a name. It holds no data, it always reflects the current state of its base tables, and it can be read like a table. You use it to avoid repeating queries, to present a stable interface, and to limit what users can see. The next chapters show how to create views, name their columns and manage them.
Exercise
A teammate says "I created a view over a slow join, so our reports should now run faster." Is this correct? Explain what a regular view does and does not change, and name the feature that would store the result.
Show answer
This is not correct. A regular view stores only the query, not the rows. Each time a report selects from the view, the database expands the definition and runs the join against the base tables, so the cost is about the same as writing the join by hand. The view makes the query easier to reuse and read, but not faster. A materialized view stores the result on disk and can make reads fast, but its data stays stale until it is refreshed.
Exercise
The employees table has salary and email columns. You want the role analyst to see each employee's id, name and department name only. Write the statements, and say why the analyst must not also have SELECT on employees.
Show answer
Create the view and grant access on it: CREATE VIEW employee_directory AS SELECT e.id, e.name, d.name AS department FROM employees e JOIN departments d ON d.id = e.department_id; then GRANT SELECT ON employee_directory TO analyst;. If the analyst also had SELECT on employees, they could query salary and email directly, so the view would hide nothing. The view only limits access for users who can reach the data through it alone.