PostgreSQL Performance & Query Optimization · Pelajaran

Indeks Parsial dan Indeks Ekspresi

Pelajari cara membuat indeks pada sebagian baris atau pada hasil suatu ekspresi untuk pengoptimalan yang terarah.

Pelajaran 2 dari 411 langkah

Indeks Parsial dan Indeks Ekspresi adalah pelajaran PostgreSQL Performance & Query Optimization gratis di CoddyKit. Ini adalah pelajaran 2 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar PostgreSQL Performance & Query Optimization, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus PostgreSQL Performance & Query Optimization mencakup 4 pelajaran total.

Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.

Intro to Targeted Indexes

Welcome! In this lesson, we'll dive into two powerful, specialized index types in PostgreSQL: Partial Indexes and Expression Indexes.

These indexes allow for highly targeted optimization, focusing on specific subsets of data or the results of calculations, rather than entire columns.

Focus with Partial Indexes

A Partial Index is an index that covers only a portion of the rows in a table. You define this subset using a WHERE clause during index creation.

Think of it as filtering your index. Only rows that satisfy the WHERE condition will be included in the index structure.

Benefits of Partial Indexes

Why use a partial index?

  • Smaller Size: They take up less disk space and memory compared to full indexes.
  • Faster Updates: Less data to maintain means faster INSERT, UPDATE, and DELETE operations on the indexed table.
  • Reduced Bloat: Can significantly reduce index bloat on tables with frequently updated rows that don't satisfy the index's WHERE clause.

They shine when a small subset of rows is queried very often, like 'active' users or 'pending' orders.

Creating Partial Indexes

The syntax for a partial index is straightforward. You simply add a WHERE clause to your standard CREATE INDEX statement.

The condition in the WHERE clause must match the condition used in your queries for the index to be effective.

CREATE INDEX index_name
ON table_name (column_name)
WHERE condition;

Partial Index in Action

Let's see a partial index in action. We'll create an index on order_date specifically for orders with a status of 'pending'. This is common for e-commerce where 'pending' orders need quick attention.

Try running the code to see how it works:

CREATE TABLE orders (
  order_id SERIAL PRIMARY KEY,
  customer_id INT,
  order_date DATE,
  status VARCHAR(20)
);

INSERT INTO orders (customer_id, order_date, status) VALUES
(101, '2023-01-15', 'completed'),
(102, '2023-01-16', 'pending'),
(103, '2023-01-17', 'completed'),
(104, '2023-01-18', 'pending'),
(105, '2023-01-19', 'completed'),
(106, '2023-01-20', 'completed'),
(107, '2023-01-21', 'pending');

CREATE INDEX idx_pending_orders_date
ON orders (order_date)
WHERE status = 'pending';

EXPLAIN ANALYZE SELECT order_id, order_date
FROM orders
WHERE status = 'pending' AND order_date > '2023-01-01';

Indexing Expressions

An Expression Index (also known as a Function-Based Index) indexes the result of a function or expression, rather than just the raw column value.

This is incredibly useful when your queries frequently use functions on columns, like converting text to lowercase for case-insensitive searches.

Power of Expression Indexes

Expression indexes offer great flexibility:

  • Case-Insensitive Search: Index LOWER(column) or UPPER(column) to speed up queries like WHERE LOWER(column) = 'value'.
  • Date/Time Manipulation: Index DATE_TRUNC('month', timestamp_column) to optimize queries grouped or filtered by month.
  • Complex Computations: Index on mathematical results or custom functions if they are part of frequent query conditions.

Without an expression index, PostgreSQL would have to compute the function for every row during a scan, making it slow.

Creating Expression Indexes

To create an expression index, you simply replace the column name in your CREATE INDEX statement with the desired function or expression.

The important rule is that the expression in your query's WHERE clause must exactly match the expression used in the index definition for the index to be used.

CREATE INDEX index_name
ON table_name (expression);

Expression Index Example

Let's create an expression index to enable fast, case-insensitive searches on email addresses. This is a very common use case.

Notice how the EXPLAIN ANALYZE output should show an 'Index Scan' using our new idx_lower_email index.

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

INSERT INTO users (username, email) VALUES
('Alice', 'alice@example.com'),
('Bob', 'BOB@example.com'),
('Charlie', 'Charlie@example.com'),
('David', 'david@example.com');

CREATE INDEX idx_lower_email ON users (LOWER(email));

EXPLAIN ANALYZE SELECT user_id, username
FROM users
WHERE LOWER(email) = 'bob@example.com';

-- This query would NOT use the index:
-- EXPLAIN ANALYZE SELECT user_id, username
-- FROM users
-- WHERE email = 'bob@example.com';

Apply Your Knowledge

Now that you've learned about Partial and Expression Indexes, let's test your understanding.

Lesson Summary

Great job! You've learned about two powerful advanced indexing techniques:

  • Partial Indexes: Index only a subset of rows based on a WHERE clause, saving space and speeding up writes.
  • Expression Indexes: Index the result of a function or expression, optimizing queries that use those functions in their conditions.

By using these targeted indexes, you can significantly improve the performance of specific, critical queries in your PostgreSQL database.

Gratis untuk memulai

Belajar SQL dengan tutor AI — gratis

Tulis dan jalankan kode asli di browser kamu, dapatkan bantuan instan dari tutor AI 24/7, dan lanjutkan di mana kamu tinggalkan di web atau aplikasi.

Kursus
22
Pelajaran
88

Pertanyaan yang Sering Diajukan

Apakah pelajaran “Indeks Parsial dan Indeks Ekspresi” gratis?

Ya — teks lengkap “Indeks Parsial dan Indeks Ekspresi” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus PostgreSQL Performance & Query Optimization, upgrade ke CoddyKit PRO. Kursus PostgreSQL Performance & Query Optimization mencakup 4 pelajaran total.

Apa yang akan aku pelajari di “Indeks Parsial dan Indeks Ekspresi”?

Pelajari cara membuat indeks pada sebagian baris atau pada hasil suatu ekspresi untuk pengoptimalan yang terarah. Kamu berlatih PostgreSQL Performance & Query Optimization dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.

Apakah aku perlu pengalaman untuk memulai PostgreSQL Performance & Query Optimization?

Tidak diperlukan pengalaman sebelumnya. PostgreSQL Performance & Query Optimization di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 2 dari 4.

Berapa lama pelajaran “Indeks Parsial dan Indeks Ekspresi” memakan waktu?

Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.

Bisakah aku menulis dan menjalankan kode dalam pelajaran PostgreSQL Performance & Query Optimization ini?

Ya. Setiap pelajaran PostgreSQL Performance & Query Optimization menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.

Semua pelajaran dalam kursus ini

  1. Indeks Hash, GIN, dan GiST
  2. Indeks Parsial dan Indeks Ekspresi
  3. Indeks Peliput dan Pemindaian Hanya Indeks
  4. Indeks BRIN untuk Data Sekuensial Berskala Besar
← Kembali ke PostgreSQL Performance & Query Optimization