110 words
1 minute
Splitting on commas in SQLite
Anubhav Gain
2024-05-04

Splitting on commas in SQLite#

I had an input string in x,y,z format and I needed to split it into three separate values in SQLite. I managed to do it using a confusing combination of the instr() and substr() functions.

Here’s what I came up with:

with comma_locations as (
select instr(:path, ',') as first_comma,
instr(:path, ',') + instr(substr(:path, instr(:path, ',') + 1), ',') as second_comma
), variables as (
select
substr(:path, 0, first_comma) as first,
substr(:path, first_comma + 1, second_comma - first_comma - 1) as second,
substr(:path, second_comma + 1) as third
from comma_locations
)
select * from variables

Against an input of x12,y1234,z12345 it returns this:

firstsecondthird
x12y1234z12345

Here’s a live demo of the query.

Splitting on commas in SQLite
https://mranv.pages.dev/posts/splitting-on-commas-in-sqlite/
Author
Anubhav Gain
Published at
2024-05-04
License
CC BY-NC-SA 4.0