I’ve encountered the same problem twice for different customers, so I guess it’s worth a discussion.
A common task for web applications is to find out the country/region of a user, based on her IP address, as can be detected in the HTTP request. Depending on the country of origin, the website can translate dates for different time zones, can change locale settings, and, perhaps most commonly, show advertisements in her native language.
To start with, there’s a table which lists the IP ranges per country/region. Let’s assume we’re only dealing with IPv4:
CREATE TABLE regions_ip_range ( regions_ip_range_id INT UNSIGNED AUTO_INCREMENT, country VARCHAR(64) CHARSET utf8, region VARCHAR(64) CHARSET utf8, start_ip INT UNSIGNED, end_ip INT UNSIGNED, … PRIMARY KEY(regions_ip_range_id), ... );
The table is fixed, and is populated. Now the question arises: how do we query this table, and which indexes should be created?
The wrong way
The form I’ve encountered is as follows: an index is declared on regions_ip_range:
KEY ip_range_idx (start_ip, end_ip)
And the query goes like this:
SELECT * FROM regions_ip_range WHERE my_ip BETWEEN start_ip AND end_ip
Continue reading » “SQL: finding a user’s country/region based on IP”