// SQL snippet

Split a comma-separated field into rows in SQL

Tags stored as a comma-separated blob need one row per tag for counting, joining and filtering.

Main statement
SQL Server
Также охватывает
PostgreSQL Oracle

The task

The tags column holds 'wifi,pool,pet-friendly' in one cell. To count the most common tags you need each value on its own row.

The snippet

Written for SQL Server. Versions for PostgreSQL and Oracle are under Variations.

SQL Server
SELECT id, LTRIM(RTRIM(value)) AS tag
FROM amenities
CROSS APPLY STRING_SPLIT(tags_csv, ',');

Как это работает

STRING_SPLIT returns one row per comma-separated value. CROSS APPLY multiplies each source row by its values, so the id stays attached to every tag. STRING_SPLIT needs SQL Server 2016+ at compatibility level 130 or higher, has no TRIM option, and before SQL Server 2022 (which added the enable_ordinal argument) does not report each value's position.

Variations

PostgreSQL

PostgreSQL
SELECT a.id, btrim(t) AS tag
FROM amenities a, unnest(string_to_array(a.tags_csv, ',')) AS t;

Oracle

Oracle
SELECT a.id,
       TRIM(REGEXP_SUBSTR(a.tags_csv, '[^,]+', 1, LEVEL)) AS tag
FROM amenities a
CONNECT BY LEVEL <= REGEXP_COUNT(a.tags_csv, '[^,]+')
    AND PRIOR a.id = a.id
    AND PRIOR SYS_GUID() IS NOT NULL;

Questions that come up

Can I split on a multi-character delimiter?

Not with STRING_SPLIT: its separator must be exactly one character in every version, including 2022 and 2025. PostgreSQL's string_to_array accepts any delimiter string and Oracle's REGEXP_SUBSTR any pattern; on SQL Server, REPLACE the multi-character delimiter with a single rare character first.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.