String Concatenation Chain With Format

Build display strings with chained ||, the concat and concat_ws functions, and format() placeholders — each handles NULL and separators differently.

SqlData Fetching

Code

snippet
SELECT
    product_id,
    -- || 链:任何一环是 NULL 整体塌缩
    sku || ' / ' || variant AS sku_variant,
    -- concat:NULL 当空串,但分隔符要自己写
    concat(sku, ' / ', variant) AS concat_version,
    -- concat_ws:跳过 NULL 且自动插分隔符,适合可选字段拼接
    concat_ws(' / ', sku, variant, color) AS concat_ws_version,
    -- format:占位符模板,%s 逐个填充,%I/%L 转义用于动态 SQL
    format('%s (%s)', sku, COALESCE(color, 'std')) AS formatted
FROM products;

-- concat_ws 第一个参数是分隔符,其余可全部为 NULL 时结果是空串
SELECT concat_ws('-', NULL, NULL) AS all_null_empty;
-- format 里输出字面百分号要用 %% 转义
SELECT format('%s%% off', 20) AS percent_literal;

How it works

Several statements share this file — SELECT, with products among the objects involved.

Putting it to use

Run it in the products database context.

Core lines

SELECT
    product_id,
    sku || ' / ' || variant AS sku_variant,
    concat(sku, ' / ', variant) AS concat_version,
    concat_ws(' / ', sku, variant, color) AS concat_ws_version,
    format('%s (%s)', sku, COALESCE(color, 'std')) AS formatted
FROM products;
SELECT concat_ws('-', NULL, NULL) AS all_null_empty;
SELECT format('%s%% off', 20) AS percent_literal;

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`products`.