Introduction
Extracting individual values from comma-separated strings is a common requirement in data analysis. In SQLite, there's no straightforward equivalent to SQL's SubString() function, making this task somewhat challenging. However, with the help of Common Table Expressions (CTEs), we can create an efficient and intuitive solution.
The Solution: Using a CTE
A CTE allows us to define and name a temporary result set. By leveraging recursion within a CTE, we can iteratively parse the comma-separated string, extracting each value one at a time.
The CTE declaration in our case looks something like this:
WITH split(word, csv) AS ( -- 'initial query' (see SQLite docs linked above) SELECT '', 'Auto,A,1234444'||',' -- 'recursive query' UNION ALL SELECT substr(csv, 0, instr(csv, ',')), substr(csv, instr(csv, ',') + 1) FROM split WHERE csv != '' )
In the 'initial query,' we create a starting point for the recursive portion of the CTE. We specify an empty string for 'word' and append a comma-separated string with an extra comma to indicate the end of the CSV.
The 'recursive query' is where the magic happens. It uses the instr() function to find the position of the first comma in the 'csv' field. Then, it splits the 'csv' field using substr() into 'word' and the remaining 'csv' portion.
Recursion is used to continue splitting the remaining 'csv' portion until there are no more commas left, effectively extracting all the comma-separated values.
Retrieving the Split Values
Once the CTE has defined the split values, we can retrieve them using a simple query:
SELECT word FROM split WHERE word!='';
The WHERE clause filters out the empty strings that represent the initial and terminal values.
Output and Benefits
The output of the query is as follows:
Auto A 1234444
This approach provides several benefits:
The above is the detailed content of How Can I Easily Split Comma-Separated Values in SQLite Using Common Table Expressions?. For more information, please follow other related articles on the PHP Chinese website!