I have a table called articles
that contains data in the following format:
id|categories
--+----------
1|123,13,43
2|1,3,15
3|9,17,44,18,3
For testing purposes, you may create this table using the following SQL commands:
CREATE TABLE articles(id INTEGER PRIMARY KEY, categories TEXT);
INSERT INTO articles VALUES(1, '123,13,43'), (2, '1,3,15'), (3, '9,17,44,18,3');
Now I would like to split the values of the categories
column so that a table like the following one is the result:
id|category
--+--------
1|123
1|13
1|43
2|1
2|3
2|15
3|9
3|17
3|44
3|18
3|3
As you can see, I would like to bring the original table into the First normal form.
I already know how to split just one row in this way, from this answer. The following code example just takes the second row (i.e. the one where id=2) and splits them in the desired way:
WITH split(article_id, word, str, offsep) AS
(
VALUES
(
2,
'',
(SELECT categories FROM articles WHERE id=2),
1
)
UNION ALL
SELECT
article_id,
substr(str, 0, CASE WHEN instr(str, ',') THEN instr(str, ',') ELSE length(str)+1 END),
ltrim(substr(str, instr(str, ',')), ','),
instr(str, ',')
FROM split
WHERE offsep
) SELECT article_id, word FROM split WHERE word!='';
Of course this is very unflexible, as the article ID needs to be hard-coded. So, now my question is: What do I have to add to or change in the upper SQLite code to make it operate on all rows and output the desired result?