PostgreSQL Performance & Query Optimization · บทเรียน

ควรสร้างดัชนีเมื่อใดและอย่างไร

เรียนรู้แนวทางปฏิบัติที่ดีที่สุดในการตัดสินใจว่าควรสร้างดัชนีให้คอลัมน์ใด และหลีกเลี่ยงการสร้างดัชนีมากเกินไปได้อย่างไร

บทเรียน 3 จาก 411 ขั้นตอน

ควรสร้างดัชนีเมื่อใดและอย่างไร เป็นบทเรียน PostgreSQL Performance & Query Optimization ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน PostgreSQL Performance & Query Optimization และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส PostgreSQL Performance & Query Optimization มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Smart Indexing Starts Here

Indexes are powerful tools for speeding up PostgreSQL queries. But they aren't magic, and blindly adding them can actually hurt performance!

In this lesson, we'll learn the art of smart indexing: when to create indexes, what types to use, and how to avoid common pitfalls like over-indexing.

Indexing Your WHERE Clause

The most common reason to create an index is to speed up searches in your WHERE clauses. If you frequently filter data based on a specific column, an index on that column can dramatically reduce query time.

Think of it like an alphabetical index in a book. Instead of scanning every page, you go straight to the relevant section.

CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  email VARCHAR(255) UNIQUE,
  name VARCHAR(255)
);
INSERT INTO users (email, name) VALUES
('alice@example.com', 'Alice'),
('bob@example.com', 'Bob'),
('charlie@example.com', 'Charlie');

-- To make this query fast, index 'email'
-- CREATE INDEX idx_users_email ON users (email);
SELECT * FROM users WHERE email = 'alice@example.com';

Indexes for JOINs and ORDER BY

Indexes don't just help with filtering; they're also crucial for efficient JOIN operations and sorting results with ORDER BY. When joining two tables, an index on the join columns helps PostgreSQL quickly match rows.

Similarly, an index on columns used in ORDER BY can allow PostgreSQL to retrieve sorted data directly, avoiding a costly sort operation.

CREATE TABLE customers (
  id SERIAL PRIMARY KEY,
  name VARCHAR(255)
);
CREATE TABLE orders (
  id SERIAL PRIMARY KEY,
  customer_id INT,
  order_date DATE
);
INSERT INTO customers (name) VALUES ('Alice'), ('Bob');
INSERT INTO orders (customer_id, order_date) VALUES
(1, '2023-01-01'), (2, '2023-01-02'), (1, '2023-01-05');

-- To speed up this query, index customer_id and order_date
-- CREATE INDEX idx_orders_customer_id ON orders (customer_id);
-- CREATE INDEX idx_orders_order_date ON orders (order_date);
SELECT c.name, o.order_date
FROM orders o
JOIN customers c ON o.customer_id = c.id
ORDER BY o.order_date DESC;

Cardinality: More Unique Values, Better

Cardinality refers to the number of unique values in a column. Columns with high cardinality (many unique values, like user_id or email) are generally excellent candidates for indexing.

An index on a low cardinality column (few unique values, like a boolean flag or gender) is often less effective because the database might still have to scan a large portion of the table.

Multi-Column Indexes: Order Matters

Sometimes, your queries filter or sort on multiple columns. A multi-column (or composite) index can cover these cases. The order of columns in a composite index is crucial due to the "left-most prefix" rule.

  • An index on (A, B, C) can help queries on A, (A, B), or (A, B, C).
  • It generally won't help queries only on B, C, or (B, C).
CREATE TABLE products (
  id SERIAL PRIMARY KEY,
  category VARCHAR(50),
  price DECIMAL(10, 2),
  color VARCHAR(20)
);
INSERT INTO products (category, price, color) VALUES
('Electronics', 599.99, 'Black'),
('Books', 25.00, 'Red'),
('Electronics', 120.00, 'Silver');

-- Create a multi-column index
CREATE INDEX idx_prod_cat_price ON products (category, price);

-- This query uses the index efficiently
SELECT * FROM products
WHERE category = 'Electronics' AND price > 100;

Partial Indexes: Targeting Subsets

A partial index is an index created on a subset of rows in a table, defined by a WHERE clause. This can make the index smaller, faster to maintain, and more efficient for queries that only target that specific subset of data.

It's perfect for tables where only a small percentage of rows are frequently queried in a specific way (e.g., "active" users, "pending" tasks).

