Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all the string before an empty space in postgres?

So basically I need to get a part of the postcode string, all before an empty space

my current query is

select postcode, left(postcode, length(postcode) - strpos(' ', postcode)) 
from postcodetable

But it just doesn't return the post code correctly, example: 1st column is NW1 1AA, 2nd column should just be NW1 but instead it just repeats the first column

like image 873
Luffydude Avatar asked Oct 24 '25 23:10

Luffydude


1 Answers

Your arguments to strpos() are in the wrong order. So you can do:

select postcode, left(postcode, length(postcode) - strpos(postcode, ' '))
from (values ('NW1 1AA')) v(postcode);

You can also do this using substring() with regular expressions:

select postcode, substring(postcode from '[^ ]+'::text)
like image 54
Gordon Linoff Avatar answered Oct 27 '25 18:10

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!