0

I am currently using a query, however sometimes it doesn't update all fields. I need a workaround on this. Can anybody help me?

update table1 
set number = 
( 
select substring(number from offset) 
from table2 
where strpos(number,prefix) = '1' 
order by length(prefix) 
desc limit '1' 
) ; 

table1:

number
----------
1001123456

table2:

prefix | offset
-------+-------
1001   | 5

My goal, hopefully, is to retrieve only the substring (in this example "123456" for every row in table1 that matches the specific prefix in table2.

Any help would be greatly appreciated! Thank you!

0

1 Answer 1

1

Actually you don't need the offset field.

Table 1:

+------------+
|   NUMBER   |
+------------+
| 1001123456 |
|   10012222 |
|  200244444 |
|    2003666 |
+------------+

Table 2:

+--------+
| PREFIX |
+--------+
|   1001 |
|  20036 |
+--------+

Query:

select number, prefix,
  cast(
    substring(cast(t1.number as text), 
              char_length(cast(t2.prefix as text)) + 1)
  as integer) as suffix
from t1
join t2 on cast(t2.prefix as text) = 
  left(cast(t1.number as text),
       char_length(cast(t2.prefix as text)))

Result:

+------------+--------+--------+
|   NUMBER   | PREFIX | SUFFIX |
+------------+--------+--------+
| 1001123456 |   1001 | 123456 |
|   10012222 |   1001 |   2222 |
|    2003666 |  20036 |     66 |
+------------+--------+--------+
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the response Mosty! I forgot to mention I am using Postgresql 8.2.1 because we can't update it for now. Although, i'm kind of lost on the cast expressions. It is the same with the "::" correct?... Also, the left(... part seems not to be working on mine. I wonder what went wrong?
Hey John! Hmm, I don't know much about Postres (I know nothing, actually) but I'm sure that works on version 9. Take a look at this link. I don't know how to cast in Postgres, but cast the way you usually do :) The left seems to be added in version 9 and is actually the same as substring(1, x), I think :) See 8.2 and 9.1
Moreover, I tried this: select number, prefix, substring(t1.number from length((t2.prefix)::integer + 1)) as suffix from t1 join t2 on t2.prefix = substring(t1.number from 1 for char_length(t2.prefix::int + 1 ));

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.