I am using REGEXP_SUBSTR()
to return the nth value from a comma-separated list. This works fine when all values are present, but fails if an item is null. Here is an example that works where all values are present and I am selecting the 2nd occurrence of 1 or more characters that are not a comma:
SQL> select REGEXP_SUBSTR('1,2,3,4,5,6', '[^,]+', 1, 2) data
2 from dual;
D
-
2
But when the second value is null, I am really getting the third item in the list, which of course really is the 2nd occurrence of 1 or more characters that are not a comma. However, I need it to return NULL as the 2nd item is empty:
SQL> select REGEXP_SUBSTR('1,,3,4,5,6', '[^,]+', 1, 2) data
2 from dual;
D
-
3
If I change the regex to allow for zero or more characters instead of 1 or more, it also fails for numbers past the null:
SQL> select REGEXP_SUBSTR('1,,3,4,5,6', '[^,]*', 1, 4) data
2 from dual;
D
-
3
I need to allow for the null but can't seem to get the syntax right. Logically I need to return what is before the nth occurrence of a comma whether data is present or not (and allow for the last value also). Any ideas?