<div dir="ltr"><div>Hello PostGIS users, <br></div><div><br></div><div>I am looking for a way to increase the speed of my query with KNN. <br></div><div><br></div><div>I have two tables with millions of points in each table. I would like to find the nearest neighbor (only one) of my points in table A with my points in table B.</div><div><br></div><div>I wrote the following query: <br></div><div><br></div><div>WITH index_query as (<br>  SELECT<br>    <a href="http://t1.id">t1.id</a>,<br>    t1.geom AS geom,<br>    t2.geom AS geom2, <br>    t1.geom <-> t2.geom AS distance<br>  FROM research_scrapper.table1 t1, <br>      research_scrapper.table2 t2<br>  ORDER BY t1.geom <-> t2.geom<br>)<br>SELECT tbl.cas_id, tbl.geom <br>FROM index_query tbl<br>INNER JOIN<br>    (<br>        SELECT geom2, <br>               MIN(distance) as distance<br>        FROM index_query <br>        GROUP BY geom2<br>    )tbl1<br>    ON tbl1.geom_generated=tbl.geom_generated<br>    AND tbl1.distance = tbl.distance<br></div><div><br></div><div>This is taking forever, would you have any suggestions on how to increase the efficiency?</div><div><br></div><div>Thanks for your help,</div><div><br></div></div>