------------------------------------------------------- 
-- earth_box radius from airport with distance.
-------------------------------------------------------

SELECT 
    airports.airport_id,
    airports.name,
    airports.latitude,
    airports.longitude,
    airports.airlines_flying,
    round (CAST (float8 (earth_distance(
        ll_to_earth(
                (SELECT
                    airports.dd_latitude AS latitude
                 FROM
                    airports
                WHERE
                    UPPER (airports.airport_id) LIKE upper(:name)) -- name of origin
                ,
                 (SELECT
                    airports.dd_longitude AS longitude
                 FROM
                    airports
                WHERE
                    UPPER (airports.airport_id) LIKE upper(:name)) -- name of origin
            ), 
        ll_to_earth(
            airports.dd_latitude,
            airports.dd_longitude
        )
    )) AS NUMERIC ), 2)AS distance
FROM
    airports
WHERE
    earth_box(
        ll_to_earth(
            (SELECT
                airports.dd_latitude AS latitude
            FROM
                airports
            WHERE
                UPPER (airports.airport_id) LIKE upper(:name)) -- name of origin
            ,
            (SELECT
                airports.dd_longitude AS longitude
            FROM
                airports
            WHERE
                UPPER (airports.airport_id) LIKE upper(:name)) -- name of origin
            )
        , :distance -- this is the radius in meters
    ) @> 
     ll_to_earth(
            airports.dd_latitude,
            airports.dd_longitude
     )
ORDER BY
    distance asc