PostgreSQL Error 42P21: Collation Mismatch Fix
In this article
PostgreSQL error 42P21 (collation mismatch) means two strings you are comparing, joining, sorting, or inserting were created with different collation rules, and PostgreSQL will not guess which one should win. The fix is to make both sides use the same collation: either add an explicit COLLATE clause to the query, change the column's collation with ALTER TABLE ... ALTER COLUMN ... TYPE ... COLLATE ..., or recreate the object with a matching collation. You do not need to reinstall PostgreSQL or restart the server.
What You'll Need
- A PostgreSQL user with permission to read the affected tables and, for schema changes, ownership of the table or superuser rights.
- A client such as
psql, pgAdmin, or your application's SQL console. - The exact error text, which usually names the collations involved (for example
en_US.utf8versusC). - A backup or a tested restore path before you alter column types on production data.
Step-by-Step
- Read the full error message. PostgreSQL reports 42P21 as
collation mismatchand normally adds detail such ascollation "en_US.utf8" for encoding "UTF8" is not compatible with collation "C"or names the two expressions that conflict. Write down both collations. If the message is vague, reproduce the failing statement inpsqlso you see the DETAIL line. - Identify where each collation comes from. Run
SELECT table_schema, table_name, column_name, collation_name FROM information_schema.columns WHERE collation_name IS NOT NULL AND table_name = 'your_table';to list column collations. Also check the database default withSELECT datcollate, datctype FROM pg_database WHERE datname = current_database();and the server default withSHOW lc_collate;. A common cause is a column created without an explicit collation inheriting the database default, then being compared to a literal or column from another database that uses a different default. - Decide whether the fix belongs in the query or the schema. If the mismatch is a one-off report or an ad-hoc join, fix the query. If the same error keeps returning from application code, fix the column so every query agrees.
- Fix it in the query with an explicit COLLATE clause. Add
COLLATE "en_US.utf8"(or whichever collation the other side uses) to the expression that differs. For example:SELECT * FROM a JOIN b ON a.name COLLATE "en_US.utf8" = b.name;orSELECT * FROM t ORDER BY name COLLATE "C";Use the collation name exactly as it appears inpg_collation; you can list available ones withSELECT collname FROM pg_collation;. Quote names that contain uppercase letters or dots. - Fix it in the schema by changing the column type. Back up the table first. Then run
ALTER TABLE your_table ALTER COLUMN your_column TYPE text COLLATE "en_US.utf8";This rewrites the table and takes an exclusive lock, so schedule it for a maintenance window on large tables. For a varchar column, keep the length:ALTER TABLE your_table ALTER COLUMN your_column TYPE varchar(255) COLLATE "en_US.utf8"; - Handle indexes and constraints. Changing a column's collation invalidates indexes and unique constraints that depend on it. PostgreSQL will usually refuse or rebuild dependent objects; if it errors, drop and recreate the affected indexes after the type change. Check with
\d your_tableinpsql. - Re-run the failing statement. If it succeeds, test the application path that triggered the error, not just the isolated query, because prepared statements and ORMs can cache the old plan.
- If the mismatch spans databases, you cannot compare columns across databases directly in one query. Use
dblink,postgres_fdw, or export and import with matching collations. When using foreign tables, set the column collation on the foreign table definition to match the local side.
Common Mistakes
- Adding
COLLATEto only one side of a comparison when the other side is a literal. Literals inherit the database default, so you may need'text' COLLATE "C"explicitly. - Assuming
CandPOSIXbehave like a language collation. They sort bytewise, which changesORDER BYresults and unique-index behaviour for case and accents. - Changing a column's collation on a large table during peak hours. The rewrite locks the table and can take a long time.
- Forgetting that
CREATE INDEXandUNIQUEconstraints store collation information; after anALTER COLUMN, recreate them rather than assuming they still apply. - Mixing a database created with
LC_COLLATE=Cand one created with a locale such asen_US.UTF-8and expecting cross-database comparisons to work without conversion.
Tips
- Standardise new columns by declaring
COLLATEexplicitly inCREATE TABLE, so future queries do not depend on the database default. - Use
SELECT * FROM pg_collation WHERE collname LIKE '%utf8%';to see which locale-based collations are installed on the server. - For case-insensitive matching, prefer
citextor a functional index withlower()over switching collations mid-query, which can prevent index use. - Test collation changes on a staging copy first; sort order and uniqueness can change for accented and uppercase characters.
- Keep the original collation name from the error message; guessing a similar locale name often produces a different error.
Troubleshooting
If the error persists after adding COLLATE, confirm you edited every conflicting expression, including WHERE, JOIN, ORDER BY, GROUP BY, and UNION branches. If ALTER TABLE fails with a dependency error, list dependent objects with \d+ your_table and drop the indexes or views first, then recreate them. If the server reports that the collation does not exist, query pg_collation and use an installed name; creating a new OS locale may require operating-system packages and a PostgreSQL restart. If only some clients fail, check whether they connect to a different database with a different default collation. If the error appears inside a function, add COLLATE inside the function body or declare the parameter with an explicit collation. When a schema change is too risky, the safe fallback is to cast both sides to text and compare with an explicit collation in the query, accepting that indexes on the original column may not be used.
Frequently Asked Questions
What causes PostgreSQL error 42P21?
It occurs when an operation combines strings with different collations, such as joining a column using the database default to one with an explicit COLLATE "C", or comparing columns from databases created with different locales.
Can I fix 42P21 without changing the table?
Yes. Add an explicit COLLATE clause to the conflicting expression in the query. This is the least invasive fix and is suitable for reports and one-off joins.
Does changing a column collation lock the table?
Yes. ALTER TABLE ... ALTER COLUMN ... TYPE ... COLLATE ... rewrites the table and takes an exclusive lock. Plan it for low-traffic periods and back up first.
Will changing collation affect sorting and unique indexes?
It can. Collations define sort order and equality for text, so results of ORDER BY and uniqueness checks may change. Recreate dependent indexes and test on staging.
Why does the error mention encoding as well as collation?
Some collations are only valid for certain encodings. A collation created for UTF-8 cannot be used with a LATIN1 database, so PostgreSQL reports both the collation and encoding in the detail message.
Can I compare columns across two databases directly?
Not in a single query. Use postgres_fdw, dblink, or export and import data, and make the collations match on both sides before comparing.