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 WHERE
clause in your query will not have much impact on execution time. However, if you add indexes to the fields mentioned in your WHERE
clause, you could considerably improve performance.
So in your example, if there is not an index on city_id
and you were to add that condition to your WHERE
clause and create an index on that field, you would likely see a considerable performance improvement.
Adding criteria could go either way, but usually more criteria does help performance, especially if the columns have indices.
In your case if you have an index that includes city_id and long and lat you'll get much better performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With