Views

Updated · 9 min read
mediumPostgreSQL 18sqlviewsmaterialized-viewcreate-viewinterview

A view is a saved query with a name, which you can then select from as if it were a table. "Each student's total paid" takes a left join, a GROUP BY and a coalesce. Written once as a view called student_balances, it becomes SELECT * FROM student_balances, for everyone, every time. A view stores no rows: each time you query it, it runs its query on the current data, so it's never out of date. This lesson covers creating, changing and dropping views, what they're good for, when you can update through one, and materialized views, which do store their rows.

In One Minute

  • CREATE VIEW name AS SELECT ... saves a query under a name.
  • Querying a view runs its query on current data; the view itself stores nothing.
  • CREATE OR REPLACE VIEW changes the query; DROP VIEW removes it.
  • Simple views on one table can be updated through; views with GROUP BY or joins can't, by default.
  • A materialized view stores its result and must be refreshed to see new data.

Creating a View

SQL
CREATE VIEW view_name AS
SELECT ...;

Each student's total paid, as a view:

SQL▶ Try it
CREATE VIEW student_balances AS
SELECT s.student_id, s.first_name,
       coalesce(sum(p.amount_usd), 0.00) AS total_paid
FROM students AS s
LEFT JOIN payments AS p ON p.student_id = s.student_id
GROUP BY s.student_id, s.first_name;
 
SELECT * FROM student_balances ORDER BY student_id;
Output
CREATE VIEW
 
 student_id | first_name | total_paid
------------+------------+------------
        101 | Srihitha   |    1700.00
        102 | Advitha    |       0.00
        103 | Navika     |     450.00
(3 rows)

From now on, the join and grouping are hidden behind a name. You can filter, sort and join a view like any table:

SQL▶ Try it
CREATE VIEW student_balances AS
SELECT s.student_id, s.first_name, coalesce(sum(p.amount_usd), 0.00) AS total_paid
FROM students AS s LEFT JOIN payments AS p ON p.student_id = s.student_id
GROUP BY s.student_id, s.first_name;
 
SELECT * FROM student_balances
WHERE total_paid > 400
ORDER BY student_id;
Output
CREATE VIEW
 
 student_id | first_name | total_paid
------------+------------+------------
        101 | Srihitha   |    1700.00
        103 | Navika     |     450.00
(2 rows)

Always Up to Date

A view runs its query each time, so it always reflects the current data. Record Advitha's first payment, then ask the view again:

SQL▶ Try it
CREATE VIEW student_balances AS
SELECT s.student_id, s.first_name, coalesce(sum(p.amount_usd), 0.00) AS total_paid
FROM students AS s LEFT JOIN payments AS p ON p.student_id = s.student_id
GROUP BY s.student_id, s.first_name;
 
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (102, 1, 450.00, '2026-01-05', '2026-01-05', 'card');
 
SELECT * FROM student_balances ORDER BY student_id;
Output
CREATE VIEW
 
INSERT 0 1
 
 student_id | first_name | total_paid
------------+------------+------------
        101 | Srihitha   |    1700.00
        102 | Advitha    |     450.00
        103 | Navika     |     450.00
(3 rows)

Advitha's total went from 0.00 to 450.00 with no change to the view. That's the difference from CREATE TABLE AS, which saves a snapshot.

SELECT FROM student_balances runs the saved join and GROUP BY on today's payments

Why Use Views

Views give people a simple, safe interface to complicated or sensitive data:

  • Simplicity. Analysts select from student_balances without knowing about left joins or coalesce.
  • One definition. Everyone's "total paid" is computed the same way, so reports agree.
  • Security. A view can show some columns and hide others, such as names without emails or phones, and you can grant access to the view but not the table, as Users, Roles and Privileges shows.
  • Stable names. If the tables underneath are reorganized, the view can be rewritten to keep returning the same columns, and queries that use it keep working.

Changing and Removing a View

CREATE OR REPLACE VIEW changes a view's query, as long as the existing columns keep their names, order and types; new columns can be added at the end:

SQL▶ Try it
CREATE VIEW student_balances AS
SELECT s.student_id, s.first_name, coalesce(sum(p.amount_usd), 0.00) AS total_paid
FROM students AS s LEFT JOIN payments AS p ON p.student_id = s.student_id
GROUP BY s.student_id, s.first_name;
 
CREATE OR REPLACE VIEW student_balances AS
SELECT s.student_id, s.first_name,
       coalesce(sum(p.amount_usd), 0.00) AS total_paid,
       count(p.payment_id) AS payments
FROM students AS s
LEFT JOIN payments AS p ON p.student_id = s.student_id
GROUP BY s.student_id, s.first_name;
 
SELECT * FROM student_balances ORDER BY student_id;
Output
CREATE VIEW
 
CREATE VIEW
 
 student_id | first_name | total_paid | payments
------------+------------+------------+----------
        101 | Srihitha   |    1700.00 |        5
        102 | Advitha    |       0.00 |        0
        103 | Navika     |     450.00 |        2
(3 rows)

