Postgres Query to retrieve locations within a given distance I have the following sql query that works fine in MYSQL but it gives me an error in Postgres:

SELECT * , 
        ( 3959 * acos( cos( radians('13.1') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('53.1') ) + sin( radians('13.1') ) * sin(radians(lat)) ) ) AS distance 
FROM person 
HAVING distance &lt; 10 
ORDER BY distance LIMIT 20


**ERROR**:  column "distance" does not exist
LINE 1: ...(radians(lat)) ) ) AS distance FROM person HAVING distance &lt;...
You can repeat the expression in the filter condition, or you can avoid that by using a subquery:

SELECT *
FROM (SELECT *, 
             3959 * acos(
                       cos(
                          radians('13.1')
                       ) * cos(
                          radians(lat)
                       ) * cos(
                          radians(lng) - radians('53.1')
                       ) + sin(
                          radians('13.1')
                       ) * sin(radians(lat))
                    ) AS distance 
      FROM person) AS q 
WHERE distance &lt; 10 
ORDER BY distance LIMIT 20;