Return the grid distance between two H3 cells as an integer number of hex steps.
H3_GRID_DISTANCE(cell1, cell2)
## Overview Returns the grid distance between two H3 cells, defined as the minimum number of adjacent hex steps required to travel from one cell to the other. Because all cells on the grid are hexagons (with twelve pentagonal exceptions), grid distance is integer-valued and matches the intuition of how many cells you traverse. It is not a meter distance; to convert, multiply by H3_EDGE_LENGTH of one of the cells (roughly). Use it for ring expansions, fast proximity ranking where Haversine is not needed, corridor queries, and for estimating how large a k-disk must be to cover a target region. ## Behavior - Returns a BIGINT representing the number of hex steps, which is zero or positive. - Returns NULL if the two cells are at different resolutions. - Returns NULL if the pair is not connected in the grid (for example because a pentagon falls between them), since pentagon distortion can prevent a clean hex-step path. - Returns NULL if either input is NULL or not a valid H3 cell. - Symmetric: H3_GRID_DISTANCE(a, b) = H3_GRID_DISTANCE(b, a). - Zero if both inputs are the same cell. - Deterministic: the same pair always returns the same distance. ## H3 resolution reference | Res | Average edge length | 1 step approximates | | --- | --- | --- | | 7 | 1.22 km | ~1.22 km | | 8 | 461 m | ~461 m | | 9 | 174 m | ~174 m | | 10 | 65.9 m | ~65.9 m | | 12 | 9.4 m | ~9.4 m | ## Compatibility - Follows the standard H3 hierarchical hex grid specification for grid distance.
| Name | Type | Description |
|---|---|---|
cell1 | Specifies the first H3 cell index. Must be a valid H3 cell at the same resolution as cell2. | |
cell2 | Specifies the second H3 cell index. Must be a valid H3 cell at the same resolution as cell1. |
SELECT H3_GRID_DISTANCE(
H3_LATLNG_TO_CELL(40.7128, -74.0060, 9),
H3_LATLNG_TO_CELL(40.7128, -74.0060, 9)
) AS dist_steps;
-- Two nearby resolution 9 cells separated by a few hex steps.
SELECT H3_GRID_DISTANCE(
H3_LATLNG_TO_CELL(40.7580, -73.9855, 9),
H3_LATLNG_TO_CELL(40.7614, -73.9776, 9)
) AS dist_steps;
-- A k-step distance covers roughly k * edge_length meters.
SELECT
H3_GRID_DISTANCE(a, b) AS steps,
H3_GRID_DISTANCE(a, b) * H3_EDGE_LENGTH(a) AS approx_m
FROM (
SELECT H3_LATLNG_TO_CELL(35.6762, 139.6503, 9) AS a,
H3_LATLNG_TO_CELL(35.6812, 139.7671, 9) AS b
);
-- Sort candidate venues by the number of grid steps from a user cell.
WITH user_cell AS (SELECT H3_LATLNG_TO_CELL(51.5074, -0.1278, 9) AS c)
SELECT v.venue_id,
H3_GRID_DISTANCE(u.c, H3_LATLNG_TO_CELL(v.lat, v.lng, 9)) AS steps
FROM venues v CROSS JOIN user_cell u
ORDER BY steps
LIMIT 20;
-- Different resolutions, or paths blocked by pentagon distortion, return NULL.
SELECT H3_GRID_DISTANCE(
H3_LATLNG_TO_CELL(40.7128, -74.0060, 8),
H3_LATLNG_TO_CELL(40.7128, -74.0060, 9)
) AS dist;