Sitemap
Minseo Kim

Minseo Kim

SQL - Manhattan Distance

1 min readJun 26, 2026
  • Manhattan Distance : total distance = | c - a | + | d - b |

My first answer

SELECT round(Max(LONG_W)-MIN(LONG_W)+MAX(LAT_N)-MIN(LAT_N),4)
from station;

While this works, it looks messy. I wonder if I can get a result using substitution.

SELECT round(A + B,4)
from(
SELECT
Max(LONG_W)-MIN(LONG_W) AS A,
MAX(LAT_N)-MIN(LAT_N) AS B
from station
) AS tmp

I defined the coordinate differences as A and B beforehand. It works well and looks like more readable.

If we want to use Euclidean Distance instead of Manhattan Distance, we can apply the geometric formula that √(A² + B²)

Get Minseo Kim’s stories in your inbox

Join Medium for free to get updates from this writer.

Thanks to the substitution structure we built earlier, we don’t need to rewrite the entire subquery. We can easily calculate it by adding SQL’s SQRT() and POW() functions to the main query

SELECT round(SQRT(POW(A,2) + POW(B, 2)) ,4)
from(
SELECT
Max(LONG_W)-MIN(LONG_W) AS A,
MAX(LAT_N)-MIN(LAT_N) AS B
from station
) AS tmp

--

--