Creating Indexes in IBM DB2 | Generated by AI

Home 2025.10

Creating Indexes in IBM DB2

IBM DB2 supports indexes to optimize query performance by allowing faster data retrieval. Indexes can be created on one or more columns of a table. Below, I’ll cover the basics, including unique indexes and multi-column (composite) indexes. Note that “union index” isn’t a standard term in DB2 documentation— it might refer to a composite index (covering multiple keys) or a misunderstanding of union operations in queries. If you meant something else, provide more details!

Basic Index Creation

Use the CREATE INDEX statement to build a simple index on a single column. This speeds up searches, sorts, and joins on that column.

Syntax:

CREATE INDEX index_name
ON table_name (column_name [ASC | DESC]);

Example:

CREATE INDEX idx_employee_id
ON employees (employee_id ASC);

Unique Index (Enforcing Unique Keys)

A unique index ensures no duplicate values in the indexed column(s), similar to a unique constraint. DB2 automatically creates a unique index when you define a primary key or unique constraint.

Syntax:

CREATE UNIQUE INDEX index_name
ON table_name (column_name [ASC | DESC]);

Example:

CREATE UNIQUE INDEX uidx_email
ON users (email ASC);

Composite Index (Multiple Keys, e.g., Two or More Columns)

A composite (or multi-column) index covers multiple keys, useful for queries filtering/joining on combinations of columns. The order of columns matters—place the most selective column first.

Syntax:

CREATE INDEX index_name
ON table_name (column1 [ASC | DESC], column2 [ASC | DESC], ...);

Example (Two Keys):

CREATE INDEX idx_order_date_customer
ON orders (order_date ASC, customer_id DESC);

Additional Tips

Db2 CREATE INDEX Statement
Db2 Unique Indexes
Db2 Composite Indexes Example
Db2 Unique Index Tutorial


Back

x-ai/grok-4-fast

Donate