Home > Database > Mysql Tutorial > How Can I Efficiently Split Comma-Separated Values in SQLite Using CTEs?

How Can I Efficiently Split Comma-Separated Values in SQLite Using CTEs?

Mary-Kate Olsen
Release: 2025-01-04 03:12:11
Original
198 people have browsed it

How Can I Efficiently Split Comma-Separated Values in SQLite Using CTEs?

Splitting Comma-Separated Values in SQLite

An alternative approach to working with comma-separated strings in SQLite involves leveraging Common Table Expressions (CTEs). CTEs provide a means to break down the string into individual values effectively.

Step-by-Step Implementation:

  1. Create a CTE: Begin by defining a CTE named split that accepts two parameters: word to hold individual values and csv to store the comma-separated string.
  2. Initial Query: In the initial query of the CTE, you'll specify the CSV string, concatenating an additional comma to indicate its end.
  3. Recursive Query: The recursive query employs substr() and instr() to extract the first word up until the next comma and update the csv to remove the parsed part. This process repeats until no more commas are encountered.
  4. Select Result: Finally, select the word column from the CTE, excluding the first and last rows, which represent the raw CSV string and any residual empty text.

Example:

Here's a code sample to illustrate the CTE approach:

WITH split(word, csv) AS (
  SELECT '', 'Auto,A,1234444'||','
  UNION ALL SELECT
    substr(csv, 0, instr(csv, ',')),
    substr(csv, instr(csv, ',') + 1)
  FROM split
  WHERE csv != ''
) SELECT word FROM split 
WHERE word!='';
Copy after login

Output:

Auto
A
1234444
Copy after login

This method offers a concise and efficient way to split comma-separated strings in SQLite, enabling you to access individual values with ease.

The above is the detailed content of How Can I Efficiently Split Comma-Separated Values in SQLite Using CTEs?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template