Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL statement to find last word in string

Tags:

sql

mysql

I have a table with a text field that contains one or more words, separated by spaces. I want to isolate the last word in that text field. For example if the table contained:

|col1 |
+-----+
|a    |
|b c  |
|d e f|

I want a query that will return:

|result|
+------+
|a     |
|c     |
|f     |

Thanks in advance!

Barry

P.S. I am running MySQL 5.1

like image 204
Barry Fruitman Avatar asked Aug 14 '11 03:08

Barry Fruitman


People also ask

How do I get the last word in a string in SQL?

Late answer, posted only as guidance. The simple fix is to add a "fail-safe" in the charindex() by adding a space to the string, thus ensuring a hit.

How do I find a specific word in a string in SQL?

SQL Server CHARINDEX() Function The CHARINDEX() function searches for a substring in a string, and returns the position. If the substring is not found, this function returns 0. Note: This function performs a case-insensitive search.

How do I get the last value in SQL?

We can use the ORDER BY statement and LIMT clause to extract the last data. The basic idea is to sort the sort the table in descending order and then we will limit the number of rows to 1. In this way, we will get the output as the last row of the table. And then we can select the entry which we want to retrieve.

How do I get the first word of a string in SQL?

SELECT SUBSTRING_INDEX(yourColumnName,' ',1) as anyVariableName from yourTableName; In the above query, if you use -1 in place of 1 then you will get the last word.


1 Answers

SELECT SUBSTRING_INDEX(TRIM(col1), ' ', -1) FROM table;

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring-index

like image 148
Dan Grossman Avatar answered Oct 08 '22 11:10

Dan Grossman