Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a FIND_IN_SET by index in MySQL?

Tags:

string

sql

mysql

I know storing lists as strings is not wise, but I have to deal with that to export some data stored that way. I also know the FIND_IN_SET function, which returns the index of a certain string in a list:

SELECT FIND_IN_SET('bar', 'foo,bar,baz');
-- selects 2

Is there any built-in function (or combination of functions) to get the string in a particular index of the list? I'm looking for something like this:

SELECT IN_SET_AT_INDEX(2, 'foo,bar,baz');
-- selects 'bar'

I'd like to avoid a split-like function that makes the list a separate table, if possible.

like image 314
bfavaretto Avatar asked Jan 24 '26 04:01

bfavaretto


1 Answers

SUBSTRING_INDEX() can do this, sort of:

mysql> SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('foo,bar,baz', ',', 2), ',', -1) AS middle_one;
+------------+
| middle_one |
+------------+
| bar        |
+------------+
like image 88
Bill Karwin Avatar answered Jan 26 '26 18:01

Bill Karwin



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!