Nov 23, 20265 min read

Case-Insensitive Unique Emails in Postgres: citext vs lower() Index

Three ways to stop Ana@example.com and ana@example.com from becoming two accounts, how each one affects queries and LIKE, how to clean up existing duplicates, and a Go example on Encore.

Illustration for Case-Insensitive Unique Emails in Postgres: citext vs lower() Index

A plain UNIQUE constraint on an email column compares bytes, so Ana@example.com and ana@example.com can belong to two accounts. The duplicate usually appears months later, when a phone capitalizes the first letter at signup.

Postgres offers three fixes that differ in query style, LIKE behavior and portability. This guide compares them, cleans up existing duplicates and wires the result into a Go API.

What are the options for case-insensitive uniqueness?

A unique index on lower(email). The column stays plain text, and an index on an expression enforces uniqueness on the lowercased value. It works on every Postgres version and every managed service, the stored value keeps the user's capitalization, and queries must filter on lower(email) to use the index.

The citext type. The citext extension adds a text type whose comparisons are case-insensitive, so a normal UNIQUE constraint and a normal WHERE email = $1 both work. It needs CREATE EXTENSION citext, and the Postgres docs themselves now point to nondeterministic collations as the preferred approach.

A nondeterministic ICU collation. You define a collation such as und-u-ks-level2 with deterministic = false and declare the column with it, and equality and unique constraints ignore case. The collation documentation covers the details, and the practical limit is that LIKE on such a column fails with "nondeterministic collations are not supported for LIKE" before Postgres 18.

Which one should you pick?

For email addresses on an existing table, the lower() index is the least surprising: no extension, no type change, no collation that needs ICU, and the behavior is visible in every query that uses it. Pick citext when many queries compare the column and you would rather not wrap each one in lower(). Pick a nondeterministic collation when you are on Postgres 18 or later, or do not need LIKE on that column, and want the most correct Unicode handling, since lower() and citext only fold case and treat some characters differently from ICU.

lower() indexcitextICU collation
Schema changeIndex onlyColumn type and extensionCollation and column definition
Query changesFilter on lower(email)NoneNone
LIKEWorksWorks, case-insensitiveNot supported before Postgres 18

How do you clean up duplicates before adding the index?

The CREATE UNIQUE INDEX fails if duplicates already exist, so find them first:

SELECT lower(email) AS email, array_agg(id ORDER BY created_at) AS user_ids FROM users GROUP BY lower(email) HAVING count(*) > 1;

Each row lists the accounts that collide, oldest first. Deciding which account survives is a product decision (often the oldest, with data from the others merged into it), so handle these by hand or with a one-off script before the migration runs. On large tables, build the index with CREATE UNIQUE INDEX CONCURRENTLY outside a transaction to avoid blocking writes while it builds.

Case-insensitive emails with Encore

Encore

Encore is a backend framework with built-in infrastructure, and the database and its migrations are declared in the same Go service as the signup endpoint. The Postgres database below gets the lower() index from a regular migration file, and Encore reports constraint failures with typed error codes the handler can map to a clean API error.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

-- users/migrations/1_create_users.up.sql CREATE TABLE users ( id BIGSERIAL PRIMARY KEY, email TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE UNIQUE INDEX users_email_lower ON users (lower(email));
// users/users.go package users import ( "context" "errors" "strings" "encore.dev/beta/errs" "encore.dev/storage/sqldb" "encore.dev/storage/sqldb/sqlerr" ) var db = sqldb.NewDatabase("users", sqldb.DatabaseConfig{Migrations: "./migrations"}) type SignupParams struct { Email string } type User struct { ID int64 Email string } //encore:api public method=POST path=/users func Signup(ctx context.Context, p *SignupParams) (*User, error) { email := strings.TrimSpace(p.Email) u := &User{Email: email} err := db.QueryRow(ctx, `INSERT INTO users (email) VALUES ($1) RETURNING id`, email).Scan(&u.ID) if sqldb.ErrCode(err) == sqlerr.UniqueViolation { return nil, &errs.Error{Code: errs.AlreadyExists, Message: "an account with this email already exists"} } else if err != nil { return nil, err } return u, nil } type LookupParams struct { Email string `query:"email"` } //encore:api private method=GET path=/users/by-email func ByEmail(ctx context.Context, p *LookupParams) (*User, error) { u := &User{} err := db.QueryRow(ctx, `SELECT id, email FROM users WHERE lower(email) = lower($1)`, strings.TrimSpace(p.Email)).Scan(&u.ID, &u.Email) if errors.Is(err, sqldb.ErrNoRows) { return nil, &errs.Error{Code: errs.NotFound, Message: "user not found"} } else if err != nil { return nil, err } return u, nil }

encore run starts Postgres locally and applies the migration. A second signup with different capitalization should then return already_exists. The stored email keeps the capitalization the user typed, which matters for display and for the rare mail server that does treat the local part as case-sensitive. To switch to citext later, the migration adds CREATE EXTENSION IF NOT EXISTS citext, which the Encore Postgres image ships with, and changes the column type.

An agent that adds another lookup by email tends to write WHERE email = $1, and keeping the rule in the schema means the test for duplicate signups fails locally the moment someone breaks it.

Best fit: Apps that want one account per address enforced by the database they run in their own cloud account, with signup errors their clients can act on.

Frequently asked questions

How do you make a unique constraint case-insensitive in Postgres?

Create a unique index on lower(email), for example CREATE UNIQUE INDEX users_email_lower ON users (lower(email)). Postgres then rejects a second row whose lowercased email matches an existing one, and lookups that filter on lower(email) use the same index.

Should I use citext for email columns?

It works, and it makes every comparison on the column case-insensitive without changing queries. The Postgres documentation now suggests nondeterministic collations instead, and a lower() index is the most portable option, so citext is a reasonable choice rather than the default one.

Does a lower() index work with WHERE email = ?

No. The index is built on the expression lower(email), so only queries that filter on lower(email) can use it. A plain WHERE email = $1 falls back to another index or a sequential scan and still compares case-sensitively.

How do I enforce case-insensitive emails with Encore?

Add the unique index on lower(email) in an Encore migration, look users up with WHERE lower(email) = lower($1), and map sqlerr.UniqueViolation to an AlreadyExists error in the signup endpoint. encore run starts Postgres locally and applies the migration.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders