Postgres lower() function
Convert strings to lowercase
The lower()
function in Postgres is used to convert a string to lowercase.
It's commonly used for search functionality where you want case-insensitivity or when you need to standardize user input for storage or comparison purposes. For example, lower()
can be used to normalize email addresses or usernames in a user management system.
Function signature
The lower()
function has a simple signature:
string
: The input string to be converted to lowercase.
Example usage
Consider a table products
with a product_name
column that contains product names with inconsistent capitalization. We can use lower()
to standardize these names for comparison or display purposes.
This query converts all product names to lowercase, making them consistent regardless of their original capitalization. Note that non-alphabetic characters are left unchanged.
Advanced examples
Case-insensitive search
You can use lower()
in a WHERE
clause to perform case-insensitive searches:
This query will find the customer regardless of how the email address was capitalized in the database or search term.
Combining with other string functions
lower()
can be combined with other string functions for more complex operations:
This query splits the username into parts, converts the name parts to lowercase, and keeps the user ID as-is.
lower()
to create indexes
Using Postgres supports creating a functional index based on the result of a function applied to a column. To optimize case-insensitive searches, we can create an index using the lower()
function:
This index will improve the performance of queries that use lower(name)
to filter data.
Normalizing data for uniqueness constraints
When you want to enforce uniqueness regardless of case, you can use lower()
to create a unique index on the column.
Trying to insert a duplicate organization name with different capitalization will raise an error:
Additional considerations
Performance implications
While lower()
is generally fast, using it in WHERE
clauses or JOIN
conditions on large tables can impact performance, as it prevents the use of standard indexes directly. In such cases, consider using functional indexes as shown in the earlier example.
Locale considerations
The lower()
function uses the database's locale setting for its case conversion rules. If your application needs to handle multiple languages, you may need to consider using the lower()
function with specific collations or implementing custom case-folding logic.
Alternative functions
upper()
- Converts a string to uppercase.initcap()
- Converts the first letter of each word to uppercase and the rest to lowercase.