4

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

0

2 Answers 2

11

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Oh it kinda worked now but there's still something wrong, my string of WC1B 4HH got trummed into WC1 instead of WC1B. Using your 2nd option it worked fine
3

Not only inverted arguments in strpos function, but also the 2nd parameter of left function is the number of characters to pick from the left.

Relating to official postgres docs:

left(str text, n int)

Return first n characters in the string. When n is negative, return all but last |n| characters.

So the correct query would be:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.