Last active
January 26, 2024 14:13
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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