CREATE TABLE tasks (
  id SERIAL PRIMARY KEY,
  status VARCHAR(20),
  due_date DATE
);
INSERT INTO tasks (status, due_date) VALUES
('pending', '2023-12-31'),
('completed', '2023-11-15'),
('pending', '2024-01-31'),
('archived', '2023-10-01');

-- Index only pending tasks, smaller and faster
CREATE INDEX idx_pending_tasks ON tasks (due_date) WHERE status = 'pending';

-- This query uses the partial index
SELECT * FROM tasks WHERE status = 'pending' AND due_date < '2024-01-01';

Expression Indexes: Computed Values

An expression index allows you to create an index on the result of a function or expression, rather than just a raw column value. This is incredibly useful for queries that transform data before comparison.

Common uses include case-insensitive searches (using LOWER() or UPPER()) or indexing parts of a string or date.

CREATE TABLE contacts (
  id SERIAL PRIMARY KEY,
  email VARCHAR(255)
);
INSERT INTO contacts (email) VALUES
('JOHN.DOE@example.com'),
('jane.doe@example.com'),
('peter.smith@example.com');

-- Index for case-insensitive email searches
CREATE INDEX idx_email_lower ON contacts (LOWER(email));

-- This query uses the expression index
SELECT * FROM contacts WHERE LOWER(email) = 'john.doe@example.com';

When NOT to Index: The Pitfalls

Not every column needs an index. Here are some scenarios where indexes might not help, or even hurt performance:

  • Low Cardinality: Columns with very few unique values (e.g., a boolean is_active flag) often don't benefit much.
  • Small Tables: For tables with only a few hundred rows, a full table scan is often faster than an index lookup.
  • Infrequently Queried Columns: If a column is rarely used in WHERE, JOIN, or ORDER BY clauses, an index is probably unnecessary.

Avoiding Over-Indexing

It's tempting to index everything, but over-indexing is a real problem. Each index comes with overhead:

  • Write Performance: Every INSERT, UPDATE, or DELETE operation must also update all relevant indexes, slowing down writes.
  • Disk Space: Indexes consume disk space, sometimes significantly.
  • Query Planner Overhead: Too many indexes can confuse the query planner, making it harder for PostgreSQL to choose the optimal plan.

Aim for a balanced approach: index what's truly needed.

Index Best Practices

Which of the following scenarios are generally good candidates for creating an index in PostgreSQL?

Recap: Indexing Wisely

You've learned that indexing isn't about indexing everything, but about making strategic choices. Indexes are vital for speeding up WHERE, JOIN, and ORDER BY clauses, especially on columns with high cardinality.

Remember to consider partial and expression indexes for specific needs, and always be mindful of the costs of over-indexing. The goal is to optimize reads without unduly sacrificing write performance or consuming excessive resources.

เริ่มต้นได้ฟรี

เรียนรู้ SQL ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
22
บทเรียน
88

คำถามที่พบบ่อย

บทเรียน “ควรสร้างดัชนีเมื่อใดและอย่างไร” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “ควรสร้างดัชนีเมื่อใดและอย่างไร” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส PostgreSQL Performance & Query Optimization ให้อัปเกรดเป็น CoddyKit PRO คอร์ส PostgreSQL Performance & Query Optimization มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “ควรสร้างดัชนีเมื่อใดและอย่างไร”

เรียนรู้แนวทางปฏิบัติที่ดีที่สุดในการตัดสินใจว่าควรสร้างดัชนีให้คอลัมน์ใด และหลีกเลี่ยงการสร้างดัชนีมากเกินไปได้อย่างไร คุณปฏิบัติ PostgreSQL Performance & Query Optimization ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน PostgreSQL Performance & Query Optimization หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน PostgreSQL Performance & Query Optimization บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “ควรสร้างดัชนีเมื่อใดและอย่างไร” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน PostgreSQL Performance & Query Optimization นี้ได้ไหม

ได้ บทเรียน PostgreSQL Performance & Query Optimization ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. พื้นฐานดัชนี B-Tree
  2. การสร้างและใช้ดัชนี
  3. ควรสร้างดัชนีเมื่อใดและอย่างไร
  4. ดัชนีแบบผสมและแบบครอบคลุม
← กลับไปที่ PostgreSQL Performance & Query Optimization