Name

<-> — Returns the 2D distance between A and B.

Synopsis

double precision <->( geometry A , geometry B );

double precision <->( geography A , geography B );

Description

The <-> operator returns the 2D distance between two geometries. Used in the "ORDER BY" clause provides index-assisted nearest-neighbor result sets with true KNN distance search for geometries, and distance on the sphere for geographies.

[Note]

This operand will make use of 2D GiST indexes that may be available on the geometries. It is different from other operators that use spatial indexes in that the spatial index is only used when the operator is in the ORDER BY clause.

[Note]

A GiST distance-ordered scan compares the indexed column to a value that is fixed for that scan. This can be a literal, a query parameter, or a value supplied by an outer row in a LATERAL join.

Refer to PostGIS workshop: Nearest-Neighbor Searching for a detailed example.

Enhanced: 2.2.0 -- True KNN ("K nearest neighbor") behavior for geometry and geography. Note for geography KNN is based on sphere rather than spheroid.

Availability: 2.0.0 -- Weak KNN provides nearest neighbors based on geometry centroid distances instead of true distances. Exact results for points, inexact for all other types.

Examples

Code
SELECT ST_Distance(geom, 'SRID=3005;POINT(1011102 450541)'::geometry) as d, edabbr, vaabbr
FROM va2005
ORDER BY d limit 10;
Output
        d         | edabbr | vaabbr
------------------+--------+--------
                0 | ALQ    | 128
 5541.57712511724 | ALQ    | 129A
 5579.67450712005 | ALQ    | 001
  6083.4207708641 | ALQ    | 131
  7691.2205404848 | ALQ    | 003
 7900.75451037313 | ALQ    | 122
 8694.20710669982 | ALQ    | 129B
 9564.24289057111 | ALQ    | 130
  12089.665931705 | ALQ    | 127
 18472.5531479404 | ALQ    | 002
(10 rows)

Then the KNN raw answer:

Code
SELECT ST_Distance(geom, 'SRID=3005;POINT(1011102 450541)'::geometry) as d,edabbr, vaabbr
FROM va2005
ORDER BY geom <-> 'SRID=3005;POINT(1011102 450541)'::geometry limit 10;
Output
        d         | edabbr | vaabbr
------------------+--------+--------
                0 | ALQ    | 128
 5541.57712511724 | ALQ    | 129A
 5579.67450712005 | ALQ    | 001
  6083.4207708641 | ALQ    | 131
  7691.2205404848 | ALQ    | 003
 7900.75451037313 | ALQ    | 122
 8694.20710669982 | ALQ    | 129B
 9564.24289057111 | ALQ    | 130
  12089.665931705 | ALQ    | 127
 18472.5531479404 | ALQ    | 002
(10 rows)

If you run "EXPLAIN ANALYZE" on the two queries you would see a performance improvement for the second.

To find the nearest candidate for each query point, use a LATERAL subquery with the distance operator in its ORDER BY. The inner scan uses the current query point as its search value.

Code
CREATE TEMP TABLE candidates AS
SELECT n AS id, ST_MakePoint(n, 0) AS geom
FROM generate_series(1, 10000) AS n;
CREATE INDEX candidates_geom_idx ON candidates USING gist (geom);
ANALYZE candidates;

SELECT q.id AS query_id, nearest.id AS nearest_id
FROM (VALUES (1, ST_MakePoint(2.1, 0)),
             (2, ST_MakePoint(9.9, 0))) AS q(id, geom)
CROSS JOIN LATERAL (
    SELECT c.id
    FROM candidates AS c
    ORDER BY c.geom <-> q.geom
    LIMIT 1
) AS nearest
ORDER BY q.id;
Output
 query_id | nearest_id
----------+------------
        1 |          2
        2 |         10
(2 rows)

To keep each query point and limit the search to candidates within a radius, reuse the candidates table with LEFT JOIN LATERAL and put ST_DWithin inside the subquery. A query point with no qualifying candidate has a null nearest ID.

Code
SELECT q.id AS query_id, nearest.id AS nearest_id
FROM (VALUES (1, ST_MakePoint(2.1, 0)),
             (2, ST_MakePoint(-2, 0))) AS q(id, geom)
LEFT JOIN LATERAL (
    SELECT c.id
    FROM candidates AS c
    WHERE ST_DWithin(c.geom, q.geom, 1)
    ORDER BY c.geom <-> q.geom
    LIMIT 1
) AS nearest ON true
ORDER BY q.id;
Output
 query_id | nearest_id
----------+------------
        1 |          2
        2 |
(2 rows)

For geography, spherical and spheroidal distances can rank the same candidates differently. In this example, the operator ranks east first, while ST_Distance with its default spheroidal distance ranks north first. To find the nearest candidate by spheroidal distance, order the full candidate set by that distance. If the search is bounded by a radius, use ST_DWithin to filter by that radius before sorting.

Code
WITH candidates(id, geog) AS (
    VALUES ('east', 'SRID=4326;POINT(1 0)'::geography),
           ('north', 'SRID=4326;POINT(0 1.003)')
), origin(geog) AS (
    VALUES ('SRID=4326;POINT(0 0)'::geography)
)
SELECT id,
       round(c.geog <-> o.geog) AS sphere_m,
       round(ST_Distance(c.geog, o.geog)) AS spheroid_m
FROM candidates AS c CROSS JOIN origin AS o
ORDER BY c.geog <-> o.geog;
Output
  id   | sphere_m | spheroid_m
-------+----------+------------
 east  |   111195 |     111319
 north |   111529 |     110906
(2 rows)