The default collations provided by Firebird do not apply this form of sorting (or at least, I can't think of any that do). You will need to create a custom collation for this to work, and you will have to use the UTF8 character set for the column involved.
To be clear, the solution below does not offer the exact sort order you describe, instead it will sort as: 1, 02, 2, 005, w1, w2, w100, z0, z1. I'm not aware of numeric sorting algorithms that would treat leading zeros differently than other numbers.
First of all, create a custom collation:
create collation unicode_numeric for utf8 from unicode 'NUMERIC-SORT=1';
This creates a derivation of the built-in UNICODE
collation, with the NUMERIC-SORT
enabled. You could also use another UTF8 collation as a base (e.g. UNICODE_CI
or UNICODE_CI_AI
, etc.).
If the column you're sorting on is already UTF8, you can sort by applying the collate
clause:
select val
from numeric_sort_example2
order by val collate unicode_numeric;
If the column has a different character set, you will first have to cast before you can apply the collation:
select val
from numeric_sort_example3
order by cast(val as varchar(50) character set utf8) collate unicode_numeric;
You can also specify the collation as part of the column definition:
create table numeric_sort_example1 (
val varchar(50) character set utf8 collate unicode_numeric
);
You can then use order by
without an explicit collation:
select val
from numeric_sort_example1
order by val;
See also this fiddle: https://dbfiddle.uk/UnePdleL