Skip to content

Instantly share code, notes, and snippets.

@jasonhancock
Created April 23, 2013 17:01
Show Gist options
  • Save jasonhancock/5445430 to your computer and use it in GitHub Desktop.
Save jasonhancock/5445430 to your computer and use it in GitHub Desktop.
Ordering IP ranges in CIDR notation stored in a SQL DB correctly

Imagine you're storing IP ranges in CIDR notation in a database table like this:

CREATE TABLE ranges (
    block VARCHAR(50)
);

INSERT INTO ranges(block) VALUES ('192.168.2.0/24'),('192.168.10.0/24');

When you try to select the blocks and order them, you get:

SELECT block FROM ranges ORDER BY block;
+-----------------+
| block           |
+-----------------+
| 192.168.10.0/24 |
| 192.168.2.0/24  |
+-----------------+
2 rows in set (0.00 sec)

Here's a way to order them correctly:

SELECT block FROM ranges ORDER BY INET_ATON(SUBSTRING(block FROM LENGTH(block) * -1 FOR (INSTR(block, '/') - 1)));
+-----------------+
| block           |
+-----------------+
| 192.168.2.0/24  |
| 192.168.10.0/24 |
+-----------------+
2 rows in set (0.00 sec)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment