2

I am Using PostgreSQL 9.5 and have a table with a "area_name" text column of names that have numbered extentions:

area_name
----------------
AREA
AREA EXT
AREA EXT 1
AREA EXT 5
AREA EXT 49
AREA EXT 50

I want to order the result numerically by extention as shown above.

I have tried using a regexp_replace to lpad the numbers with 0s, but using a length of 4 is adding 2 0s in front of the number regardless of if it is 1 or 2 digits!

create table ext_test (
    area_name text
);

insert into ext_test values
  ('AREA'),
  ('AREA EXT'),
  ('AREA EXT 1'),
  ('AREA EXT 5'),
  ('AREA EXT 49'),
  ('AREA EXT 50');

select
    area_name,
    regexp_replace(area_name, ' EXT (\d*)', ' EXT ' || lpad('\1', 4, '0')) as order_result
from ext_test
order by order_result;

area_name    | order_result
------------------------------ 
AREA         | AREA
AREA EXT     | AREA EXT
AREA EXT 1   | AREA EXT 001
AREA EXT 49  | AREA EXT 0049
AREA EXT 5   | AREA EXT 005
AREA EXT 50  | AREA EXT 0050

Where am I going wrong with the replace expression?

1
  • I hope you check out my answer. ;) it's substantially easier and faster. Apr 27, 2017 at 22:41

4 Answers 4

1

When you execute regexp_replace(area_name, ' EXT (\d*)', ' EXT ' || lpad('\1', 4, '0'))
First of all the parameters are being evaluated

lpad('\1', 4, '0') becomes '00\1'

' EXT ' || lpad('\1', 4, '0') becomes ' EXT 00\1'

Which means the captured groups (the numbers in this case) are going to be preceded by 2 zeros.


Your goal can be achieved in 2 phases -

  1. Left pad all numbers with X preceding zeros
  2. truncate each number to its most right X digits

select      area_name
           ,regexp_replace(regexp_replace(area_name,'\d+',repeat('0',4) || '\&'),'\d*(\d{4})','\1') as order_result

from        ext_test

order by    order_result
;

+-------------+---------------+
| area_name   | order_result  |
+-------------+---------------+
| AREA        | AREA          |
+-------------+---------------+
| AREA EXT    | AREA EXT      |
+-------------+---------------+
| AREA EXT 1  | AREA EXT 0001 |
+-------------+---------------+
| AREA EXT 5  | AREA EXT 0005 |
+-------------+---------------+
| AREA EXT 49 | AREA EXT 0049 |
+-------------+---------------+
| AREA EXT 50 | AREA EXT 0050 |
+-------------+---------------+

If you have more than a single number in your text, use this version which is based on 'AREA EXT ' -

select      area_name
           ,regexp_replace(regexp_replace(area_name,'(?<=AREA EXT )\d+',repeat('0',4) || '\&'),'(?<=AREA EXT )\d*(\d{4})','\1') as order_result

from        ext_test

order by    order_result
;
0
0

I'm not sure why you're trying to format them your question calls for ordering. That's pretty simple. Just keep them as int.

I want to order the result numerically by extention as shown above.

Just put in the ORDER BY statement.

SELECT area_name
FROM ext_test
ORDER BY
  CASE
    WHEN area_name ~ '\d'
    THEN (regexp_matches(area_name, '\d+'))[1]::int
  END NULLS FIRST,
  area_name;

  area_name  
-------------
 AREA
 AREA EXT
 AREA EXT 1
 AREA EXT 5
 AREA EXT 49
 AREA EXT 50
(6 rows)
0

Update:

(I added one more row with AREA TEXT 509)

It looks you can't reference '\1' from regular to lpad( like this. Look below - column o is yours - the result is 00509, second column has length('\1') *which of course is always two, because '\1' is interpreted as text, not as regular expression meta syntax. So I believe what happens is lpad interprets first argument as metasyntax, but then substracting length of '\1' from second argumet interprets it as text => 4-2 is ALWAYS 2. So it appends two zeroes to any input.

While this is either bug or not meant usage of SQL functions mixed with regular expression meta syntax, I propose getting a value from regular expression and then use it with sql function. Here column r is example. and column replace is example of meant output:

t=# with p as (select regexp_replace(area_name, ' EXT (\d*)', ' EXT ' || lpad('\1', 4, '0')) o,regexp_replace(area_name,'AREA EXT (\d*)',length('\1')||'.\1'||'.'), area_name,regexp_replace(area_name,'AREA EXT (\d*)','\1') r from ext_test)
select *, length(r),replace(area_name,r,lpad(r,4,'0')) from p;
       o        | regexp_replace |  area_name   |    r     | length |    replace
----------------+----------------+--------------+----------+--------+---------------
 AREA           | AREA           | AREA         | AREA     |      4 | AREA
 AREA EXT       | AREA EXT       | AREA EXT     | AREA EXT |      8 | AREA
 AREA EXT 001   | 2.1.           | AREA EXT 1   | 1        |      1 | AREA EXT 0001
 AREA EXT 005   | 2.5.           | AREA EXT 5   | 5        |      1 | AREA EXT 0005
 AREA EXT 0049  | 2.49.          | AREA EXT 49  | 49       |      2 | AREA EXT 0049
 AREA EXT 0050  | 2.50.          | AREA EXT 50  | 50       |      2 | AREA EXT 0050
 AREA EXT 00509 | 2.509.         | AREA EXT 509 | 509      |      3 | AREA EXT 0509
(7 rows)

Time: 0.519 ms

just a proposal - maybe use integers for ordering, like here?:

t=# with a as (select *,split_part(area_name,'AREA EXT ',2) s from ext_test) select area_name,case when s='' then 0 else s::int end c from a order by c,area_name;
  area_name  | c
-------------+----
 AREA        |  0
 AREA EXT    |  0
 AREA EXT 1  |  1
 AREA EXT 5  |  5
 AREA EXT 49 | 49
 AREA EXT 50 | 50
(6 rows)

Time: 0.354 ms
5
  • This is a simplified example. In the actual data 'AREA' above is hundreds of different names from thousands of records. Sometimes the where clause selects on the beginning of the name and then I can just use: order by length(area_name), area_name Where my where clause get more complicated there can be multiple area_names in the result so this dosn't work.
    – Derek
    Feb 8, 2017 at 8:41
  • please update your question with more examples then?
    – Vao Tsun
    Feb 8, 2017 at 8:44
  • This is enough data to show the problem. The real question is why is the padding not working as expected inside the regexp_replace?
    – Derek
    Feb 8, 2017 at 9:05
  • I don't know how to attract attention on this of particular persons. Whales like Erwin or Craig could answer if this is a bug or you just not meant to use regular meta syntax as argument to SQL functions
    – Vao Tsun
    Feb 8, 2017 at 9:25
  • Thank you. Now I understand why I wasn't getting the result I expected.
    – Derek
    Feb 8, 2017 at 9:52
0

And here is another simple way to achieve your goal

select      area_name
           ,substring (area_name,'(?<=AREA EXT )\d+')::int as order_result

from        ext_test

order by    order_result nulls first
           ,area_name
;

+-------------+--------------+
| area_name   | order_result |
+-------------+--------------+
| AREA        | (null)       |
+-------------+--------------+
| AREA EXT    | (null)       |
+-------------+--------------+
| AREA EXT 1  | 1            |
+-------------+--------------+
| AREA EXT 5  | 5            |
+-------------+--------------+
| AREA EXT 49 | 49           |
+-------------+--------------+
| AREA EXT 50 | 50           |
+-------------+--------------+

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.