Reputation: 1109
I'm running a query to get all locations in a table within a 15 mile radius. The query can take up to 15 seconds.
SELECT *
FROM rmiukpostcodes
WHERE 3963.191 * ACOS( (SIN(PI()*50.8320711166062/180)*SIN(PI()*latitude/180))+(COS(PI()*50.8320711166062/180)*cos(PI()*latitude/180)*COS(PI()*longitude/180-PI()*-0.207548227491786/180))) < = 5
Is there anything I can do to speed it up?
Upvotes: 1
Views: 668
Reputation: 110221
Your query reads every row in the table. Use some SARGABLE filter criteria and an index.
For example: before you run the query, precompute the max/min lat or long and use it.
WHERE
codes.Lat BETWEEN @minLat AND @maxLat
AND YourDistanceCalcHere(codes.Lat, codes.Long)
Then, an index on codes (Lat) would help the query
Upvotes: 0
Reputation:
You might benefit here from using a computed persisted column. You're causing a table/index scan because of your WHERE
clause, I believe.
Capture your execution plan. Try adding the computed column and alter your SELECT
query.
Upvotes: 1