Removing a column that way fails with cannot drop columns from view; drop and recreate the view instead. ALTER VIEW student_balances RENAME TO student_totals renames it, and DROP VIEW student_balances removes it, leaving the tables untouched. A view also protects its tables: ALTER TABLE payments DROP COLUMN amount_usd is refused while student_balances uses that column. SQL Server writes CREATE OR ALTER VIEW; MySQL supports CREATE OR REPLACE VIEW too.

Updating Through a View

A simple view on one table, without grouping or joins, can be updated, and the change goes into the table:

SQL▶ Try it
CREATE VIEW card_payments AS
SELECT payment_id, student_id, amount_usd, method
FROM payments
WHERE method = 'card';
 
UPDATE card_payments SET amount_usd = 451.00 WHERE payment_id = 1;
 
SELECT payment_id, amount_usd FROM payments WHERE payment_id = 1;
Output
CREATE VIEW
 
UPDATE 1
 
 payment_id | amount_usd
------------+------------
          1 |     451.00
(1 row)

The update went through the view into payments. A view with GROUP BY, aggregates, DISTINCT or joins of several tables can't be updated automatically, because there's no single row to change:

SQL▶ Try it
CREATE VIEW student_balances AS
SELECT s.student_id, s.first_name, coalesce(sum(p.amount_usd), 0.00) AS total_paid
FROM students AS s LEFT JOIN payments AS p ON p.student_id = s.student_id
GROUP BY s.student_id, s.first_name;
 
UPDATE student_balances SET total_paid = 0 WHERE student_id = 101;
Output
CREATE VIEW
 
ERROR:  cannot update view "student_balances"
DETAIL:  Views containing GROUP BY are not automatically updatable.
HINT:  To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.

Add WITH CHECK OPTION to a filtered view, and inserts or updates through it must still match its WHERE: inserting a 'check' payment through card_payments is then refused.

card_payments maps each row to one payments row, so it's updatable; student_balances groups rows, so it isn't

Materialized Views

A materialized view stores its query's result, like a table, and only changes when you refresh it. It's for expensive queries that are read often and don't need to be up to the second, such as a dashboard's monthly totals:

SQL▶ Try it
CREATE MATERIALIZED VIEW monthly_totals AS
SELECT date_trunc('month', paid_on)::date AS month, sum(amount_usd) AS total
FROM payments
GROUP BY 1;
 
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (103, 5, 25.00, '2026-01-05', '2026-01-05', 'card');
 
SELECT * FROM monthly_totals WHERE month = '2026-01-01';
 
REFRESH MATERIALIZED VIEW monthly_totals;
 
SELECT * FROM monthly_totals WHERE month = '2026-01-01';
Output
SELECT 5
 
INSERT 0 1
 
   month    | total
------------+--------
 2026-01-01 | 200.00
(1 row)
 
REFRESH MATERIALIZED VIEW
 
   month    | total
------------+--------
 2026-01-01 | 225.00
(1 row)

Before the refresh, January still showed $200.00, missing the new $25.00 payment; after REFRESH, it shows $225.00. Reading a materialized view is fast, because nothing is recomputed, but its data is only as fresh as the last refresh. Materialized views are PostgreSQL and Oracle features; SQL Server has indexed views, and MySQL has none.

A view reruns its query every time; a materialized view stores rows and shows new data only after REFRESH

Common Mistakes

Expecting a view to be faster. A plain view runs its query every time; it's a name, not a cache.

Forgetting to refresh a materialized view. It shows old data until refreshed.

Removing columns with CREATE OR REPLACE. It can only add columns at the end. Drop and recreate.

Updating through a grouped view. It can't be done automatically. Update the underlying table.

Interview Corner

What is a view?

A named, saved query. Selecting from it runs the query on the current data; the view itself stores no rows.

What's the difference between a view and a materialized view?

A view reruns its query every time, so it's always current. A materialized view stores the result for fast reads and must be refreshed to see changes.

Can you update data through a view?

Yes, for simple views on one table without aggregates, DISTINCT or GROUP BY; the change goes to the underlying table. More complex views need INSTEAD OF triggers.

Practice

Challenge: Create a view late_payments showing payment_id, student_id and days_late (paid_on - due_on) for payments made after their due date. Then select from it, sorted by payment_id.

Show solution
SQL▶ Try it
CREATE VIEW late_payments AS
SELECT payment_id, student_id, paid_on - due_on AS days_late
FROM payments
WHERE paid_on > due_on;
 
SELECT * FROM late_payments ORDER BY payment_id;
Output
CREATE VIEW
 
 payment_id | student_id | days_late
------------+------------+-----------
          3 |        101 |         2
          7 |        103 |         4
(2 rows)

Two late payments. Any late payment recorded in the future will appear in the view automatically, with no change to it.

Quick check: Views

3 questions
1A new payment is inserted after student_balances was created. Does the view include it?
2Which view can be updated automatically?
3What must you do for a materialized view to show new data?

Key Takeaways

You want toWrite
Save a queryCREATE VIEW student_balances AS SELECT ...
Change itCREATE OR REPLACE VIEW student_balances AS SELECT ...
Remove itDROP VIEW student_balances;
Store resultsCREATE MATERIALIZED VIEW monthly_totals AS SELECT ...
Update stored resultsREFRESH MATERIALIZED VIEW monthly_totals;

Was this tutorial helpful?

Lesson 59 of 115