db=# explain analyze SELECT DISTINCT l.numlieu, l.nomlieu, ROUND (earth_distance(ll_to_earth(48.85957600, 2.34860800), ll_to_earth(l.wgslat, l.wgslon))) as dist db-# FROM lieu l, lieugelieu lgl db-# WHERE lgl.codegelieu = 'PKG' AND earth_box(ll_to_earth(48.85957600, 2.34860800), 1750) @ ll_to_earth(l.wgslat, l.wgslon) AND lgl.numlieu = l.numlieu ORDER BY dist ASC LIMIT 2; QUERY PLAN --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Limit (cost=626.84..626.85 rows=1 width=51) (actual time=449.287..449.298 rows=2 loops=1) -> Unique (cost=626.84..626.85 rows=1 width=51) (actual time=449.283..449.290 rows=2 loops=1) -> Sort (cost=626.84..626.84 rows=1 width=51) (actual time=449.278..449.279 rows=2 loops=1) Sort Key: round(sec_to_gc(cube_distance('(4192714.86111655, 171959.656483755, 4803394.52951123)'::cube, (ll_to_earth((l.wgslat)::double precision, (l.wgslon)::double precision))::cube))), l.numlieu, l.nomlieu -> Nested Loop (cost=3.38..626.83 rows=1 width=51) (actual time=258.877..448.651 rows=78 loops=1) -> Bitmap Heap Scan on lieu l (cost=3.38..201.34 rows=106 width=51) (actual time=32.988..60.197 rows=5786 loops=1) Recheck Cond: ('(4190964.86112204, 170209.656489245, 4801644.52951672),(4194464.86111106, 173709.656478266, 4805144.52950574)'::cube @ (ll_to_earth((wgslat)::double precision, (wgslon)::double precision))::cube) -> Bitmap Index Scan on idx_lieu_earth (cost=0.00..3.38 rows=106 width=0) (actual time=30.229..30.229 rows=5864 loops=1) Index Cond: ('(4190964.86112204, 170209.656489245, 4801644.52951672),(4194464.86111106, 173709.656478266, 4805144.52950574)'::cube @ (ll_to_earth((wgslat)::double precision, (wgslon)::double precision))::cube) -> Index Scan using idx_lieugelieu_codegelieu_numlieu_principal on lieugelieu lgl (cost=0.00..4.00 rows=1 width=4) (actual time=0.052..0.052 rows=0 loops=5786) Index Cond: (((lgl.codegelieu)::text = 'PKG'::text) AND (lgl.numlieu = "outer".numlieu)) Total runtime: 449.607 ms (12 rows)