create or replace function FindNearestAirport(
    longitude_P numeric,
    latitude_P numeric,
    distanceKm int
) returns table (
    AirportCode char(3),
    AirportName text,
    AirportLocation geography(Point, 4326),
    Distance_KM numeric
) as $$
    begin
        return query
        select a.code, a.name, a.location, (ST_Distance(a.location, ST_MakePoint(longitude_P, latitude_P)::geography) / 1000)::numeric
        from airport as a
        where ST_DWithin(a.location, ST_MakePoint(longitude_P, latitude_P)::geography, distanceKm * 1000)
        order by a.location <-> ST_MakePoint(longitude_P, latitude_P)::geography;
    end;
$$ language plpgsql;

select * from FindNearestAirport(21.62, 41.96, 100000);
