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.
Code
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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables or CTEs does it reference?
- `products`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.