1

So I have a column (called account_uri) in a postgres table that looks like this:

/randomCharacters/123456/randomNumbers

I need to query for the substring in the middle, which is a string of characters between two / symbols.

My current attempt looked like this:

SELECT 
REVERSE(SUBSTRING(REVERSE([account_uri]),0,CHARINDEX('/',REVERSE(account_uri))))
FROM exp_logs
LIMIT 15

Which selects only the randomNumbers and not the desired numbers.

I tried to build on that idea though and used

(SUBSTRING(REVERSE(SUBSTRING(REVERSE([account_uri]),CHARINDEX('/',REVERSE(account_uri)))),1,CHARINDEX('/',REVERSE(SUBSTRING(REVERSE([account_uri]),CHARINDEX('/',REVERSE(account_uri)))))))

but that only returns a bunch of / symbols and no numbers at all.

If anyone can help me query for this substring, I would be immensely grateful

1

2 Answers 2

4
select
  split_part(account_url, '/', 3)
from exp_logs;

works.

http://www.postgresql.org/docs/9.3/static/functions-string.html

Compatibility: 8.3+

Fiddle: http://sqlfiddle.com/#!15/5e931/1

Sign up to request clarification or add additional context in comments.

3 Comments

shouldn't it be 2 instead of 3?
I doubt the question is for postgresql but if it's then nice answer.
@FuzzyTree it would parse the string like this: /randomCharacters/123456/randomNumbers = 1/2/3/4 , due to the leading '/'
3

A couple of solutions, sorted by fastest first:

SELECT split_part(account_uri, '/', 3)        AS solution_1  -- Neil's solution
      ,substring(account_uri,'^/.*?/(.*?)/')  AS solution_2
      ,substring(account_uri,'^/[^/]*/(\d*)') AS solution_3
      ,(string_to_array(account_uri,'/'))[3]  AS solution_4
FROM (
   VALUES
     ('/randomCharacters/123456/randomNumbers')
    ,('/v o,q9063´6qu/24734782/2369872986')
    ,('/DFJTDZTJ/1/234567')
    ,('/ ijgtoqu29836UGB /999/29672')
   ) exp_logs(account_uri);

@Neil's solution proved fastest in a quick test on a table with 30k rows.

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.