// strings reference

SQL MySQL CHARSET and COLLATION functions

Introspection for strings: which charset and collation does this value carry right now? Check it before converting or debugging a comparison.

Kategorie
Strings
Returns
string
In this category
82 of 172

Syntax

CHARSET(string)
COLLATION(string)

Each block is a separate form. The support table and the examples show which engine takes which.

Engine-Unterstützung

EngineSupportNotizen
SQL Server Not built in No built-in equivalent.
PostgreSQL Not built in No built-in equivalent.
MySQL Ja Supported under this name.
SQLite Not built in No built-in equivalent.
Oracle Not built in No built-in equivalent.

Beispiele

MySQL

SELECT CHARSET('x') AS cs, COLLATION('x') AS col;

MySQL

SELECT CHARSET(CHAR(160)) AS cs;  -- binary

Gut zu wissen

  • The classic result: CHARSET(CHAR(160)) is binary; MySQL's CHAR() returns raw bytes unless you add USING, and then the bytes must be valid: CHAR(0xC2A0 USING utf8mb4) is an NBSP, CHAR(160 USING utf8mb4) is NULL.
  • Literals inherit the connection charset, so the same query shows different charsets per client. SET NAMES changes it for the session.
  • Column charset vs literal charset mismatches force conversions at compare time, which silently break index use.
  • CHARSET returns the string's charset; COLLATION its collation. A utf8mb4 string can carry any utf8mb4_* collation, which decides its sorting and padding rules.

Questions about CHARSET / COLLATION

Why is my CHAR(160) comparison failing?

CHAR(160) produced the single binary byte 0xA0, which never matches the two-byte UTF-8 NBSP in utf8mb4 text. Use CHAR(0xC2A0 USING utf8mb4); CHARSET() confirms the diagnosis.

Do CHARSET() and COLLATION() look at the column or the value?

The value. Pass a column and you get its charset/collation; pass a literal and you get the connection's. That asymmetry is the debugging value.

Do other engines have this?

PostgreSQL exposes encoding via server settings rather than per-value functions; SQL Server via COLLATIONPROPERTY on named collations. MySQL's per-value pair is unique.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: MySQL.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.