PostgreSQL – CREATE INDEX
Last Updated :
13 Aug, 2024
Indexes in PostgreSQL are crucial for improving the performance of database searches. They function similarly to a phone book. Imagine looking up Raju Kumar’s phone number in an alphabetically ordered phone book. You quickly navigate to the ‘K’ section, find ‘Kumar,’ then ‘Raju,’ and finally get his phone number. This ordered search is efficient. However, if the phone book were unordered, you would have to scan every entry sequentially to find Raju Kumar, making the search time-consuming. This sequential scan is what happens when a database table lacks indexes.
Why Use Indexes?
Indexes in PostgreSQL organize table data in a particular order to speed up searches. They act like the alphabetized phone book, allowing for quick data retrieval. Without indexes, PostgreSQL performs a sequential scan, checking each row until it finds the matching data. This method is slow, especially for large datasets.
In PostgreSQL, the CREATE INDEX statement to define a new index for a table.
Syntax
CREATE INDEX index_name ON table_name [USING method]
(
column_name [ASC | DESC] [NULLS {FIRST | LAST }],
...
);
Parameters
Let’s analyze the above syntax:
- Index Name: Choose a meaningful and memorable name for the index.
- Table Name: Specify the table to which the index belongs.
- Index Method: Choose an index method such as ‘btree’, ‘hash’, ‘gist’, ‘spgist’, ‘gin’, or ‘brin’. PostgreSQL defaults to ‘btree’.
- Columns: List one or more columns to include in the index.
- Sort Order: Specify the sort order with ‘ASC’ (default) or ‘DESC’.
- Nulls Order: Specify ‘NULLS FIRST’ or ‘NULLS LAST’. ‘NULLS FIRST’ is the default with ‘DESC’, and ‘NULLS LAST’ is the default with ‘ASC’.
For the purpose of demonstration, we will use the address table from the sample database for the demonstration.

PostgreSQL CREATE INDEX Example
Let us look at an example of CREATE INDEX Statement in PostgreSQL to better understand the concept.
The following query finds the address whose phone number is 223664661973.
Query:
SELECT * FROM address
WHERE phone = '223664661973';
It is obvious that the database engine had to scan the whole address table to look for the address because there is no index available for the phone column.
To show the query plan, you use the EXPLAIN statement as follows.
Query:
EXPLAIN SELECT * FROM address
WHERE phone = '223664661973';
This will result in the following:

To create an index for the values in the phone column of the address table, you use the following statement.
Query:
CREATE INDEX idx_address_phone
ON address(phone);
Now, if you execute the query again, you will find that the database engine uses the index for lookup.
Query:
EXPLAIN SELECT * FROM address
WHERE phone = '223664661973';
Output:

This time, the output will show that PostgreSQL uses the index for a more efficient lookup, significantly speeding up the query.
Please Login to comment...