Select Everything Before or After a Delimiter in MySQL

Using the SUBSTRING_INDEX function in MySQL makes it really easy to split your string data based on a specified delimiter. This comes in handy when your string data is not uniform.

In my code snippet below, I am specifying my string column, splitting the column on the 1st instance of the - character, and finally selecting everything before my specified character.

SUBSTRING_INDEX(column, '-', 1)

If my string column contained hi paul-cool trick, my query would return hi paul

The SUBSTRING_INDEX column takes the following parameters:

  1. A table column
  2. The delimiter
    • This could be a special character, text, or whatever you include inside your quotes ' '
  3. Start at the X occurrence
    • Specifies if the string should be split at the 1st, 2nd, 3rd, etc. occurrence.
    • If the number is positive, the results will grab everything to the left of the string
    • If the number is negative, the results will grab everything to the right of the string

Posted

in

by

Tags: