[Solved] What is the fastest way to compare polygon geometry data?

EverSQL Database Performance Knowledge Base

What is the fastest way to compare polygon geometry data?

We have two tables with polygons stored in geometry type columns.

I want to fetch the polygons present in one table that are not present in another table.

As of now I am doing a left outer join and using STAsText(), however that is taking a very long time.

FYI, we have approximately 120 million polygons in both tables.

Is there a fast way of comparing geometry type data? Maybe I need to use the spatial indexing, however I am not aware of this.

SELECT newPolygon.* 
FROM table1 newPolygon 
    LEFT JOIN table2 oldPolygon 
        ON newPolygon.Shape.STAsText() = oldPolygon.Shape.STAsText() 
WHERE oldPolygon.Shape IS NULL

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  2. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `table2` ADD INDEX `table2_idx_shape` (`Shape`);
The optimized query:
SELECT
        newPolygon.* 
    FROM
        table1 newPolygon 
    LEFT JOIN
        table2 oldPolygon 
            ON newPolygon.Shape.STAsText() = oldPolygon.Shape.STAsText() 
    WHERE
        oldPolygon.Shape IS NULL

Related Articles



* original question posted on StackOverflow here.