Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to exclude some letter in order by

I have table with these columns: id, placement
my placement is type text and looks like this: A-L-100, A-L-101, A-R-100, …
When I do order by placement, It gives all A-L at first then A-R. Is there any option to get A-Ls and A-Rs after each other order by their first letter and their number?

Something like this A-L-100, A-R-100

my current sql:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT * FROM inventory ORDER BY placement

>Solution :

It seems that you need to order by the numeric suffix first and then by the letters’ prefix. So here it is using regular expressions.

with inventory(placement) as (values ('A-L-100'), ('A-L-101'), ('A-R-100'))
select * from inventory 
 order by substring(placement from '(\d+)$'), 
          substring(placement from '(^[^\d]+)');

After your comment – order by the leading letter and then by the trailing number.

with inventory(placement) as 
(
 values 
 ('B-L-100'), ('B-L-101'), ('B-R-100'),
 ('A-L-100'), ('A-L-101'), ('A-R-100')
)
select * from inventory 
 order by left(placement, 1), substring(placement from '(\d+)$');

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading