Write a query to display character after comma's

Input:

VV,XXX,YYYY,ZZZZZ

Extract First Value

SELECT REGEXP_SUBSTR(
         'VV,XXX,YYYY,ZZZZZ',
         '[^,]+',
         1,
         1
       ) col
FROM dual;

Output:

COL
-----
VV

Extract Second Value

SELECT REGEXP_SUBSTR(
         'VV,XXX,YYYY,ZZZZZ',
         '[^,]+',
         1,
         2
       ) col
FROM dual;

Output:

COL
-----
XXX

Extract Third Value

SELECT REGEXP_SUBSTR(
         'VV,XXX,YYYY,ZZZZZ',
         '[^,]+',
         1,
         3
       ) col
FROM dual;

Output:

COL
-----
YYYY

Extract Fourth Value

SELECT REGEXP_SUBSTR(
         'VV,XXX,YYYY,ZZZZZ',
         '[^,]+',
         1,
         4
       ) col
FROM dual;

Output:

COL
-----
ZZZZZ

How It Works

The regular expression [^,]+ searches for one or more characters that are not commas. The last parameter of REGEXP_SUBSTR specifies which occurrence should be returned.

1st occurrence  →  VV
2nd occurrence  →  XXX
3rd occurrence  →  YYYY
4th occurrence  →  ZZZZZ

Therefore, by changing the occurrence parameter from 1 to 4, we can extract each value from the comma-separated string individually.

No comments:

Post a Comment