Skip to content

Instantly share code, notes, and snippets.

@soply
Last active January 26, 2024 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soply/8f025b1e7d77f409bc5517d0d0165a5f to your computer and use it in GitHub Desktop.
Save soply/8f025b1e7d77f409bc5517d0d0165a5f to your computer and use it in GitHub Desktop.
Snippet to select last n words from a text in Postgres, which also works for version < 14 without negative indexing.
-- Create table and add a row
create table test_table (
some_text text
);
insert into test_table(some_text) values (
'this is a test'
);
-- Last word:
select
substring(some_text FROM '((\S+\s+){0,0}\S+$)') as last_word
from test_table
-- Last two words:
select
substring(some_text FROM '((\S+\s+){0,1}\S+$)') as last_two_words
from test_table
-- Last three words:
select
substring(some_text FROM '((\S+\s+){0,2}\S+$)') as last_three_words
from test_table
-- and so on.
-- First n words can be done via double `reverse`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment