<div dir="ltr">Thanks David for your feedback. I got it down to 4ms or so. Below is the explain analyze. It's 2 subqueries now. Any ideas for simplification of the query?<br><div dir="ltr"><div><br></div><div><div>explain analyze WITH knn_query AS</div>
<div>(</div><div> SELECT</div><div> *</div><div> FROM places</div><div> WHERE "places"."place_category_id" = 10</div><div> ORDER by geom <#> 'SRID=4326;POINT(-79.3937393 43.6526704)' LIMIT 50</div>
<div> )</div><div>SELECT *,</div><div>ST_Distance_Sphere(geom, 'SRID=4326;POINT(-79.3937393 43.6526704)') as distance</div><div>FROM (</div><div>SELECT * FROM knn_query</div><div>ORDER BY ST_Distance(geom, 'SRID=4326;POINT(-79.3937393 43.6526704)') ASC</div>
<div>LIMIT 5</div><div>) places;</div><div> QUERY PLAN </div><div>-----------------------------------------------------------------------------------------------------------------------------------------------------</div>
<div> Subquery Scan on places (cost=107.29..108.62 rows=5 width=1672) (actual time=2.893..3.564 rows=5 loops=1)</div><div> CTE knn_query</div><div> -> Limit (cost=0.00..92.96 rows=50 width=2062) (actual time=0.141..1.434 rows=50 loops=1)</div>
<div> -> Index Scan using index_places_on_geom on places (cost=0.00..2102.78 rows=1131 width=2062) (actual time=0.140..1.424 rows=50 loops=1)</div><div> Order By: (geom <#> '0101000020E61000009829520633D953C09B8823B48AD34540'::geometry)</div>
<div> Filter: (place_category_id = 10)</div><div> Rows Removed by Filter: 136</div><div> -> Limit (cost=14.33..14.34 rows=5 width=1672) (actual time=2.275..2.277 rows=5 loops=1)</div>
<div> -> Sort (cost=14.33..14.46 rows=50 width=1672) (actual time=2.274..2.276 rows=5 loops=1)</div><div> Sort Key: (st_distance(knn_query.geom, '0101000020E61000009829520633D953C09B8823B48AD34540'::geometry))</div>
<div> Sort Method: top-N heapsort Memory: 27kB</div><div> -> CTE Scan on knn_query (cost=0.00..13.50 rows=50 width=1672) (actual time=0.496..2.201 rows=50 loops=1)</div><div> Total runtime: 3.642 ms</div>
</div></div></div>