Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a single sql column into five

I'm trying to split one column into up to five around the " > " delimiter but the things I've tried haven'tw orked:

I tried

select
id, 
compoundColumn,
split(compoundColumn," > ")[1] as "first"
split(compoundColumn," > ")[2] as "second"
from table
where compoundColumn is not null

which didn't work, and

this which sort of did (the first part anyway, not the nth part)

select
id, 
compoundColumn,
first(split(compoundColumn," > ")) as "first"
nth(compoundColumn," > ")[n] as "second"
from table

I've found lots of examples on here but they all seem to be saying to use the brackets but the brackets throw an error:

Exception: Malformed SQL. More information: Error with SQL statement: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[1] as "first" from table where compoundColumn IS NOT NULL' at line 3.

like image 601
J. G. Avatar asked May 08 '26 10:05

J. G.


1 Answers

  • there's missing comma after "first" in your SQL
  • I guess CloudSQL is based on some old version of MySQL which can split only using substring_index (see query below - yes it's verbose and clumsy, case clause must sanitize short strings)
  • perhaps try brackets with [offset(0)] or [ordinal(1)], that's what works for us, though we use Postgres dialect, also as #standardSql, not #legacySql

SQL from second point: (fiddle)

select id,
  case when substring_index(cc,' > ',0) = cc then null else substring_index(substring_index(cc,' > ',1),' > ',-1) end as a1,
  case when substring_index(cc,' > ',1) = cc then null else substring_index(substring_index(cc,' > ',2),' > ',-1) end as a2,
  case when substring_index(cc,' > ',2) = cc then null else substring_index(substring_index(cc,' > ',3),' > ',-1) end as a3,
  case when substring_index(cc,' > ',3) = cc then null else substring_index(substring_index(cc,' > ',4),' > ',-1) end as a4,
  case when substring_index(cc,' > ',4) = cc then null else substring_index(substring_index(cc,' > ',5),' > ',-1) end as a5
from d
like image 99
Tomáš Záluský Avatar answered May 11 '26 01:05

Tomáš Záluský



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!