Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to delete everything after a 'space' in MySQL field?

Tags:

string

mysql

Let's assume I have the following field:

' name sub _blah '

I can get rid of the outside spaces with the TRIM() function but I am actually looking to remove everything after the first space (after the trim).

so:

'name sub _blah' would turn into 'name'

I know this is possible in PHP but I am trying to do on a MySQL only call. Is there a function I do not know about for this?

Thanks!

like image 496
JM4 Avatar asked Mar 03 '11 18:03

JM4


2 Answers

select substring_index('name sub _blah',' ',1)
like image 181
Nicola Cossu Avatar answered Sep 20 '22 06:09

Nicola Cossu


Try this:

SUBSTRING_INDEX(str,' ', 1)

Or, if you still need TRIM as well:

SUBSTRING_INDEX(TRIM(str),' ', 1)

See e.g. here for additional documentation.

like image 27
phooji Avatar answered Sep 20 '22 06:09

phooji