SQL · Module 13 · Lesson 12 min read

Views & Materialized Views

View – a saved query

SQL
CREATE VIEW monthly_spending AS
SELECT user_id, date_trunc('month', spent_on) AS month, sum(amount) AS total
FROM expenses GROUP BY 1, 2;

SELECT * FROM monthly_spending WHERE user_id = 1;
  • Stores only the query, not the data — every SELECT runs it fresh (always up to date)
  • CREATE OR REPLACE VIEW to change it (you can add columns, not remove/rename them); DROP VIEW

Why use views?

  • Simplify complex joins and calculations for the app or analysts
  • Consistency: business logic defined once ("active expense = not deleted")
  • Security: expose only some columns/rows (hide emails, hide deleted rows)
  • Stable interface: change underlying tables without breaking queries

Updatable views

Simple views (one table, no GROUP BY/DISTINCT/aggregates) accept INSERT/UPDATE/DELETE. WITH CHECK OPTION blocks writes that would fall outside the view.

Security note (Supabase)

Views run with the owner's permissions by default, which can bypass Row Level Security. In PostgreSQL 15+ use WITH (security_invoker = true) so RLS applies to the caller.

Materialized view – a saved RESULT

SQL
CREATE MATERIALIZED VIEW category_totals AS SELECT …;
REFRESH MATERIALIZED VIEW category_totals;
  • Stores the data physically → very fast reads (and you can index it)
  • ❌ Becomes stale until refreshed
  • REFRESH MATERIALIZED VIEW CONCURRENTLY – readers aren't blocked (needs a UNIQUE index)
  • Refresh on a schedule (pg_cron, Supabase cron) or after data loads

View vs materialized view vs table

ViewMaterialized viewTable
Stores data❌✅✅
Always current✅❌ (refresh)you maintain it
Read speedsame as the queryfastfast
Good forlogic, securityheavy reports, dashboardssource data

Example

SQL
-- A view hiding soft-deleted rows and joining names
ALTER TABLE expenses ADD COLUMN deleted_at TIMESTAMPTZ;
UPDATE expenses SET deleted_at = now() WHERE title = 'Movie tickets';

CREATE VIEW expense_details AS
SELECT e.id, u.name AS user_name, c.name AS category, e.title, e.amount, e.spent_on
FROM expenses e
JOIN users u ON u.id = e.user_id
LEFT JOIN categories c ON c.id = e.category_id
WHERE e.deleted_at IS NULL;

SELECT user_name, category, title, amount FROM expense_details
WHERE user_name = 'Asha Sharma' AND spent_on >= '2026-11-01';
-- Monthly groceries, Bus pass (Movie tickets is hidden)

-- A "public" view that hides private columns
CREATE VIEW public_profiles WITH (security_invoker = true) AS
SELECT id, split_part(name, ' ', 1) AS first_name, city FROM users;
SELECT * FROM public_profiles LIMIT 3;

-- Updatable view WITH CHECK OPTION
CREATE VIEW unpaid_bills AS SELECT * FROM bills WHERE NOT paid WITH CHECK OPTION;
UPDATE unpaid_bills SET amount = 1600 WHERE title = 'Internet';      -- ✅ allowed
-- INSERT INTO unpaid_bills (user_id, title, amount, due_date, paid) VALUES (1,'x',1,'2026-12-01',true);
-- ❌ new row violates check option for view "unpaid_bills"

-- Materialized view for a dashboard
CREATE MATERIALIZED VIEW category_month_totals AS
SELECT c.name AS category, date_trunc('month', e.spent_on)::date AS month, sum(e.amount) AS total
FROM expenses e JOIN categories c ON c.id = e.category_id
GROUP BY 1, 2;
CREATE UNIQUE INDEX ON category_month_totals (category, month);

SELECT * FROM category_month_totals WHERE category = 'Groceries' ORDER BY month;

-- New data isn't visible until a refresh
INSERT INTO expenses (user_id, category_id, title, amount, spent_on) VALUES (4, 7, 'Rice sack', 3000, '2026-11-20');
SELECT total FROM category_month_totals WHERE category = 'Groceries' AND month = '2026-11-01';  -- 8100.00 (stale)
REFRESH MATERIALIZED VIEW CONCURRENTLY category_month_totals;
SELECT total FROM category_month_totals WHERE category = 'Groceries' AND month = '2026-11-01';  -- 11100.00