MySQL Second (or third) Index Of in String

Bryan Field picture Bryan Field · Jan 15, 2013 · Viewed 27.6k times · Source

What would be the simplest way to locate the index of the third space in a string.

My goal is to get CCC out of this space separated list: AAAA BBBB CCCC DDDD EEE. where A and B and D are fixed length, and C is variable length, E F G are optional.

In Java I would use indexof, with a starting point of 10 and that would get me the third space, but it seems that I cannot do that in MySQL, so I thought maybe I could find a 'third index of' function?

Answer

Mike Brant picture Mike Brant · Jan 15, 2013

You would want to use SUBSTRING_INDEX function like this

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(field, ' ', 3), ' ', -1)
FROM table

The inner function call would get you to AAAA BBBB CCCC while the outer function call would pare that down to just CCCC.