I have written a query to fetch the polygon data from Sql database.
I have following query to fetch the results.
SELECT ZIP,
NAME,
STABB,
AREA,
TYPE,
orgZc.OrganizationId,
orgZc.[ZipCode] AS ORGzip,
REPLACE(REPLACE(REPLACE(REPLACE(GEOM.STAsText(),'POLYGON ((',' '),'MULTIPOLYGON (((',' '),'))',''),')))','')AS WKT
FROM USZIP
INNER JOIN ORGANIZTION_ZIP_CODES orgZc ON orgZc.[ZipCode]=USZIP.zip
WHERE orgZc.OrganizationId=@ORGANIZATION_ID
On this table i have already added a spatial index as below
CREATE SPATIAL INDEX SIndx_SpatialTable_geometry_col1
ON USZIP(GEOM) WITH ( BOUNDING_BOX = ( -90, -180, 90, 180 ) );
But it took 38 sec to fetch the 2483 records. Can anyone help me to optimize this query
My guess is that important part of your query is the
fromandwhereclauses. However, you can test this by removing the line:To see if that processing is taking up a lot of time.
For this part of the query:
You say that the zip code is "a primary column". However, it has to be the first column in a composite index (or primary key) in order to be used for the join. So, you really want an index on
USZIP(zip)for the join to work. (I'm guessing this is true based on the name of the table, but I want to be explicit.)Second, your
whereclause is limited to oneOriganizationId, presumably of many. If so, you want an index onORGANIZATION_ZIP_CODES(OrganizationId). Or, better yet, onORGANIZATION_ZIP_CODES(OrganizationId, ZipCode).