…
…
SQL and Database Fundamentals · Lesson 38 / 41 · Transactions and views
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Student Affairs at Northbridge University wants the same report every week: how many seats each section has, how many students enrolled, and which sections are over capacity. The report is a long query that joins four tables, and every week someone rewrites it. You want to write the query once, save it under a name, and then use it like a table.
In this unit you added rows to tables (lesson 34), updated them (35), deleted them (36), and grouped changes that belong together into one transaction (37). All of that was about the data itself. This lesson is about how we look at the data: instead of rewriting a frequently asked question every time, you will save it in the database.
By the end of the lesson, the weekly report will shrink to a one-line query:
OutputSELECT * FROM section_fill WHERE enrolled > capacity;This query will return three rows: sections 47, 48, and 49, which are over capacity. Four tables and a grouping sit behind it, but the person who asks for the report will not need to know that.
In this lesson you will:
CREATE VIEW, then filter and join it like a table.Here is something that happens in a term review meeting. The dean's office report says "1 section is over capacity." The Student Affairs report says "3 sections." Both teams wrote their own query, and both queries run. Half of the meeting goes to arguing about which number is right.
When the queries are put side by side, the difference shows up: the dean's query has the line WHERE t.name = '2026-Fall', so it looks at one term only and finds only section 48. The Student Affairs query looks at all terms and finds 47, 48, and 49. Both say "over-capacity section," but they do not mean the same thing. The real problem is not that one query is wrong. The same business rule was written in two places in two different ways.
The solution is to write the rule once, store it under a name, and let everyone use that name. If someone needs a single term, they add that filter in their own query. The answer to "what does over capacity mean?" stays in one place. This named query is called a view.
A view is defined with CREATE VIEW name AS, followed by an ordinary SELECT. After that, you use the name like a table name in FROM: you filter it, sort it, and join it with other tables.
Example 1 (case): Students per department
CREATE VIEW department_count AS SELECT d.name, COUNT(s.id) AS students FROM department d LEFT JOIN student s ON s.department_id = d.id GROUP BY d.name; SELECT * FROM department_count WHERE students > 15 ORDER BY students DESC;
| name | students |
|---|---|
| Business Administration | 24 |
| Psychology | 23 |
| Software Engineering | 20 |
| Management Information Systems | 17 |
The first command returns no rows; it only saves the query under the name department_count. The second query reads the view like a table. Because of the LEFT JOIN, all 8 departments are in the view; Data Science and Analytics has no students yet and sits at 0, but WHERE students > 15 filters it out.
The same code is ready in the cell below. Run it, then try two tasks:
1. Change 15 to 20. How many departments are left?
2. Change the last query to join the view with the department table and bring the faculty too: FROM department_count s JOIN department d ON d.name = s.name.
Try it now· not graded; doesn't affect progress
A view is similar to the CTE from lesson 23: both give a query a name. The difference is how long they live. A CTE lives only as long as the query it is written in; when the query ends, the name is gone. A view stays in the database, is still there tomorrow, and anyone who connects to the database can use it. Use a CTE to split up a long one-time query, and a view for a question that everyone will ask again and again.
Now the weekly report itself. It has the section number, the course code, the term, the capacity, and the enrollment count. The enrollment table is attached with a LEFT JOIN so that sections with no enrollments also appear, with 0.
Example 2 (case): The section-fill view
CREATE VIEW section_fill AS SELECT o.id, c.code, t.name AS term, o.capacity, COUNT(e.id) AS enrolled FROM course_offering o JOIN course c ON c.id = o.course_id JOIN term t ON t.id = o.term_id LEFT JOIN enrollment e ON e.offering_id = o.id GROUP BY o.id, c.code, t.name, o.capacity; SELECT * FROM section_fill WHERE enrolled > capacity ORDER BY id;
| id | code | term | capacity | enrolled |
|---|---|---|---|---|
| 47 | GEN101 | 2025-Fall | 50 | 77 |
| 48 | GEN101 | 2026-Fall | 40 | 79 |
| 49 | GEN102 | 2026-Spring | 30 | 41 |
All 54 sections are in the view; the filter kept the three over-capacity ones. Now Student Affairs moves section 48 to a bigger room and raises its capacity to 80. If you run the same query again without touching the view, what do you see?
After section_fill is defined, UPDATE course_offering SET capacity = 80 WHERE id = 48; runs. Then how many rows does SELECT * FROM section_fill WHERE enrolled > capacity; return?
Example 3 (case): A view is always up to date
UPDATE course_offering SET capacity = 80 WHERE id = 48; SELECT * FROM section_fill WHERE enrolled > capacity ORDER BY id;
| id | code | term | capacity | enrolled |
|---|---|---|---|---|
| 47 | GEN101 | 2025-Fall | 50 | 77 |
| 49 | GEN102 | 2026-Spring | 30 | 41 |
We never touched the view; when the table changed, the result of the view changed too. You can picture this as a window: you look outside through the window, but you do not copy the scenery. If something outside changes, you see the changed scene through the window. The idea that "a view is a copy of the data from the moment it was defined" is common but wrong. This is why you do not need to do anything extra to keep a view up to date, and why a view and its tables never drift apart.
Because a view is used like a table, the table rule applies to it too: there cannot be two columns with the same name. This is easy to miss when you write a join, because many tables have a column called name. Look at this definition, which puts the course name and the department name side by side:
Does this view definition work?
CREATE VIEW course_department AS SELECT c.name, d.name FROM course c JOIN department d ON d.id = c.department_id;
The error message is:
OutputCREATE VIEW course_department AS SELECT c.name, d.name FROM course c JOIN department d ON d.id = c.department_id;
ERROR: column "name" specified more than onceThe fix is a familiar tool from lesson 3: the alias. If you write SELECT c.name, d.name AS department, the view's columns become name and department and the definition is accepted. The alias is not decoration here; it is required. Column names are what the person using the view will see, so it also matters to choose meaningful ones.
Requests change. Next to the department count, you now want to see the faculty too. To change a view's definition, you use CREATE OR REPLACE VIEW: you write a new definition under the same name and it replaces the old one. PostgreSQL is strict here. The first attempt:
OutputCREATE OR REPLACE VIEW department_count AS
SELECT d.faculty, d.name, COUNT(s.id) AS students
FROM department d
LEFT JOIN student s ON s.department_id = d.id
GROUP BY d.faculty, d.name;
ERROR: cannot change name of view column "name" to "faculty"What does the message say? The first column of the old view was name; in the new definition, faculty is first. PostgreSQL reads this as "changing the name of the first column" and does not allow it. The rule is this: CREATE OR REPLACE must keep the existing columns with the same name, the same type, and the same order; it can only add new columns at the end. Why so strict? Because other queries and reports use the view, and if the first column quietly became something else overnight, they would break without any warning.
There are two correct ways. The first is to put the new column at the end: the definition SELECT d.name, COUNT(s.id) AS students, d.faculty ... is accepted, and the view's columns become name, students, faculty. The second, if you really want to rearrange the columns, is to drop the view first with DROP VIEW department_count; and then create it again with CREATE VIEW. The second way is freer, but the queries that use the view must be reviewed too.
Do not be afraid of dropping a view. DROP VIEW department_count; deletes only the saved query; it does not touch the tables behind it. After the drop, SELECT COUNT(*) FROM student; still returns 120. Do not confuse it with DROP TABLE from lesson 33: that destroys the table and the data in it, while DROP VIEW only removes the window, and the scenery stays where it is.
One more question remains: can you change data through a view? For simple views that come from a single table and contain no grouping or joins, yes. PostgreSQL passes an UPDATE written against such a view on to the table behind it.
Example 4 (case): Updating through a view
CREATE VIEW fourth_year AS SELECT id, student_no, first_name, last_name, email FROM student WHERE year = 4; UPDATE fourth_year SET email = 'camila.osei@northbridge.example' WHERE student_no = '202302001'; SELECT student_no, email FROM student WHERE student_no = '202302001';
| student_no | |
|---|---|
| 202302001 | camila.osei@northbridge.example |
The fourth_year view shows the 21 fourth-year students; the update was written to the view, but the table that changed was student. If you try the same thing on a grouped view, UPDATE department_count SET students = 0 WHERE name = 'Business Administration'; fails with cannot update view "department_count". The reason is simple: the students column is a count of 24 rows; setting it to 0 would mean changing which rows? PostgreSQL cannot know, so it refuses. This answers the mistaken belief that "you can write through every view": you can only do it when each view row matches exactly one row in a table.
Match each operation with its result in the case database.
For each row, pick its match from the list, then check.
CREATE OR REPLACECREATE OR REPLACEDROP VIEW department_count;UPDATE through the grouped department_count viewUPDATE through the single-table, ungrouped fourth_year viewWhat a view gives you is organization, not speed. Reading from a regular view does the same work as writing the SELECT behind it directly: PostgreSQL merges the view's definition with your query and reads the tables again. "A view makes queries faster" is a common mistake; a regular view neither speeds a query up nor noticeably slows it down.
Sometimes, though, a query is very heavy, its result is opened hundreds of times a day, and it does not need to be fresh every second. A materialized view is made for this. CREATE MATERIALIZED VIEW really stores the result of the query; reading it is as fast as reading a ready-made table. The price is freshness: it does not update by itself when the tables change. To update it, you run REFRESH MATERIALIZED VIEW name;. To continue the window picture, this is a photograph: it shows the moment it was taken, and even if the scenery changes, the photograph stays the same until you take a new one.
The Data Science and Analytics department (id 8) has no students yet. Let's build a department summary as a materialized view, and then add a student to this department:
department_summary is created as a materialized view, and then a student is added to department 8. Without a REFRESH, what does SELECT * FROM department_summary WHERE department_id = 8; return?
CREATE MATERIALIZED VIEW department_summary AS SELECT department_id, COUNT(*) AS students FROM student GROUP BY department_id; INSERT INTO student (student_no, first_name, last_name, department_id, year, enrollment_date) VALUES ('202608001', 'Sam', 'Reyes', 8, 1, DATE '2026-09-10');
Example 5 (case): Refreshing with REFRESH
CREATE MATERIALIZED VIEW department_summary AS SELECT department_id, COUNT(*) AS students FROM student GROUP BY department_id; INSERT INTO student (student_no, first_name, last_name, department_id, year, enrollment_date) VALUES ('202608001', 'Sam', 'Reyes', 8, 1, DATE '2026-09-10'); REFRESH MATERIALIZED VIEW department_summary; SELECT department_id, students FROM department_summary WHERE department_id = 8;
| department_id | students |
|---|---|
| 8 | 1 |
Without the REFRESH line, the last query returns no rows; after the refresh, department 8 appears with 1 student. One question decides which to choose: must the person reading this report see the latest change immediately? If Student Affairs must see a section in the fill report the moment it is closed, use a regular view. If the president's dashboard only needs to be computed once a night and is opened hundreds of times during the day, use a materialized view and one REFRESH every night. When you meet a summary that looks inconsistent, your first question should be: when was this summary last refreshed?
Now a new request comes in: advisors want to see a transcript for each student: student, department, course, term, and letter grade. That is a query joining five tables. It is tempting to start by writing CREATE VIEW directly, but that makes debugging harder: if the definition is rejected or the numbers do not match, you cannot tell whether the problem is in the query or in the view. The safe order is to make sure the query works correctly on its own first.
Put the steps in the correct order when writing the student transcript view.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Views do the same job in every database. A small café keeps its sales in one table, and the owner asks the same question every evening: how many items did we sell today, and what is the revenue? If we write the question as a view once, a one-line query is enough each evening.
Example 6 (outside the case): Daily revenue
CREATE TABLE sale (id INTEGER PRIMARY KEY, sale_date DATE NOT NULL, item VARCHAR(20) NOT NULL, amount NUMERIC(5,2) NOT NULL); INSERT INTO sale VALUES (1, '2026-11-03', 'Latte', 4.25), (2, '2026-11-03', 'Tea', 1.25), (3, '2026-11-03', 'Toast', 3.50), (4, '2026-11-04', 'Latte', 4.25), (5, '2026-11-04', 'Cookie', 2.00); CREATE VIEW daily_revenue AS SELECT sale_date, COUNT(*) AS items, SUM(amount) AS revenue FROM sale GROUP BY sale_date; INSERT INTO sale VALUES (6, '2026-11-03', 'Cookie', 2.00); SELECT * FROM daily_revenue ORDER BY sale_date;
| sale_date | items | revenue |
|---|---|---|
| 2026-11-03 | 4 | 11.00 |
| 2026-11-04 | 2 | 6.25 |
Without the last INSERT, the November 3 row would show 3 items and $9.00. The sale added after the view was defined was counted too, because the view reads the sale table again on every query. Try it yourself: run the cell, then delete the last INSERT line, run it again, and see the difference in the November 3 row.
Try it now· not graded; doesn't affect progress
Views have one more use: instead of the whole table, a user can be given a view that shows only some columns. For example, a view can show students' names and departments while hiding birth dates and GPAs. You will set this up together with permissions in lesson 40.
A view joins like a table. department_count does not carry faculty information; joining it with the department table on the name brings it in.
SELECT s.name, d.faculty, s.students FROM department_count s JOIN department d ON d.name = s.name WHERE s.students > 20 ORDER BY s.students DESC;
| name | faculty | students |
|---|---|---|
| Business Administration | Faculty of Business and Management | 24 |
| Psychology | Faculty of Humanities and Social Sciences | 23 |
The join works on the name because department.name is unique (UNIQUE). If the view also had a d.id column, joining on the key would be more robust.
REPLACE department_count d.name, (s.id) students, d.faculty department d student s s.department_id = d.id d.faculty, d.name; * department_count faculty = name;
Thinking that a view copies the data. A regular view stores no data, only the text of the query: when you change a table, the view changes too (once section 48's capacity is 80, the over-capacity sections drop from 3 to 2), and dropping a view does not delete data (after DROP VIEW, the student count is still 120). The reverse should not be forgotten either: a materialized view really does store the data and stays old until it is refreshed with REFRESH. When a summary looks inconsistent, first ask: "when was it last refreshed?"
CREATE VIEW name AS SELECT ...): you filter and join it like a table, it keeps a business rule in one place, and its column names must be unique.CREATE OR REPLACE can only add columns at the end, and a bigger change needs DROP VIEW and a new CREATE; DROP VIEW does not touch the data, and writing through a view works only for single-table, ungrouped views.REFRESH MATERIALIZED VIEW runs; use a regular view when you need instant freshness, and a materialized view for a heavy summary that changes rarely.Next lesson: A view does not give speed; the tool that speeds up queries is the index, and in lesson 39 you will choose which index a query needs. You will see how to limit access with a view in lesson 40.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
| name | students | faculty |
|---|---|---|
| Data Science and Analytics | 0 | Faculty of Engineering |
| Industrial Engineering | 12 | Faculty of Engineering |
| Software Engineering | 20 | Faculty of Engineering |
name and students stayed in place and faculty was added at the end, so CREATE OR REPLACE was accepted. Queries that use the view in its old form (SELECT name, students FROM department_count) are not affected at all.