Stack Exchange
Sort Records according to distance
SELECT p FROM public.project p LEFT JOIN public.quotes q ON p.id = q.project_id WHERE q.status = 'ACCEPTED' and EXISTS(SELECT distinct l AS l1 FROM Location l where postal_code = (SELECT postal_code FROM address WHERE id = p.address_id)  and calculate_distance(43.7731408,-79.2317523,l.latitude,l.longitude,'K') <= 10.0)

This query is returning the projects which are in radius of 10 KM from user.
User location is 43.7731408,-79.2317523.
calculate_distance(lat1, long1, lat2, long2, units) is the function which returns distance between two points.
Now have to sort that projects according to the distance.
SELECT p FROM public.project p LEFT JOIN public.quotes q ON p.id = q.project_id
    WHERE q.status = 'ACCEPTED' and EXISTS(SELECT distinct l AS l1 FROM Location l where postal_code =  
   (SELECT postal_code FROM address WHERE id = p.address_id)  and 
   calculate_distance(43.7731408,-79.2317523,l.latitude,l.longitude,'K') <= 10.0)  
   ORDER BY calculate_distance(43.7731408,-79.2317523,l1.latitude,l1.longitude,'K') DESC

Tried this but its not working
Projects that are nearest to the user should be displayed first.

If you sort by DESC then it will start from farthest to nearest. Isn't?

Another way is create table in memory " create table... ", put data and then "select... order by"

Please post your table schema

Looks like the query could be simplified
SELECT distinct p.*
FROM public.project p
JOIN address a ON a.id = p.address_id
JOIN Location l1 ON l1.postal_code = a.postal_code 
   and calculate_distance(43.7731408,-79.2317523,l1.latitude,l1.longitude,'K') <= 10.0 
JOIN public.quotes q ON p.id = q.project_id and q.status = 'ACCEPTED' 
ORDER BY calculate_distance(43.7731408,-79.2317523,l1.latitude,l1.longitude,'K') DESC

I'm using inner JOIN instead of LEFT JOIN because OP WHERE references joined table columns without checking for NULL.
