SQL CONCAT_WS function
Joins strings with a separator between each pair, collapsing the CONCAT(a, ', ', b, ', ', c) pattern into one call that drops NULL values along with their separators.
- 类别
- Strings
- Returns
string- In this category
- 15 of 172
语法
CONCAT_WS(separator, value1, value2, ...)
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| SQL Server | 是 | from SQL Server 2017 |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | 是 | Supported under this name. |
| SQLite | 是 | from SQLite 3.44 |
| Oracle | Not built in | No built-in equivalent. |
示例
Any engine
SELECT CONCAT_WS(' ', first_name, last_name) AS full_name
FROM users;
MySQL
SELECT CONCAT_WS(', ', NULL, 'Paris', 'France') AS place; -- Paris, France
Oracle
SELECT CONCAT(CONCAT(city, ', '), country) AS place FROM addresses;
值得了解
- NULL values are skipped on SQL Server, PostgreSQL, MySQL and SQLite. A NULL separator returns NULL on PostgreSQL, MySQL and SQLite, but SQL Server treats it as '' and returns the values run together.
- Empty strings are not skipped: CONCAT_WS(', ', 'a', '', 'c') keeps the gap, so '' and NULL behave differently.
- Oracle has no CONCAT_WS, up to and including 23ai. Chain || with the separator typed out, and use CASE or NVL2 to drop a part and its separator when the value is NULL.
- Numbers join using their default text format; TO_CHAR, CAST or FORMAT first when the look matters.
Questions about CONCAT_WS
Does CONCAT_WS skip NULLs?
Yes, every NULL value is dropped with no stray separator, on SQL Server, PostgreSQL, MySQL and SQLite. Empty strings are kept, which is the main difference to watch for.
Why does my result come back NULL?
The separator itself is NULL, not the values. CONCAT_WS(NULL, 'a', 'b') is NULL on PostgreSQL, MySQL and SQLite. SQL Server is the exception: it treats a NULL separator as '' and returns 'ab', and when every value is NULL it returns '' rather than NULL.
Is CONCAT_WS in Oracle?
No. Before 23ai Oracle's CONCAT takes exactly two arguments, so multi-part joins mean nested CONCAT or || chains with the separator written out. 23ai's CONCAT accepts more arguments but still has no separator form.
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.
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.