SQL concatenation and implicit casts
What happens when a number or date meets a string operator depends on the engine: a conversion error, silent arithmetic, or a session-dependent date format.
- カテゴリ
- Strings
- Returns
string- In this category
- 24 of 172
構文
'x' || CAST(n AS text) -- always safe
エンジンサポート
| エンジン | Support | メモ |
|---|---|---|
| SQL Server | はい | Supported under this name. |
| PostgreSQL | はい | Supported under this name. |
| MySQL | はい | Supported under this name. |
| SQLite | はい | Supported under this name. |
| Oracle | はい | Supported under this name. |
例
SQL Server
SELECT CONCAT('Order ', 42) AS ok; -- Order 42
MySQL
SELECT 'Total: ' + 5 AS arith, CONCAT('Total: ', 5) AS joined;
-- 5, Total: 5
Oracle
SELECT 'Due: ' || TO_CHAR(due_date, 'YYYY-MM-DD') AS due FROM tasks;
知っておくと便利なこと
- SQL Server: + keeps the higher-precedence type, so 'Age: ' + 42 is a conversion error, while '5' + 1 is 6. CONCAT converts every argument to text cleanly.
- MySQL and SQLite: + is arithmetic on strings; 'Total: ' + 5 is 5, because 'Total: ' casts to 0. There is no string +.
- Oracle: number || string works, but dates pick up NLS_DATE_FORMAT, so the same query shows different date formats per session. TO_CHAR explicitly.
- PostgreSQL: || works when one side is text ('x' || 1 is 'x1') but 1 || 2 is an error. Dates print per the DateStyle setting, so use to_char for a fixed format.
Questions about Implicit casts in concatenation
Why does my concatenation throw a conversion error?
On SQL Server, + with a number tries to convert the string side to a number (int outranks varchar). CONCAT or an explicit CAST avoids the trap.
Why did my date concatenate as '01-AUG-26'?
That is Oracle's default NLS_DATE_FORMAT (DD-MON-RR) at work; PostgreSQL follows DateStyle instead. TO_CHAR with an explicit pattern, or CONVERT with a style on SQL Server, pins it down.
Is there one portable way to join strings and numbers?
CAST the non-string operand explicitly, then use the engine's string joiner. Casting first makes the intent independent of engine precedence rules.
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, MySQL, SQLite, 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.