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?