A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/postgresql-index-on-expression/ below:

PostgreSQL - Index On Expression

PostgreSQL - Index On Expression

Last Updated : 15 Jul, 2025

When working with databases, optimizing query performance is crucial, especially when dealing with large datasets. One powerful technique in PostgreSQL is leveraging indexes on expressions. This approach allows you to optimize queries that involve expressions, ensuring faster retrieval times and efficient database operations. In this article, we'll explore how to create and use indexes on expressions to enhance query performance, using practical examples.

Index On Expression in PostgreSQL

Indexes on expressions are special types of indexes in PostgreSQL that store the result of an expression rather than just the column values. This is particularly useful when your queries involve expressions like functions, arithmetic operations, or transformations. By indexing the result of an expression, PostgreSQL can quickly retrieve the relevant rows without recalculating the expression for each row during a query.

Syntax

Use the below syntax for creating an index on expression :

CREATE INDEX index_name 
ON table_name (expression);

Let's analyze the above syntax:

PostgreSQL Index On Expression Example

For the purpose of demonstration, we will work with the 'customer' table of the sample database, ie, dvdrental.

Scenario 1: Without an Index on Expression

The customer table has a B-Tree index defined for the 'first_name' column. The following query finds customers whose last name is “Purdy”:

SELECT 
    customer_id, 
    first_name, 
    last_name 
FROM 
    customer 
WHERE 
    last_name = 'Purdy';

When executing this query, PostgreSQL uses the 'idx_last_name' index as shown in the following EXPLAIN statement:

EXPLAIN
SELECT 
    customer_id, 
    first_name, 
    last_name 
FROM 
    customer 
WHERE 
    last_name = 'Purdy';

It will result in the following:

Scenario 2: With an Index on Expression

To improve this query, you can define an index expression like this:

CREATE INDEX idx_ic_last_name
ON customer(LOWER(last_name));

Now, the query that finds customers based on the last name in a case-insensitive manner will use the index on expression as shown below:

EXPLAIN
SELECT 
    customer_id, 
    first_name, 
    last_name 
FROM 
    customer 
WHERE 
    LOWER(last_name) = 'purdy';

Output:

Important Points About PostgreSQL Index On Expression


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4