SQL TRANSLATE function
Maps each character of a from-set to the character at the same position in a to-set. One call replaces a chain of single-character REPLACEs.
- Catégorie
- Strings
- Returns
string- In this category
- 36 of 172
Syntaxe
TRANSLATE(string, from_chars, to_chars)
Prise en charge des moteurs
| Moteur | Support | Notes |
|---|---|---|
| SQL Server | Oui | from SQL Server 2017 |
| PostgreSQL | Oui | translate(), in every supported version |
| MySQL | Not built in | No built-in equivalent. |
| SQLite | Not built in | No built-in equivalent. |
| Oracle | Oui | Supported under this name. |
Exemples
SQL Server
SELECT TRANSLATE('2[3]4', '[]', '()') AS t; -- 2(3)4
PostgreSQL
SELECT TRANSLATE('12345', '143', 'ax') AS t; -- a2x5
Oracle
SELECT TRANSLATE('23423', '12345', 'abcd') AS t FROM dual; -- bcdbc: 2->b, 3->c, 4->d
Bon à savoir
- Positional, not sequential: TRANSLATE('2[3]4', '[]', '()') gives 2(3)4. It cannot map one character to two, and it is not a substring replace; that is REPLACE.
- Length mismatch splits the engines: PostgreSQL and Oracle delete from-chars that have no partner in to_chars, while SQL Server refuses with error 9828 unless both lists are the same length. Oracle needs at least one mapped character, because an empty to-list is NULL there: TRANSLATE(s, '-', '') returns NULL, TRANSLATE(s, 'x-', 'x') deletes the dashes.
- Unavailable on MySQL and SQLite: nested REPLACE (which runs in order and can re-map already-replaced text) is the workaround; TRANSLATE avoids that cascade.
- For full substring swaps, or patterns, use REPLACE or REGEXP_REPLACE; TRANSLATE is strictly character-for-character.
- Case: PostgreSQL and Oracle match exactly, but SQL Server follows the collation, so under a case-insensitive one TRANSLATE('ABC', 'abc', 'xyz') returns 'xyz'.
Questions about TRANSLATE
What is the difference between TRANSLATE and REPLACE?
REPLACE swaps whole substrings left to right; TRANSLATE maps single characters positionally and can never turn one character into two: TRANSLATE('ab', 'a', 'xy') gives 'xb', not 'xyb'.
Why is TRANSLATE not available in MySQL?
It never shipped there, nor in SQLite. Chain REPLACE calls for a known set, but remember sequential REPLACE can re-process earlier replacements; TRANSLATE has no cascade.
Can TRANSLATE delete characters?
On PostgreSQL and Oracle, yes. Leave them unmatched: TRANSLATE(s, 'abc', 'ab') deletes every 'c'. SQL Server rejects unequal lists, so delete with REPLACE(s, 'c', '') there.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, Oracle.
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.