Skip to main content
PostgreSQL
CHAPTER 17 Intermediate

Views and Materialized Views

Updated: May 16, 2026
7 min read

# CHAPTER 17

Views and Materialized Views

1. Introduction

In Chapter 16, we wrote a massive, 4-table INNER JOIN query to generate an E-Commerce Sales Report. What happens if the Marketing team needs to run that report every single day? You don't want them typing out 15 lines of complex SQL logic every morning. What if they make a typo? Instead, we can take that massive query and save it permanently inside PostgreSQL as a View. In this chapter, we will learn how to abstract complex architectures into simple virtual tables, and use Materialized Views to turbocharge performance.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the concept of Database Abstraction.
  • Use CREATE VIEW to save complex queries as virtual tables.
  • Query a View just like a normal table.
  • Understand the performance differences between Standard Views and Materialized Views.
  • Create and refresh Materialized Views.

3. Creating a Standard View

A View is essentially a saved SQL query. When you create a View, PostgreSQL does not save the actual data; it just saves the instructions on how to fetch the data.

Let's save our complex joining logic:

sql
123456789101112
CREATE VIEW active_sales_report AS
SELECT 
    u.first_name, 
    u.email, 
    p.product_name, 
    o.order_date, 
    oi.quantity
FROM users u
JOIN orders o ON u.id = o.user_id
JOIN order_items oi ON o.id = oi.order_id
JOIN products p ON oi.product_id = p.id
WHERE o.status = 'Completed';

4. Querying a View

Now that the View is created, the Marketing team never has to write a JOIN again. They can simply query the View exactly as if it were a physical table!
sql
123
-- The complex logic is completely hidden!
SELECT * FROM active_sales_report 
WHERE order_date = CURRENT_DATE;

*(Every time you run this SELECT, PostgreSQL secretly unpacks the View and runs the massive 4-table join behind the scenes).*

5. Security Benefits of Views

Views are incredible for security. Suppose your employees table contains names, emails, AND Social Security Numbers (SSNs). You want the HR interns to be able to see names and emails, but you absolutely cannot let them see the SSNs.

You do NOT give the interns access to the employees table. Instead, you create a View:

sql
123
CREATE VIEW public_employee_directory AS
SELECT first_name, last_name, email, department 
FROM employees;

You give the interns access to publicemployeedirectory. They can query it all day long, but it is physically impossible for them to access the SSN column!

6. The Problem with Standard Views

Because a standard View does not store data on the hard drive (it just saves the query instructions), every time you query activesalesreport, PostgreSQL has to re-calculate the massive 4-table join. If your database has 50 million orders, running SELECT * FROM activesalesreport will still take 5 seconds to load.

7. Materialized Views (The Performance Turbocharger)

PostgreSQL offers a massive performance upgrade called a Materialized View. Unlike a standard View, a Materialized View physically executes the query and saves the resulting data onto the hard drive as a real, physical table.
sql
1234567
CREATE MATERIALIZED VIEW monthly_financial_summary AS
SELECT 
    category, 
    SUM(price * quantity) AS total_revenue
FROM orders 
JOIN products...
GROUP BY category;

*(Because the data is pre-calculated and saved, querying monthlyfinancialsummary takes 1 millisecond, even if the underlying tables have 50 million rows!)*

8. Refreshing Materialized Views

Because a Materialized View is a physical snapshot of the data, it goes out of date. If a customer places a new order 5 minutes after you create the Materialized View, that new order will NOT be in the View. You must manually tell PostgreSQL to update the snapshot:
sql
12
-- Run this every night at 2:00 AM using a cron job
REFRESH MATERIALIZED VIEW monthly_financial_summary;

9. Common Mistakes

  • Trying to INSERT into a View: In most cases, Views are Read-Only. If you try to run INSERT INTO activesalesreport..., PostgreSQL will throw an error because the "table" is just a virtual projection of 4 different tables.
  • Overusing Materialized Views: Do not use Materialized Views for data that must be accurate up to the exact second (like a user's bank account balance). Only use them for historical reporting where a 24-hour delay is acceptable.

10. Best Practices

  • Use CONCURRENTLY: When you run REFRESH MATERIALIZED VIEW, PostgreSQL completely locks the table, preventing anyone from reading it while it rebuilds. If you create a UNIQUE INDEX on the view, you can use REFRESH MATERIALIZED VIEW CONCURRENTLY. This rebuilds the data in the background without locking the table!

11. Exercises

  1. 1. Write the SQL to create a standard View named bannedusers that only selects users where isbanned = TRUE.
  1. 2. Why does querying a standard View on a massive dataset still result in slow performance?

12. SQL Challenges

Write the SQL command to destroy a Materialized View named oldyearlyreport.
sql
1
DROP MATERIALIZED VIEW IF EXISTS old_yearly_report;

13. MCQ Quiz with Answers

Question 1

What is the fundamental difference between a standard View and a Materialized View in PostgreSQL?

Question 2

How is a standard View commonly used to enhance database security?

14. Interview Questions

  • Q: Describe a business reporting scenario where you would strongly advocate for creating a Materialized View instead of a standard View.
  • Q: Explain the mechanical limitations of a Materialized View. How do you handle the problem of data staleness?

15. FAQs

Q: Can I update the definition of a View without dropping it? A: Yes! You can use CREATE OR REPLACE VIEW my_view AS SELECT... to modify the underlying query without having to DROP the view first.

16. Summary

Views provide an elegant layer of abstraction over your database architecture. By saving complex JOIN logic as standard Views, you simplify daily operations and enhance security. By deploying Materialized Views, you can pre-compute massive analytical datasets, trading a slight delay in data freshness for absolutely massive performance gains.

17. Next Chapter Recommendation

Materialized Views are great for daily reports, but what if a user is searching the live users table for an email address, and it's taking 3 seconds to find it? We can't use a materialized view for real-time live data. In Chapter 18: Indexing and Query Optimization, we will learn the ultimate performance secret of relational databases: B-Tree Indexes.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·