Sorting by Fixed-Length Substrings
Problem
You want to sort using parts of a column that occur at a given position within the column.
Solution
Pull out the parts you need with
LEFT(),
MID(), or RIGHT(), and sort them.
Discussion
Suppose that you have a housewares table that acts as a catalog for
houseware furnishings, and that items are identified by 10-character
ID values consisting of three subparts: a three-character category
abbreviation (such as DIN for
“dining room” or KIT
for “kitchen”), a five-digit serial number, and a
two-character country code indicating where the part is
manufactured:
mysql>SELECT * FROM housewares;
+------------+------------------+
| id | description |
+------------+------------------+
| DIN40672US | dining table |
| KIT00372UK | garbage disposal |
| KIT01729JP | microwave oven |
| BED00038SG | bedside lamp |
| BTH00485US | shower stall |
| BTH00415JP | lavatory |
+------------+------------------+This is not necessarily a good way to store complex ID values, and later we’ll consider how to represent them using separate columns (see Using an AUTO_INCREMENT Column to Create Multiple Sequences). But for now, assume that the values must be stored as just shown.
If you want to sort rows from this table based on the id values, just use the entire column
value:
mysql>SELECT * FROM housewares ORDER BY id; +------------+------------------+ | id | description | +------------+------------------+ | BED00038SG | bedside lamp | | BTH00415JP | lavatory | | BTH00485US | shower ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access