Sub topic 2
Creating and querying your first view
This chapter assumes you can write SELECT queries with WHERE, ORDER BY and GROUP BY, join tables with JOIN, create tables and insert rows, and you know that databases have users with privileges. The examples run on PostgreSQL. Where other systems behave differently, the text says so.
What `CREATE VIEW` does
A view is a named SELECT statement stored in the database. CREATE VIEW does not run the query and does not copy any rows. It saves the query text, parsed into an internal form, in the system catalog. Afterwards you can use the view's name anywhere a table name is allowed in a SELECT.
The basic form is:
CREATE VIEW view_name AS
SELECT ...;The statement after AS can be any SELECT that the database accepts. It can contain joins, filters, aggregates and expressions.
The sample schema
The examples in this tutorial use two tables. Create them and load a few rows.
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)
);
INSERT INTO departments (id, name) VALUES
(1, 'Engineering'),
(2, 'Sales');
INSERT INTO employees (id, name, email, salary, status, department_id) VALUES
(1, 'Ana', '[email protected]', 5000, 'active', 1),
(2, 'Ben', '[email protected]', 4800, 'inactive', 1),
(3, 'Chloe', '[email protected]', 5200, 'active', 2),
(4, 'Dev', '[email protected]', 4100, 'active', NULL);Suppose many reports need each employee's name together with the department name. Without a view, every report repeats the same join.
Your first view
The following view stores that join under one 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;The alias department is required here. Both tables have a column called name, and a view cannot have two columns with the same name. PostgreSQL rejects the definition with an error such as column "name" specified more than once. The next chapter covers other ways to name view columns.
Querying the view
You query the view as if it were a table.
SELECT * FROM employee_directory WHERE department = 'Engineering';With the sample data this returns Ana and Ben. You can use the view with every clause you would use on a table:
SELECT department, COUNT(*) AS headcount
FROM employee_directory
GROUP BY department
ORDER BY headcount DESC;You can also join the view to a table:
SELECT v.name, v.department, e.salary
FROM employee_directory v
JOIN employees e ON e.id = v.id
WHERE e.salary > 5000;The view exposes id precisely so that this kind of join is possible. A view only contains the columns its SELECT list names. The caller cannot reach e.salary or e.email through employee_directory, because the view does not output them.
What happens when you run a query on a view
A regular view holds no data of its own. When you query it, the database substitutes the stored definition into your query and then plans the combined result. The usual term for this is view expansion.
For the first query above, the effect is roughly the same as this:
SELECT e.id, e.name, d.name AS department
FROM employees e
JOIN departments d ON d.id = e.department_id
WHERE d.name = 'Engineering';The WHERE condition on department is pushed down onto d.name, so the planner can use an index on that column, if one exists, as if you had written the join by hand. A view therefore does not make a query faster. It makes the query shorter to write and gives one place to maintain the join logic. The performance chapter returns to this in detail.
Because nothing is stored, the view always reflects the current contents of the base tables. Insert a row into employees and it appears in the view immediately, provided it satisfies the join.
INSERT INTO employees (id, name, email, salary, status, department_id)
VALUES (5, 'Eli', '[email protected]', 4500, 'active', 2);
SELECT * FROM employee_directory WHERE department = 'Sales';This now returns Chloe and Eli.
Edge cases to know from the start
Rows can silently disappear
employee_directory uses an inner JOIN. Dev has department_id = NULL, so Dev never matches a department and does not appear in the view at all.
SELECT COUNT(*) FROM employees; -- 5
SELECT COUNT(*) FROM employee_directory; -- 4If the directory should list every employee, define the view with LEFT JOIN, so that employees without a department show NULL in the department column. Whichever join you choose, the choice is part of what the view means to everyone who uses it.
Filtering on the wrong `name`
In the view, name is the employee's name. The department name is department. A condition like WHERE name = 'Engineering' is valid SQL and returns no rows, because no employee has that name. The database cannot warn you, since the query is legal. When the view's column names differ from the base tables, check which column you are filtering.
You cannot use the original table aliases
The aliases e and d exist only inside the view's definition. This fails:
SELECT e.name FROM employee_directory;PostgreSQL reports missing FROM-clause entry for table "e". Outside the view, only the view's own columns are visible.
`SELECT *` inside a definition is fixed at creation time
If a view is defined as SELECT * FROM employees, PostgreSQL expands the * into the table's column list when you create the view. Columns added to employees later do not appear in the view. Other systems differ on this point. Listing the columns explicitly avoids the question and makes the view's contract clear.
Dependencies between a view and its tables
The view depends on the tables it reads. PostgreSQL refuses DROP TABLE departments while employee_directory exists, unless you add CASCADE, which also drops the view. Renaming a column in a base table normally updates the stored definition, but dropping or changing the type of a column the view uses is rejected. Other systems may instead accept the change and leave the view broken until its next use, so test this before you rely on it.
`ORDER BY` inside a view
You can put ORDER BY in a view definition in PostgreSQL, but it gives no guarantee. A query on the view that adds its own ORDER BY, or uses a join or aggregate, can ignore it. Sort in the outer query, where the caller can see and control the order.
Checking your work
Selecting from the view and comparing it with the underlying query is the simplest test. Run the original SELECT and the same SELECT against the view, and confirm both return the same rows. If the counts differ, look first at the join type and at the filters in the definition.
A quick test of the dependency behavior, on a scratch database only:
DROP TABLE departments;On PostgreSQL this fails with an error saying that the view employee_directory depends on the table. Do not use CASCADE unless you intend to remove the view.
Summary of the working model
| Idea | What it means in practice |
|---|---|
| A view is a stored query | `CREATE VIEW` saves the `SELECT`; no rows are copied |
| Querying expands the definition | The planner merges your query with the stored `SELECT` |
| Output columns come from the `SELECT` list | Duplicate names must be aliased; hidden columns are unreachable |
| Data is always current | Each query reads the base tables as they are now |
| Join type shapes the contents | Inner joins drop unmatched rows, so check for `NULL` keys |
Exercise
Using the sample data, a colleague runs SELECT COUNT(*) FROM employee_directory; and gets 4, while SELECT COUNT(*) FROM employees; returns 5. Why do the counts differ, and how would you change the view so both counts match?
Show answer
Dev has a NULL departmentid, so the inner JOIN in the view finds no matching department and leaves Dev out. Redefine the view with a LEFT JOIN from employees to departments, for example: CREATE OR REPLACE VIEW employeedirectory AS SELECT e.id, e.name, d.name AS department FROM employees e LEFT JOIN departments d ON d.id = e.department_id; Dev then appears with a NULL department and both counts are 5.
Exercise
Write a view named engineering_staff that shows the id and name of every employee in the Engineering department, then write a query on that view that counts its rows. Why is no alias needed for the name column in this view?
Show answer
CREATE VIEW engineeringstaff AS SELECT e.id, e.name FROM employees e JOIN departments d ON d.id = e.departmentid WHERE d.name = 'Engineering'; then SELECT COUNT(*) FROM engineering_staff; returns 2 with the sample data. No alias is needed because only employees.name is in the SELECT list, so the view has no duplicate column names. The department name is used only in the WHERE clause and is not an output column.