<-> (distance operator)
Operator available since PG 8.0+; KNN index scan support via GiST added in PG 9.1+→ double precisionReturns the Euclidean distance between two geometric objects (points, segments, boxes, etc.).
Signature
geometric_type <-> geometric_type → double precisionParameters
| Parameter | Type | Description |
|---|---|---|
| shape1 | geometric type | First object |
| shape2 | geometric type | Second object |
Examples
SELECT '(0,0)'::point <-> '(3,4)'::point;5SELECT * FROM pois ORDER BY location <-> '(10,10)'::point LIMIT 5;5 closest points to (10,10)SELECT id, name, coords <-> '(51.5,-0.1)'::point AS dist FROM venues ORDER BY dist LIMIT 3;3 nearest venues to reference pointSELECT '((0,0),(1,1))'::box <-> '((3,3),(4,4))'::box;2.8284... (distance between closest box corners)Without a GiST index, `ORDER BY coords <-> target LIMIT k` performs a full sequential scan computing the distance to every row before sorting — this is O(n) and catastrophically slow on large tables.
✓ Instead: Always create `CREATE INDEX ON tbl USING GIST (coords)` before running KNN queries. Confirm index use with EXPLAIN — look for 'Index Scan using … (order: <->)'.
Create a GiST index on point columns and use `ORDER BY location <-> target LIMIT k` for fast K-nearest-neighbor queries. The planner uses the index to avoid scanning all rows.
CREATE INDEX ON locations USING GIST (coords);
SELECT id, name FROM locations ORDER BY coords <-> '(40.7,-74.0)'::point LIMIT 10;10 nearest locations to a point — index-accelerated