Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How split word in rows Mysql

Is it possible to split a word into separate lines? All the examples I found were using something to refer to as a comma or something, but I would like to separate each letter from a word, eg:

from (my table):

id name
1 banana

to: SELECT ...

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

id letter
1 b
1 a
1 n
1 a
1 n
1 a

>Solution :

One option is doing it with a recursive query, using the following two steps:

  • base step: get the letter in position 1
  • recursive step: get nth letter, using LEFT(RIGHT(1), n), which extracts the letter in position n.

Recursion is halted when the nth extracting element is higher than then length of the string.

WITH RECURSIVE cte AS (
    SELECT id, name,
           1 AS idx, 
           RIGHT(LEFT(name, 1),1) AS letter 
    FROM tab
  
    UNION ALL
  
    SELECT id, name,
           idx + 1 AS idx,
           RIGHT(LEFT(name, idx+1), 1) AS letter
    FROM cte
    WHERE idx < LENGTH(name)
)
SELECT id, letter FROM cte

Output:

id letter
1 b
1 a
1 n
1 a
1 n
1 a

Check the demo here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading