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 Covering Indexes?

Welcome to our lesson on Covering Indexes and Index-Only Scans! These advanced indexing techniques can dramatically boost your PostgreSQL query performance.

A regular index helps PostgreSQL quickly find rows based on certain column values. Think of it like a book's index: it tells you which page to go to for a topic.

The Cost of Table Access

When you use a standard index, PostgreSQL first finds the row's location (its tuple ID or CTID) in the index. Then, it has to go to the actual table to fetch the rest of the data for that row.

This extra step, called a table lookup or heap fetch, can be slow, especially if many rows are involved or if the table data isn't in memory.

Indexing All You Need

A covering index is an index that contains all the columns needed to fulfill a query, not just the columns in the WHERE clause. This means PostgreSQL can answer the query by reading only the index, without ever touching the main table data.

It 'covers' the query's data requirements entirely.

Building a Covering Index

To create a covering index, you include all the columns your query might select or filter on. PostgreSQL supports including non-key columns using the INCLUDE clause, which stores them without making them part of the primary sort key.

Let's create a table and then a covering index.

CREATE TABLE products (
  product_id SERIAL PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  price DECIMAL(10, 2) NOT NULL,
  category VARCHAR(50)
);

INSERT INTO products (name, price, category) VALUES
('Laptop', 1200.00, 'Electronics'),
('Keyboard', 75.00, 'Accessories'),
('Mouse', 25.00, 'Accessories'),
('Monitor', 300.00, 'Electronics');

-- Covering index for queries on category that also select name and price
CREATE INDEX idx_products_category_cover_name_price
ON products (category) INCLUDE (name, price);

Introducing Index-Only Scans

When a query can be fully satisfied by a covering index, PostgreSQL performs an Index-Only Scan. This is a highly efficient operation because the database engine doesn't need to read any data blocks from the main table (the 'heap').

It's like finding all the information you need directly in the book's index, without ever turning to the main chapters.

MVCC & Index-Only Scans

PostgreSQL uses MVCC (Multi-Version Concurrency Control). For an Index-Only Scan to work, PostgreSQL must ensure that the versions of the rows it finds in the index are visible to the current transaction.

It does this by checking the table's visibility map, a special data structure that tracks which table pages contain only 'all-visible' tuples. If a page is marked all-visible, no heap fetch is needed to check row visibility.

Confirming with EXPLAIN

You can verify if PostgreSQL is using an Index-Only Scan by checking the query plan with EXPLAIN ANALYZE. Look for Index Only Scan in the output.

Let's try a query that our covering index should handle.

EXPLAIN ANALYZE
SELECT name, price
FROM products
WHERE category = 'Electronics';

Benefits: Speed & Efficiency

Index-Only Scans offer several key advantages:

  • Reduced Disk I/O: Fewer disk reads are needed because the main table is skipped.
  • Faster Query Execution: Less I/O directly translates to quicker query responses.
  • Better Cache Utilization: Indexes are often smaller and more frequently accessed, leading to better use of memory caches.
  • Concurrency: Less contention on table data blocks.

Trade-offs & Considerations

While powerful, covering indexes aren't a silver bullet:

  • Larger Indexes: Including more columns makes the index physically larger, consuming more disk space.
  • Slower Writes: Updates, inserts, and deletes to the main table also require updating the index, which can be slower for larger indexes.
  • Maintenance: Larger indexes might take longer to VACUUM.

Use them strategically for read-heavy queries that frequently access a specific subset of columns.

Practical Covering Index Example

Consider a `users` table where you often query user names and emails based on their registration date. An index on `registration_date` including `name` and `email` would be a perfect candidate for a covering index.

CREATE TABLE users (
  user_id SERIAL PRIMARY KEY,
  username VARCHAR(50) NOT NULL,
  email VARCHAR(100) NOT NULL,
  registration_date DATE NOT NULL
);

INSERT INTO users (username, email, registration_date) VALUES
('alice', 'alice@example.com', '2023-01-15'),
('bob', 'bob@example.com', '2023-02-20'),
('charlie', 'charlie@example.com', '2023-01-25');

CREATE INDEX idx_users_regdate_cover_name_email
ON users (registration_date) INCLUDE (username, email);

EXPLAIN ANALYZE
SELECT username, email
FROM users
WHERE registration_date BETWEEN '2023-01-01' AND '2023-01-31';

Quick Check: Index Scans

Based on what you've learned, identify the correct statements about Index-Only Scans in PostgreSQL.

Recap: Covering Indexes

You've learned that covering indexes include all columns needed by a query, enabling highly efficient Index-Only Scans. These scans bypass the main table, significantly reducing disk I/O and speeding up read-heavy queries.

Remember to use EXPLAIN ANALYZE to confirm their usage and consider the trade-offs of increased index size and potential write overhead. Happy optimizing!

常见问题解答

「覆盖索引与仅索引扫描」课时是免费的吗?

是的 — 「覆盖索引与仅索引扫描」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 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. Hash、GIN 与 GiST 索引
  2. 部分索引与表达式索引
  3. 覆盖索引与仅索引扫描
  4. 面向大型顺序数据的 BRIN 索引
← 返回 PostgreSQL Performance & Query Optimization