Home > Software design >  Sort result by distance to a given point - Via Postgres or via Spring Data?
Sort result by distance to a given point - Via Postgres or via Spring Data?

Time:11-24

I am writing a REST-Controller in Spring Boot and I want to return Locations in order of which is closest to the given location off a Postgres Database.

My Question is: Where should I handle the sort: In a Service Function in Java or in Postgres in the Query (using Native Query e.g.) - which is the better approach or does it even matter.

For further clearance:

I save latitude and longitude of locations in the database - and I want to calculate the distance to a given lat long.

CodePudding user response:

It would be good practise to sort in database layer.

Let's say you have 1 million rows and first job will be returning of those 1 million, then in application layer, you will sort those, that's extra 2nd job. Instead of using application layer (and increase jvm memory usage because of that), just return the data which exactly you will need.

  • Related