I want to list (a sorted list) all my entries from an attribute called streetNames in my table/relation Customers. eg. I want to achieve the following order:
Street_1A
Street_1B
Street_2A
Street_2B
Street_12A
Street_12B
A simple order by streetNames will do a lexical comparision and then Street_12A and B will come before Street_2A/B, and that is not correct. Is it possible to solve this by pure SQL?
The reliable way to do it (reliable in terms of ‘to sort your data correctly’, not ‘to solve your general problem’) is to split the data into street name and house number and sort both of them on their own. But this requires knowing where the house number starts. And this is the tricky part – making the assumption best fits your data.
You should use something like the following to refactor your data and from now on store the house number in a separate field. All this string-juggling won’t perform too well when it comes to sorting large data sets.
Assuming it is the last thing in the street name, and it contains a number:
This assumes these conditions:
REPLACE(street, ' - ', '-')to sanitize common patterns beforehand.)