I have a rather large table with 150,000 + records. It has a lot of fields like country_id, region_id, city_id, latitude, longitude, postal_code, to name just a few.
I need to select from this table based on the latitude and longitude, nothing else. My query looks like this:
SELECT * FROM `mytable`
WHERE `latitude` = '$latitude'
AND `longitude` = '$longitude';
Now although my sole criteria for selecting from this table is latitude/longitude I was wondering if adding more specificity would quicken the query like:
SELECT * FROM `mytable`
WHERE `city_id` = '320'
AND `latitude` = '$latitude'
AND `longitude` = '$longitude';
It seems counter intuitive to me that adding more conditions to the query would speed it up but at the same time I am narrowing down the number of possible results by a large margin by first making sure all the records selected are from a particular city id which I know resides in the latitude and longitude range I am going to be specifying by next.
There may be around 150k total records but only about 10k from that particular city.
So is this sensible at all or am I just making the query more time consuming?
In general, adding conditions to a
WHEREclause in your query will not have much impact on execution time. However, if you add indexes to the fields mentioned in yourWHEREclause, you could considerably improve performance.So in your example, if there is not an index on
city_idand you were to add that condition to yourWHEREclause and create an index on that field, you would likely see a considerable performance improvement.