I want to split comma-separated String
inside SQLite database
Example: I have a Category
column in 1 of my table.
|Category |
|------------------------------|
|Auto,A,1234444 |
|Auto,B,2345444 |
|Electronincs,Computer,33443434|
I want to get only a single value from above string.
value1: Auto
value2: A
value3: 1234444
I have searched a lot on Google; I found a way to replace comma using Replace()
and Trim()
. However, I want to get an easier approach.
In SQL, there is provide SubString()
. But in SQLite, there is no such function. How to solve it?
EDIT: I have checked substr()
. But, this function can be set maximum length to get the string value, and my string value doesn't have fixed length.
B) Using STRING_SPLIT() function to split a comma-separated string in a column. Sometimes, database tables are not normalized. A typical example of this is when a column can store multiple values separated by a comma (,). The STRING_SPLIT() can help normalize the data by splitting these multi-valued columns.
The STRING_SPLIT(string, separator) function in SQL Server splits the string in the first argument by the separator in the second argument. To split a sentence into words, specify the sentence as the first argument of the STRING_SPLIT() function and ' ' as the second argument.
Using a common table expression it is possible to reverse a string in SQLite. WITH reverse(i, c) AS ( values(-1, '') UNION ALL SELECT i-1, substr('dlrow olleh', i, 1) AS r FROM reverse WHERE r!= '' ) SELECT group_concat(c, '') AS reversed FROM reverse; Returns hello world .
You can use a common table expression to split comma separated values in SQLite.
WITH split(word, str) AS (
-- alternatively put your query here
-- SELECT '', category||',' FROM categories
SELECT '', 'Auto,A,1234444'||','
UNION ALL SELECT
substr(str, 0, instr(str, ',')),
substr(str, instr(str, ',')+1)
FROM split WHERE str!=''
) SELECT word FROM split WHERE word!='';
Output is as expected:
Auto
A
1234444
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With