[SOLVED] Last word in a sentence: In SQL (regular expressions possible?)

Table of Contents


I need this to be done in Oracle SQL (10gR2). But I guess, I would rather put it plainly, any good, efficient algorithm is fine.

Given a line (or sentence, containing one or many words, English), how will you find the last word of the sentence?

Here is what I have tried in SQL. But, I would like to see an efficient way of doing this.

select reverse(substr(reverse(&p_word_in)
                         , 0
                         , instr(reverse(&p_word_in), ' ')
      from dual;

The idea was to reverse the string, find the first occurring space, retrieve the substring and reverse the string. Is it quite efficient? Is a regular expression available? I am on Oracle 10g R2. But I dont mind seeing any attempt in other programming language, I wont mind writing a PL/SQL function if need be.


Jeffery Kemp has given a wonderful answer. This works perfectly.


SELECT SUBSTR(&sentence, INSTR(&sentence,' ',-1) + 1)
FROM dual


I reckon it’s simpler with INSTR/SUBSTR:

WITH q AS (SELECT 'abc def ghi' AS sentence FROM DUAL)
SELECT SUBSTR(sentence, INSTR(sentence,' ',-1) + 1)

Answered By – Jeffrey Kemp

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *