// strings reference

SQL + concatenation operator

SQL Server's traditional concatenation operator, also available as += for appending in UPDATE. Two sharp edges: NULLs and implicit casts.

カテゴリ
Strings
Returns
string
In this category
17 of 172

構文

'a' + 'b'
SET @s += 'more'

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

エンジンサポート

エンジンSupportメモ
SQL Server はい + is arithmetic or concatenation depending on operand types
PostgreSQL Not built in No built-in equivalent.
MySQL Not built in No built-in equivalent.
SQLite Not built in No built-in equivalent.
Oracle Not built in No built-in equivalent.

例

SQL Server

SELECT 'Order ' + CAST(42 AS varchar(10)) AS label;  -- Order 42

SQL Server

SELECT NULL + 'a' AS poisoned;  -- NULL

SQL Server

UPDATE notes SET body += ' (reviewed)' WHERE id = 7;

知っておくと便利なこと

  • NULL + 'a' is NULL. CONCAT and CONCAT_WS skip NULLs instead; CONCAT_NULL_YIELDS_NULL controls the + behaviour but is deprecated.
  • The higher-precedence type wins: '5' + 1 is 6 (int converts the string), 'Age: ' + 42 throws a conversion error. CONCAT(42) converts cleanly.
  • 'abc' + REPLICATE('x', 9000) silently truncates at 8000 bytes unless the operands are varchar(max)/nvarchar(max).
  • Other engines do not use + for strings at all: in MySQL and SQLite, 'a' + 1 is arithmetic (and 'a' casts to 0).

Questions about + / +=

Why does NULL + 'text' return NULL?

That is the SQL Server default: a NULL operand poisons the + result. Use CONCAT or CONCAT_WS, which treat NULL as an empty string, or ISNULL(col, '') each operand.

Why does 'Age: ' + 42 fail?

int has higher type precedence than varchar, so SQL Server tries to convert 'Age: ' to a number. CONCAT('Age: ', 42) or CAST(42 AS varchar) fixes it.

Do other databases use + to join strings?

No. PostgreSQL, Oracle and SQLite use ||, MySQL uses CONCAT. In MySQL and SQLite, + between strings is arithmetic addition.

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: SQL Server.

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