Explain Codes LogoExplain Codes Logo

How to compare strings in SQL ignoring case?

sql
case-insensitive-search
sql-indexes
collation-settings
Anton ShumikhinbyAnton Shumikhin·Aug 21, 2024
TLDR

To ignore case in SQL string comparison, apply the LOWER() or UPER() functions to both sides of the equation:

SELECT * FROM my_table WHERE LOWER(column_name) = LOWER('my_string'); -- All the cool kids use lower(); be cool

Executing this makes sure that any differences in case do not interfere with string comparison.

Matching with wildcards

In case you need to achieve partial matching, use LIKE operator alongside the LOWER() or UPER() function:

SELECT * FROM my_table WHERE LOWER(column_name) LIKE LOWER('%my_string%'); -- Who cares about the case when you've got wildcards?

Applying global session settings

For Oracle databases, you can universally set case-insensitive comparisons for an entire session:

ALTER SESSION SET NLS_COMP = LINGUISTIC; ALTER SESSION SET NLS_SORT = BINARY_CI; -- Hey Oracle, take a chill pill on case sensitivity, will ya!

These commands help in reducing redundancies in your queries when case insensitivity is consistently the need of the hour.

Considering efficiency and special characters

Utilizing LIKE with a prefix % can potentially slow down your query. For optimized performance, if case-insensitive searches are frequent, create a functional index on the LOWER() or UPER() function:

CREATE INDEX IDX_LOWER_COLUMN ON my_table ((LOWER(column_name))); -- Say hello to my little 'index' friend!

Remember when dealing with non-English characters, default case conversion functions might not apply predictably. Hence examination of collation and locale-specific settings is recommended.

Index creation for case-insensitivity

Setting up the indexes to facilitate case-insensitive searching can lend a hand in enhancing the query efficiency. Here's an example for PostgreSQL:

CREATE INDEX idx_case_insensitive_column ON table_name ((LOWER(column_name))); -- Let the index do the heavy lifting

Align your queries using the LOWER() function to fully utilize the index created.

Addressing compatibility with non-English letters

Issues may arise when dealing with non-English characters since simple case conversion isn't always universal. In such cases, delve into the collation and encoding settings:

SELECT * FROM my_table WHERE column_name ILIKE 'my_string'; -- Because 'string' is an international citizen

The above instance employs PostgreSQL's ILIKE, performing a case-insensitive search, considering locale-specific variations.