Cookbook recipe

Character encoding and collation basics

Applies to PostgreSQL 13–17 Last reviewed May 2026 Grounded in source
Estimated investigation4 min

Scenario

Sorting looks wrong, or you hit "invalid byte sequence for encoding". Encoding and collation decide how text is stored and ordered. Diagnose it Check database encoding and collation: SELECT datname, pg_encoding_to_char(encoding), datcollate, datctype FROM pg_database; Why…

Investigation Path

Sorting looks wrong, or you hit “invalid byte sequence for encoding”. Encoding and collation decide how text is stored and ordered.

Diagnose it

Check database encoding and collation:

SELECT datname, pg_encoding_to_char(encoding), datcollate, datctype
FROM pg_database;

Why it happens

Encoding (usually UTF8) defines which byte sequences are valid text. Collation defines sort/compare order and case rules. A mismatch between client data and server encoding causes byte-sequence errors; collation differences change ORDER BY results.

This is a Pro lesson

Get every Learning Pathway and cookbook recipe — grounded in PostgreSQL source code, with diagnostics, fixes, and prevention for each topic.

Continue this lesson to learn:

  • How to fix it
  • Prevent it next time
  • Related & next steps
  • All 36 Learning Pathway lessons
  • 170+ cookbook recipes
  • Source-grounded diagnostics & fixes

Secure checkout Cancel anytime Source-grounded

Career Impact

This scenario builds production judgment and operational confidence under pressure.

Open Career Dashboard →

Keep going

Related & next steps

Was this helpful?

← All cookbook recipes