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 ...

Get MySQL Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.