인덱스 생성 및 사용
인덱스를 생성하고 구문을 이해하며 쿼리 성능을 향상하도록 적용하는 방법을 실습 중심으로 학습합니다.
인덱스 생성 및 사용은(는) CoddyKit의 무료 PostgreSQL Performance & Query Optimization 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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
psqlcommand-line client, type\d productsto see details for theproductstable, 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.
WHEREclauses: Filtering data by indexed columns (e.g.,WHERE category = 'Electronics').ORDER BYclauses: Sorting data by indexed columns.JOINconditions: 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, orDELETEon 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 INDEXcommand 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!
자주 묻는 질문
“인덱스 생성 및 사용” 강의는 무료인가요?
네 — “인덱스 생성 및 사용” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 PostgreSQL Performance & Query Optimization 강의 전체를 잠금 해제할 수 있습니다. PostgreSQL Performance & Query Optimization 강의에는 총 4개의 강의가 포함되어 있습니다.
“인덱스 생성 및 사용”에서 뭘 배우나요?
인덱스를 생성하고 구문을 이해하며 쿼리 성능을 향상하도록 적용하는 방법을 실습 중심으로 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 PostgreSQL Performance & Query Optimization을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
PostgreSQL Performance & Query Optimization을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 PostgreSQL Performance & Query Optimization은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“인덱스 생성 및 사용” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 PostgreSQL Performance & Query Optimization 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 PostgreSQL Performance & Query Optimization 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- B-Tree 인덱스 기초
- 인덱스 생성 및 사용
- 인덱스를 사용할 시점과 방법
- 복합 인덱스와 포함 인덱스