// strings reference

SQL REGEXP_SPLIT_TO_ARRAY function

Splits a string wherever a regular expression matches and returns the pieces as a text array.

Catégorie
Strings
Returns
text[]
In this category
107 of 172

Syntaxe

regexp_split_to_array(string, pattern [, flags])

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Not built in No arrays; SQL Server 2025's REGEXP_SPLIT_TO_TABLE returns rows.
PostgreSQL Oui Supported under this name.
MySQL Not built in No regex split; JSON_TABLE or SUBSTRING_INDEX chains.
SQLite Not built in No regex split.
Oracle Not built in No direct equivalent; REGEXP_SUBSTR walks.

Exemples

PostgreSQL

SELECT regexp_split_to_array('a, b; c', '[,;][ ]*') AS parts;  -- {a,b,c}

PostgreSQL

SELECT unnest(regexp_split_to_array(line, '\s+')) AS word
FROM lines;

Bon à savoir

  • The separator is a regex, so '[,;]\s*' splits on a comma or semicolon plus any following whitespace. With standard_conforming_strings on (the default), backslashes in a plain literal reach the regex engine unchanged.
  • Zero-length matches split between characters: regexp_split_to_array('abc', 'x*') is {a,b,c}. Only zero-length matches at the very start or end, or right after a previous match, are ignored.
  • A leading or trailing delimiter produces an empty first or last element: regexp_split_to_array(',a', ',') is {"",a}.

Questions about REGEXP_SPLIT_TO_ARRAY

When should I use string_to_array instead?

When the separator is a fixed string. string_to_array is faster and has no regex escaping to get wrong.

How do I split on any whitespace?

Use '\s+' or the POSIX class '[[:space:]]+', then unnest the array if you need rows.

Why does my array contain empty strings?

The input had adjacent delimiters or a delimiter at either end. Trim the string first, use a pattern with + so runs count as one separator, or filter empties after unnest.

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: PostgreSQL.

// 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.