0Pricing
PostgreSQL Performance & Query Optimization · 课时

使用物化视图提升性能

了解物化视图如何预先计算复杂查询结果,从而加快报表和分析速度。

使用物化视图提升性能 是 CoddyKit 上的免费 PostgreSQL Performance & Query Optimization 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 PostgreSQL Performance & Query Optimization 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 PostgreSQL Performance & Query Optimization 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What are Materialized Views?

Welcome to the lesson on Materialized Views! These are powerful tools in PostgreSQL for speeding up complex queries.

Think of a Materialized View (MV) as a pre-computed result set of a query that is stored on disk. Unlike a regular view, which runs its query every time you access it, an MV holds the actual data.

Why Use Materialized Views?

Materialized Views are incredibly useful for performance, especially when dealing with:

  • Complex Joins: Queries involving many tables.
  • Aggregations: Calculations like sums, averages, or counts over large datasets.
  • Reporting & Analytics: Dashboards and reports that frequently query the same complex data.

By pre-calculating and storing these results, MVs can drastically reduce query execution time for repeated requests.

Creating Your First MV

You create a Materialized View using the CREATE MATERIALIZED VIEW statement, followed by a SELECT query. The query defines the data that will be stored in your MV.

Let's create a simple Materialized View to see the average price per category from a products table.

Hands-on MV Creation

Try running this example. It sets up a small products table, inserts some data, and then creates a Materialized View named category_avg_price based on that data.

-- Setup table
CREATE TABLE products (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100),
    category VARCHAR(50),
    price DECIMAL(10, 2)
);

-- Insert data
INSERT INTO products (name, category, price) VALUES
('Laptop', 'Electronics', 1200.00),
('Mouse', 'Electronics', 25.00),
('Keyboard', 'Electronics', 75.00),
('Desk Chair', 'Furniture', 150.00),
('Lamp', 'Furniture', 40.00);

-- Create Materialized View
CREATE MATERIALIZED VIEW category_avg_price AS
SELECT category, AVG(price) AS average_price, COUNT(*) AS product_count
FROM products
GROUP BY category
ORDER BY category;

-- Select from MV
SELECT * FROM category_avg_price;

Keeping Data Fresh

A key difference from regular views is that Materialized Views do not update automatically when the underlying data changes. You need to explicitly refresh them.

Use the REFRESH MATERIALIZED VIEW command to update the data in an MV. For large MVs, you can add CONCURRENTLY to allow other queries to access the view while it's refreshing.

`REFRESH MATERIALIZED VIEW` Demo

Let's add a new product to our products table and then refresh our category_avg_price Materialized View. Notice how the MV shows the old data until it's refreshed.

-- Add new data to the base table
INSERT INTO products (name, category, price) VALUES
('Monitor', 'Electronics', 300.00);

-- Check MV (will NOT show new data yet)
SELECT * FROM category_avg_price;

-- Refresh the Materialized View
REFRESH MATERIALIZED VIEW category_avg_price;

-- Check MV again (NOW shows new data)
SELECT * FROM category_avg_price;

MV vs. Standard Views

It's important to understand the core differences between Materialized Views and standard views:

  • Standard Views: Are essentially stored queries. They don't store data themselves; they execute their defining query every time they are accessed.
  • Materialized Views: Store the result of their defining query as actual data on disk. This makes reading from them much faster, but they require manual (or scheduled) refreshing.

Choose MVs when performance is critical for complex, static-ish data.

When to Choose Materialized Views

Materialized Views are ideal for:

  • Batch Reporting: Generating daily, weekly, or monthly reports that don't need real-time data.
  • Data Warehousing: Pre-aggregating data for faster analytical queries.
  • External Dashboards: Providing quick access to complex metrics for BI tools.
  • Static Data: When the underlying tables don't change very frequently, minimizing refresh overhead.

Avoid MVs for highly transactional, real-time data that needs immediate updates.

MV Knowledge Check

Consider a Materialized View named daily_sales_summary that aggregates sales data from a transactions table.

If new transactions are added to the transactions table, what must you do for daily_sales_summary to reflect these new sales?

Materialized Views: Recap

In this lesson, you've learned about Materialized Views in PostgreSQL.

  • They are pre-computed query results stored on disk, offering significant performance gains for complex, repetitive queries.
  • You create them with CREATE MATERIALIZED VIEW.
  • They require explicit refreshing using REFRESH MATERIALIZED VIEW to update their data.
  • They are perfect for reporting, analytics, and data warehousing where real-time updates aren't critical.

Keep practicing with MVs to master this powerful optimization technique!

常见问题解答

「使用物化视图提升性能」课时是免费的吗?

是的 — 「使用物化视图提升性能」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 PostgreSQL Performance & Query Optimization 课程的其余内容,请升级到 CoddyKit PRO。 PostgreSQL Performance & Query Optimization 课程共包含 4 节课。

「使用物化视图提升性能」这节课中我会学到什么?

了解物化视图如何预先计算复杂查询结果,从而加快报表和分析速度。 你通过在浏览器中直接运行的动手代码来练习 PostgreSQL Performance & Query Optimization,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 PostgreSQL Performance & Query Optimization 需要有经验吗?

无需任何先前经验。CoddyKit 上的 PostgreSQL Performance & Query Optimization 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「使用物化视图提升性能」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 PostgreSQL Performance & Query Optimization 课中编写并运行代码吗?

能。每节 PostgreSQL Performance & Query Optimization 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 优化聚合与窗口函数
  2. 递归 CTE 与图查询
  3. 使用物化视图提升性能
  4. 使用 FILTER 和条件聚合优化查询
← 返回 PostgreSQL Performance & Query Optimization