The distance is NULL
because some of your records have NULL values for lat
and/or lng
. You can add:
HAVING distance is not null
until you fix the problem.
If you want to optimize the query, then think about using the geospatial extensions (the documentation is here).