// conversion reference

SQL CONVERT character set

This CONVERT changes encoding, not type. MySQL writes USING; Oracle puts the destination set first; PostgreSQL works on bytea and puts the source first.

類別
Conversion
Returns
text or bytea
In this category
21 of 39

語法

CONVERT(expr USING charset)  -- MySQL
CONVERT(text, dest_charset [, source_charset])  -- Oracle
convert(bytea, src, dest)  -- PostgreSQL

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

引擎支援

引擎Support備註
SQL Server Not built in no charset conversion; collations govern code pages
PostgreSQL Different name or syntax convert(bytea, src, dest) plus convert_to/convert_from
MySQL 是 Supported under this name.
SQLite Not built in text is UTF-8 throughout; nothing to convert
Oracle 是 Supported under this name.

範例

MySQL

SELECT CONVERT(name USING utf8mb4) AS name
FROM legacy_users;

PostgreSQL

SELECT convert_to('café', 'LATIN1') AS latin1_bytes,
       convert_from(convert_to('café', 'LATIN1'), 'LATIN1') AS back;

Oracle

SELECT CONVERT('café', 'US7ASCII', 'AL32UTF8') AS ascii_only FROM dual;

小知識

  • Argument order is opposite between the two three-argument forms: Oracle's CONVERT(text, 'US7ASCII', 'AL32UTF8') is destination then source, PostgreSQL's convert(bytes, 'UTF8', 'LATIN1') is source then destination.
  • Characters missing from the target set are replaced, not rejected: Oracle's CONVERT('café', 'US7ASCII') returns 'cafe', and MySQL substitutes '?'. Converting emoji to latin1 loses them for good.
  • MySQL data lives in the column's charset: CONVERT ... USING changes the value in flight, usually for a comparison or cross-table insert. Changing the column itself is ALTER TABLE ... CONVERT TO CHARACTER SET.

Questions about CONVERT (charset)

How do I change a column's charset?

ALTER TABLE t CONVERT TO CHARACTER SET utf8mb4 on MySQL. CONVERT ... USING only re-encodes the value in a query; the column definition is a separate operation.

Is this the same CONVERT as type conversion?

No. SQL Server's CONVERT casts types; MySQL's CONVERT does both (CONVERT(x, CHAR) casts, CONVERT(x USING cs) re-encodes); PostgreSQL's and Oracle's only re-encode. The argument shape tells you which one you are reading.

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: PostgreSQL, MySQL, Oracle.

// 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.