I have a table (Table2) containing some areas (polygons) that are stored as geography data type. The table contains 1529 rows. In another table (Table1), I have approx. 22000 rows, each having an X/Y from which I create Points that are stored in a Geography column.
I need to make a spatial join to find out which area each point belongs to. I have created a spatial index on both tables, but I think the query is too slow. Right now, it takes about 72 seconds to make the join which looks like this:
SELECT ...
FROM [DatabaseA].dbo.Table1 t1
INNER JOIN [DatabaseB].dbo.Table2 t2 ON t1.Geo.STIntersects(t2.Geo) = 1
WHERE t2.ObjectTypeId = 1 AND t2.CompanyId = 3
Please note that the two tables are in different databases but on the same server.
Before creating the spatial index, the query was much slower and I can see that the index is being used. However, creating the index on table2 does not affect performance, only the index on table1 gives better performance. Both indexes have High level grids
When I look at the execution plan, I notice a Filter part that takes 71% of the time:
CASE WHEN [Expr1015]>(2) THEN CASE WHEN [Expr1016]=[Expr1017] THEN (1) ELSE (0) END ELSE [DatabaseA].[dbo].[Table1].[Geo] as [t].[Geo].STIntersects([DatabaseB].[dbo].[Table2].[Geo] as [g].[Geo]) END=(1)
So, my question is:
Should this query be taking so long? Should I use other grid sizes? What does that filter expression mean?
Does anybody have a tip for optimizing this?