Get all characters before space in MySQL

SqlMysql

Sql Problem Overview


I would like to get all the characters in a field before a space

For example, if field1 is "chara ters"

I want it to return "chara"

What would this select statement look like?

Sql Solutions


Solution 1 - Sql

SELECT LEFT(field1,LOCATE(' ',field1) - 1)

Note that if the string in question contains no spaces, this will return an empty string.

Solution 2 - Sql

Below is another method that works and may seem a bit simpler to some. It uses the SUBSTRING_INDEX MySQL function. A 1 returns everything before the first space, and a -1 returns everything after the last space.

This returns 'chara':

SELECT SUBSTRING_INDEX( field1, ' ', 1 )

This returns 'ters':

SELECT SUBSTRING_INDEX( field1, ' ', -1 )

Details

A positive value will look for your specified character from the start of the string, and a negative value will start from the end of the string. The value of the number indicates the quantity of your specified character to look for before returning the remaining piece of the string. If the character you are searching for does not exist, the entire field value will be returned.

In this case, a -2 would return everything to the right of the second to last space, which doesn't exist in this example, so the entire field value will be returned.

Solution 3 - Sql

You would need some string operations for that. Assuming every field has at least one space character:

SELECT SUBSTR(field1, 0, LOCATE(' ', field1)) FROM your_table;

Safe approach:

SELECT IF(
    LOCATE(' ', field1),
    SUBSTR(field1, 0, LOCATE(' ', field1)),
    field1
) FROM your_table;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex GordonView Question on Stackoverflow
Solution 1 - SqlMchlView Answer on Stackoverflow
Solution 2 - SqlT. Brian JonesView Answer on Stackoverflow
Solution 3 - SqlsoulmergeView Answer on Stackoverflow