Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL Error 42P21: Collation Mismatch Fix

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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.utf8 versus C).
  • A backup or a tested restore path before you alter column types on production data.

Step-by-Step

  1. Read the full error message. PostgreSQL reports 42P21 as collation mismatch and normally adds detail such as collation "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 in psql so you see the DETAIL line.
  2. 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 with SELECT datcollate, datctype FROM pg_database WHERE datname = current_database(); and the server default with SHOW 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.
  3. 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.
  4. 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; or SELECT * FROM t ORDER BY name COLLATE "C"; Use the collation name exactly as it appears in pg_collation; you can list available ones with SELECT collname FROM pg_collation;. Quote names that contain uppercase letters or dots.
  5. 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";
  6. 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_table in psql.
  7. 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.
  8. 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 COLLATE to 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 C and POSIX behave like a language collation. They sort bytewise, which changes ORDER BY results 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 INDEX and UNIQUE constraints store collation information; after an ALTER COLUMN, recreate them rather than assuming they still apply.
  • Mixing a database created with LC_COLLATE=C and one created with a locale such as en_US.UTF-8 and expecting cross-database comparisons to work without conversion.

Tips

  • Standardise new columns by declaring COLLATE explicitly in CREATE 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 citext or a functional index with lower() 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.