Course contentsShow
← Databases & SQL
Lesson 159 of 1,9532. Querying and Data RetrievalFree lesson

Filtering on Calculated Expressions

Implement functional indexes to optimize queries that filter on transformed columns.

Optimizing Filters on Calculated Expressions

In this lesson, you will learn how to use functional indexes to make your queries lightning-fast when filtering on columns that require transformation.

The Problem: Calculation vs. Performance

Previously, we learned how to filter on calculated expressions, such as WHERE UPPER(last_name) = 'SMITH'. While this works, it often creates a performance bottleneck. When you apply a function to a column inside a WHERE clause, the database cannot use a standard index on that column. It must perform a "full table scan," calculating that function for every single row in your table to see if it matches. For large datasets, this makes your queries crawl.

The Solution: Functional Indexes

A functional index (also called an expression-based index) solves this by pre-calculating the expression and storing the result in the index itself. Instead of indexing the raw data, the database indexes the output of your calculation.

If you frequently search for users by their uppercase last names, you can create an index specifically for that expression:

CREATE INDEX idx_upper_last_name 
ON users (UPPER(last_name));

Now, when you run your query, the database engine skips the expensive calculation at runtime. It looks directly at the idx_upper_last_name index, which already contains the pre-calculated, uppercase values. It finds the matching rows instantly, just as if you were searching a standard column.

Why This Matters

Think of a standard index like an alphabetical index at the back of a book. If you try to find a word that has been "transformed" (like looking for the uppercase version of a word that is written in lowercase in the index), the index becomes useless. A functional index is like creating a second index specifically for those uppercase terms.

You should use this technique when:

  1. You have a heavy read-load on a specific calculation.
  2. The calculation involves deterministic functions (functions that always return the same output for the same input).
  3. Query performance metrics show that the WHERE clause transformation is the primary cause of slow execution.

Key Takeaway: Functional indexes allow the database to pre-compute transformed values, turning slow, calculation-heavy filters into highly efficient, index-backed lookups.