Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split comma-separated value in SQLite?

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.

like image 844
dipali Avatar asked Jun 17 '14 08:06

dipali


People also ask

How do you split a comma in SQL?

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.

Can you split a string in SQL?

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.

How do I reverse a string in SQLite?

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 .


1 Answers

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
like image 97
user1461607 Avatar answered Oct 10 '22 20:10

user1461607