11 Vote

MySQL: Read out first word of a column

Question by Guest | Last update on 2020-11-01 | Created on 2012-03-12

I am searching for a MySQL query or a corresponding function, that reads out the first word of a field from a column.

For example, if the text in a field is "Marry comes from Europe", the string "Marry" should be the MySQL result. If it is possible, I do not want to use PHP for this.

ReplyPositiveNegative
1Best Answer1 Vote

What you are looking for, is the MySQL function SUBSTRING_INDEX(), which can be used in the following manner:

SELECT SUBSTRING_INDEX(col, ' ', 1) FROM tab WHERE ...

The function expects 3 parameters:

  • A string or the name of the column (in this case "col"), which should be read out.
  • The character, at which the string should be cut off. Because you are searching for the first word, this character is a space ' '.
  • The number of occurences of the character. Because you want to cut at the first word, we cut at the first occurence of ' ' and we are writing "1" here. If you would like to read out the first two words, you had to write "2" here, because we had to cut at the second occurence of the space.

This example reads out the characters left from the position of the space. If you want to read out the characters standing right from the position of the space, you need to make the number negative.
Last update on 2020-11-01 | Created on 2012-03-12

ReplyPositive Negative
Reply

Related Topics

Quicksort: Sort two Columns

Question | 1 Answer

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.