0Pricing
PostgreSQL Performance & Query Optimization · 课时

创建和使用索引

通过实践学习如何创建索引、理解其语法,并应用索引提升查询性能。

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

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

Welcome to Index Creation

In the last lesson, we learned about B-Tree indexes, the most common type in PostgreSQL. Now, let's get practical! This lesson will guide you through creating, using, and managing indexes to boost your query performance.

You'll learn the syntax, see practical examples, and understand when and how to apply indexes effectively.

The CREATE INDEX Statement

The basic syntax for creating an index is straightforward. You specify the table, the column(s) to index, and optionally the index type (though B-Tree is default and most common).

  • CREATE INDEX: The command to create a new index.
  • index_name: A unique name you choose for your index.
  • table_name: The table on which the index is built.
  • column_name(s): The column(s) to include in the index.

Simple Index Creation Demo

Let's create a simple products table, insert some data, and then add a single-column index. This setup will be used in subsequent examples.

DROP TABLE IF EXISTS products;

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

INSERT INTO products (product_name, price, category) VALUES
('Laptop', 1200.00, 'Electronics'),
('Mouse', 25.00, 'Electronics'),
('Keyboard', 75.00, 'Electronics'),
('Desk Chair', 150.00, 'Furniture'),
('Monitor', 300.00, 'Electronics'),
('Webcam', 50.00, 'Electronics'),
('Gaming PC', 1500.00, 'Electronics'),
('Office Desk', 250.00, 'Furniture'),
('Bookshelf', 80.00, 'Furniture'),
('Smartwatch', 199.99, 'Wearables');

CREATE INDEX idx_products_category ON products (category);

Verify Your New Index

After creating an index, it's a good practice to confirm it exists. PostgreSQL provides a few ways to inspect your table's structure and its associated indexes.

  • In the psql command-line client, type \d products to see details for the products table, including its indexes.
  • Alternatively, you can query system catalog tables like pg_indexes: SELECT indexname, indexdef FROM pg_indexes WHERE tablename = 'products';

When Indexes Help Queries

Indexes are most effective when PostgreSQL needs to quickly locate specific rows without scanning the entire table. Think of them like the index in a textbook, pointing directly to relevant pages.

  • WHERE clauses: Filtering data by indexed columns (e.g., WHERE category = 'Electronics').
  • ORDER BY clauses: Sorting data by indexed columns.
  • JOIN conditions: Connecting tables on indexed columns.

Without an index, PostgreSQL might perform a slow "sequential scan" on large tables.

Single-Column Index in Action

Let's use EXPLAIN to see how our idx_products_category index can help a query that filters by the category column. EXPLAIN shows the query plan, revealing if an index is used.

-- Query that benefits from idx_products_category
EXPLAIN SELECT * FROM products WHERE category = 'Electronics';

-- Another example where the index might help with sorting
EXPLAIN SELECT product_name, price FROM products WHERE category = 'Furniture' ORDER BY price DESC;

Composite (Multi-Column) Indexes

Sometimes, your queries filter or sort by *multiple* columns together. In such cases, a composite index (or multi-column index) can be highly beneficial.

It includes more than one column, and the order of columns matters! Place the most frequently used or most selective columns (those with more unique values) first.

Creating a Composite Index

Let's create a composite index on both category and price. This would be useful for queries that filter by category and then further filter or sort by price within that category.

DROP INDEX IF EXISTS idx_products_category_price;
CREATE INDEX idx_products_category_price ON products (category, price);

-- Query benefiting from the composite index
EXPLAIN SELECT product_name, price
FROM products
WHERE category = 'Electronics' AND price > 100
ORDER BY price DESC;

When Not to Index

Indexes aren't always a magic bullet. They come with trade-offs:

  • Storage space: Indexes consume disk space, potentially a lot for large tables.
  • Write overhead: Every INSERT, UPDATE, or DELETE on an indexed column requires updating the index, which can slow down write operations.
  • Over-indexing: Too many indexes can confuse the query planner or increase write overhead, hurting overall performance.

Avoid indexing columns with very few unique values (e.g., a boolean is_active column).

Removing an Index

If an index is no longer needed, or if you've created a better one, you can easily remove it using the DROP INDEX command. This frees up storage space and reduces write overhead on your database.

DROP INDEX IF EXISTS idx_products_category_price;
DROP INDEX IF EXISTS idx_products_category;

-- You can also drop the table if you want to clean up completely
-- DROP TABLE IF EXISTS products;

Indexing Quiz

You've learned how to create and manage indexes. Let's test your understanding!

Recap: Creating & Using Indexes

Fantastic work! In this lesson, you learned the practical steps for creating and managing indexes in PostgreSQL:

  • We used the CREATE INDEX command to add indexes to tables.
  • We explored both single-column and composite (multi-column) indexes.
  • You learned when indexes are beneficial (WHERE, ORDER BY, JOIN) and their trade-offs (write overhead, storage).
  • Finally, you also learned how to verify and remove indexes using DROP INDEX.

Next, we'll dive deeper into best practices for deciding *which* columns to index and how to avoid common pitfalls!

常见问题解答

「创建和使用索引」课时是免费的吗?

是的 — 「创建和使用索引」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 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 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「创建和使用索引」课时需要多长时间?

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

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

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

此课程中的所有课时

  1. B-Tree 索引基础
  2. 创建和使用索引
  3. 何时以及如何创建索引
  4. 复合索引与覆盖索引
← 返回 PostgreSQL Performance & Query Optimization