Sub topic 5
Changing Case with upper, lower and initcap
This chapter covers the three case-conversion functions in PostgreSQL: upper, lower and initcap. It assumes you can write basic SELECT and WHERE queries and know that NULL means "unknown". It also assumes you know the difference between text and varchar, which an earlier chapter covered.
The three functions
| Function | Effect | Example | Result |
|---|---|---|---|
| `upper(text)` | Converts every letter to uppercase | `upper('Postgres')` | `POSTGRES` |
| `lower(text)` | Converts every letter to lowercase | `lower('Postgres')` | `postgres` |
| `initcap(text)` | Uppercases the first letter of each word and lowercases the rest | `initcap('hELLO wORLD')` | `Hello World` |
All three take one string and return a string. Characters that have no case, such as digits, punctuation and spaces, pass through unchanged. All three are strict functions: if the argument is NULL, the result is NULL.
SELECT upper('Postgres 16!') AS up,
lower('Postgres 16!') AS low,
initcap('postgres 16!') AS init,
upper(NULL::text) AS from_null;This returns POSTGRES 16!, postgres 16!, Postgres 16! and NULL.
These functions accept only text-like arguments. upper(123) fails with "function upper(integer) does not exist", so cast first with upper(123::text). Unlike the || operator, upper and lower do not turn a NULL into an empty string. If you want a default, wrap the argument: upper(coalesce(code, '')).
How initcap defines a word
initcap treats a word as a run of alphanumeric characters. Any other character ends the word, and the next letter starts a new one. This has three consequences you should know:
- Punctuation splits words, so
initcap('o''reilly')givesO'Reilly, which is usually what you want. - The same rule gives wrong results for some names.
initcap('mcdonald')returnsMcdonald, notMcDonald, because the function has no knowledge of naming conventions. - Digits count as alphanumeric.
initcap('3rd place')returns3rd Place, because theris in the middle of a word that began with3.
SELECT initcap('hello-world') AS hyphen,
initcap('o''reilly') AS apostrophe,
initcap('3rd PLACE') AS digit_start,
initcap('snake_case_name') AS underscore;The results are Hello-World, O'Reilly, 3rd Place and Snake_Case_Name. In the last case the underscore splits words, which is not what the "alphanumeric" description might suggest. Test your own data before relying on initcap for names or identifiers.
initcap always lowercases the remaining letters of each word. You cannot use it to keep an acronym intact: initcap('NASA mission') returns Nasa Mission.
Sentence case
PostgreSQL has no built-in sentence-case function. Combine upper, lower, left and substring:
SELECT upper(left(s, 1)) || lower(substring(s FROM 2)) AS sentence_case
FROM (VALUES ('hELLO wORLD'), (''), (NULL)) AS t(s);The results are Hello world, an empty string, and NULL. An empty input works because left('', 1) returns an empty string. A NULL input returns NULL because every function in the expression is strict.
Case-insensitive comparison
The most common use of lower is to compare text without regard to case. The default = operator on text is case-sensitive, so 'Ana' = 'ana' is false. Normalize both sides:
SELECT lower('[email protected]') = lower('[email protected]') AS same_address;This returns true. There are three common alternatives, each with trade-offs:
lower(a) = lower(b)works everywhere and can use an expression index.a ILIKE bignores case, but it is a pattern match, so%and_inbact as wildcards. Using it for plain equality is risky whenbcomes from user input.- The
citextextension provides a case-insensitive text type. It removes the need to writelower()in every query, but it is an extension and it changes the type of the column.
Applying lower() to a column in a WHERE clause normally stops PostgreSQL from using a plain B-tree index on that column. An expression index on lower(column) fixes this. The indexing chapter at the end of this tutorial covers it in detail. The short version is that the query must use exactly the same expression as the index:
CREATE INDEX idx_users_email_lower ON users (lower(email));
SELECT id FROM users WHERE lower(email) = lower('[email protected]');If you write WHERE email = '[email protected]' against this index, PostgreSQL cannot use it, because the index stores lowercased values, not the original ones.
Normalizing on write
Instead of lowercasing at every read, you can store a normalized value and enforce it with a constraint:
CREATE TABLE accounts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL UNIQUE CHECK (email = lower(email))
);
INSERT INTO accounts (email) VALUES (lower('[email protected]'));An insert of a mixed-case address that skips lower() fails the CHECK. This keeps the UNIQUE index useful, because two addresses that differ only by case can no longer coexist. If you need to preserve the user's original spelling, keep it in a second column.
Locale, encoding and non-ASCII text
Case conversion is not a pure byte operation. What upper and lower do with a character outside ASCII depends on the database's character encoding and on the locale setting that governs character classification (LC_CTYPE), or on the ICU or built-in locale provider if the database uses one. The effects you can run into:
- In a database created with the
Clocale, only the ASCII lettersatozchange case.lower('ÉCOLE')can returnÉcole, with theÉuntouched, while a database with a Unicode-aware locale such asen_US.UTF-8returnsécole. - Some characters have no one-to-one mapping. The German
ßis the classic example. Whetherupper('straße')returnsSTRASSEorSTRAßEdepends on the locale provider and its version, so do not assume either. - Locale-specific rules exist. In a Turkish locale, the lowercase
iuppercases toİ(with a dot), andIlowercases toı(without one). A query that works in one locale can give different results in another. - A string's length can change. If a conversion expands one character into two,
char_length(upper(x))can be larger thanchar_length(x). Do not sizevarchar(n)columns on the assumption that case conversion preserves length.
To see what your database uses, check its settings:
SELECT datname, datcollate, datctype
FROM pg_database
WHERE datname = current_database();PostgreSQL 18 adds a casefold() function intended for case-insensitive matching with more sophisticated Unicode rules than lower(). If you are on an older version, lower() on both sides remains the standard approach.
Because results depend on the locale, an expression index on lower(email) is only as stable as that locale. If a collation library is upgraded and changes its rules, the stored index entries can become inconsistent with newly computed values. This is the same risk that applies to any index on collation-dependent data.
Choosing a function
The diagram summarizes how to pick an approach for a given task.
Common mistakes
- Using
initcapon names that need special capitalization.McDonald,van der BergandDeShawndo not survive. Useinitcapfor rough display cleanup, not for authoritative names. - Lowercasing only one side of a comparison.
lower(email) = '[email protected]'never matches, since the left side has no capitals. - Expecting an index to help with
lower(col)without an expression index. The query runs, but as a sequential scan. - Assuming conversion is the same everywhere. A test on a development machine with a different locale from production can give different results for non-ASCII text.
- Using
ILIKEfor equality on untrusted input. Wildcard characters in the input change the meaning of the query.
Exercise
A table people(full_name text) contains values such as 'jOHN sMITH', 'o''brien' and NULL. Write a query that returns each name with the first letter of every word capitalized and the rest lowercase. What does it return for the NULL row, and what does it return for 'o''brien'?
Show answer
SELECT initcap(full_name) FROM people; The NULL row returns NULL, because initcap is strict and returns NULL for a NULL argument. 'o''brien' returns O'Brien, because the apostrophe is not alphanumeric and starts a new word, so the b is capitalized as well.
Exercise
You have an index created with CREATE INDEX idx_c ON users (lower(email)). Which of these queries can use it: (1) WHERE email = '[email protected]', (2) WHERE lower(email) = '[email protected]', (3) WHERE upper(email) = '[email protected]'? Explain why.
Show answer
Only query 2. An expression index can be used only when the query contains the same expression as the index definition. Query 1 compares the raw column, and query 3 uses upper() instead of lower(), so neither matches the indexed expression.