// strings reference

SQL CONCAT_NULL_YIELDS_NULL setting

Controls whether 'a' + NULL is NULL on SQL Server. It only affects the + operator; CONCAT and CONCAT_WS always skip NULLs regardless.

類別
Strings
Returns
setting
In this category
21 of 172

語法

SET CONCAT_NULL_YIELDS_NULL { ON | OFF }

引擎支援

引擎Support備註
SQL Server 是 Supported under this name.
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

SET CONCAT_NULL_YIELDS_NULL ON;
SELECT 'a' + NULL AS result;  -- NULL

SQL Server

SET CONCAT_NULL_YIELDS_NULL OFF;
SELECT 'a' + NULL AS result;  -- a

SQL Server

SELECT CONCAT('a', NULL) AS always_safe;  -- a

小知識

  • The setting is deprecated: a future version will always be ON. The ODBC and OLE DB drivers and SqlClient switch it ON when they connect, so in practice nearly every session is ON whatever the database default says.
  • CONCAT and CONCAT_WS ignore the setting and always treat NULL as empty; prefer them and stop depending on the flag.
  • It can be set per database (ALTER DATABASE ... SET, default OFF) or per session, and the session value wins. A connection that never sets it, or a script that runs SET ... OFF, is where results start to differ.
  • Write NULL-safe code instead: ISNULL(col, ''), COALESCE, or CONCAT.

Questions about CONCAT_NULL_YIELDS_NULL

Why does the same query return NULL in one tool and 'a' in another?

CONCAT_NULL_YIELDS_NULL differs per connection. Standard drivers turn it ON; a client that skips that, or a stored procedure or script that sets it OFF, falls back to different behaviour. Check with SELECT SESSIONPROPERTY('CONCAT_NULL_YIELDS_NULL').

Does CONCAT_NULL_YIELDS_NULL affect CONCAT?

No. CONCAT and CONCAT_WS always skip NULLs. The setting only governs the + operator and +=.

Should I turn it OFF in my database?

No. It is deprecated and future SQL Server will force ON. Make the SQL NULL-safe with CONCAT, ISNULL or COALESCE instead.

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.