Name

SUBSTRING_INDEX( )

Synopsis

SUBSTRING_INDEX(string, delimiter, count)

This function returns a substring of the string given in the first argument that contains delimited data. The delimiter needs to be given in the second argument of the function. The number of elements starting from the left end of the string to extract is given in the third argument. A negative number instructs MySQL to count from the right end.

SELECT SUBSTRING_INDEX(pre_req, '|', -1)
          AS 'Last Prerequisite',
      pre_req AS 'All Prerequisites'
FROM courses WHERE course_id = '1245';
+--------------------+----------------------------+
| Last Prerequisite | All Prerequisites           |
+--------------------+----------------------------+
| ENGL-202           | ENGL-101|ENGL-201|ENGL-202 |
+--------------------+----------------------------+

In this example, the last prerequisite course for the course selected is displayed, because -1 was entered for the count.

Get MySQL in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.