How to Create Expression Index in PostgreSQL: Syntax and Examples
In PostgreSQL, create an expression index using
CREATE INDEX index_name ON table_name (expression); where expression is any valid SQL expression. This index speeds up queries filtering or sorting by the expression instead of just columns.Syntax
The basic syntax to create an expression index in PostgreSQL is:
CREATE INDEX index_name: Names the index.ON table_name: Specifies the table to index.(expression): Defines the expression to index, which can be a function or calculation on columns.
sql
CREATE INDEX index_name ON table_name (expression);
Example
This example creates an expression index on the lowercased values of the username column to speed up case-insensitive searches.
sql
CREATE TABLE users (id SERIAL PRIMARY KEY, username TEXT); CREATE INDEX idx_lower_username ON users (LOWER(username)); -- Query that benefits from this index: SELECT * FROM users WHERE LOWER(username) = 'alice';
Common Pitfalls
Common mistakes when creating expression indexes include:
- Not using the exact same expression in queries as in the index, so the index is not used.
- Creating indexes on expressions that are too complex or volatile functions, which can slow down writes.
- Forgetting to consider NULL values in expressions, which might affect index usage.
Always ensure your query expression matches the index expression exactly.
sql
/* Wrong: index on LOWER(username), but query uses username without LOWER() */ CREATE INDEX idx_lower_username ON users (LOWER(username)); SELECT * FROM users WHERE username = 'alice'; -- index not used /* Correct: query uses LOWER() to match index */ SELECT * FROM users WHERE LOWER(username) = 'alice';
Quick Reference
| Concept | Description |
|---|---|
| CREATE INDEX | Command to create an index on a table |
| Expression | Any SQL expression using columns, functions, or calculations |
| Index Usage | Query must use the exact expression to benefit from the index |
| Performance | Speeds up reads but may slow writes due to index maintenance |
| NULL Handling | Consider how NULLs affect your expression and queries |
Key Takeaways
Use CREATE INDEX with an expression to speed up queries filtering by that expression.
The query must use the exact same expression as the index to benefit from it.
Avoid indexing volatile or very complex expressions to keep write performance reasonable.
Expression indexes are useful for case-insensitive searches or computed columns.
Always test your queries to confirm the index is being used as expected.