Skip to content
Skills Library
Data & analytics · Building & coding

postgis-spatial-query-optimization

/postgis-spatial-query-optimization

Architect, index, and optimize spatial databases using PostgreSQL and PostGIS. Master geometry vs geography data types, spatial reference systems (SRID 4326 vs 3857), GiST and SP-GiST indexing, spatial joins, K-Nearest Neighbor (KNN) distance queries, and spatial clustering with ST_ClusterDBSCAN. Trigger when designing GIS schemas, optimizing geo-queries, or processing spatial datasets.

Licence
MIT
Last repository change
16.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 16.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

Architect, index, and optimize spatial databases using PostgreSQL and PostGIS. Master geometry vs geography data types, spatial reference systems (SRID 4326 vs 3857), GiST and SP-GiST indexing, spatial joins, K-Nearest Neighbor (KNN) distance queries, and spatial clustering with ST_ClusterDBSCAN. Trigger when designing GIS schemas, optimizing geo-queries, or processing spatial datasets.

Original author description

Architect, index, and optimize spatial databases using PostgreSQL and PostGIS. Master geometry vs geography data types, spatial reference systems (SRID 4326 vs 3857), GiST and SP-GiST indexing, spatial joins, K-Nearest Neighbor (KNN) distance queries, and spatial clustering with ST_ClusterDBSCAN. Trigger when designing GIS schemas, optimizing geo-queries, or processing spatial datasets.

How it works

  1. 1. Spatial Indexing & Coordinate Systems
  2. 2. Production SQL Patterns & Optimization
  3. 3. Performance Best Practices
Original SKILL.md headings · 102 lines, 442 words
SKILL.md preview
---
name: postgis-spatial-query-optimization
metadata:
  category: Geospatial and GIS Engineering
description: Architect, index, and optimize spatial databases using PostgreSQL and PostGIS. Master geometry vs geography data types, spatial reference systems (SRID 4326 vs 3857), GiST and SP-GiST indexing, spatial joins, K-Nearest Neighbor (KNN) distance queries, and spatial clustering with ST_ClusterDBSCAN. Trigger when designing GIS schemas, optimizing geo-queries, or processing spatial datasets.
compatibility: PostgreSQL 14+, PostGIS 3.3+
---

# PostGIS Spatial Query Optimization Skill Guide

This skill establishes database modeling standards and query optimization strategies for high-volume geospatial systems using PostgreSQL and the PostGIS extension.

---

## 1. Spatial Indexing & Coordinate Systems

```text
[ Coordinate System Reference (SRID) ]
  |-- EPSG:4326 (WGS 84): Unprojected Lat/Long in degrees (GPS standard)
  |-- EPSG:3857 (Web Mercator): Projected coordinates in meters (Tile rendering)
  |
  v
[ PostGIS Column Storage ]
  |-- GEOMETRY: Flat Euclidean planar calculations (Fast, accurate on local scales)
  |-- GEOGRAPHY: Spheroidal great-circle calculations (Accurate globally across poles/equator)
  |
  v
[ Spatial Indexing (GiST / SP-GiST) ]
  +---> R-Tree Bounding Box (BBOX) index eliminates 99%+ of non-intersecting shapes
```

---

## 2. Production SQL Patterns & Optimization

### A. Schema Definition with Spatial Indexing

```sql
-- Enable PostGIS extensions
CREATE EXTENSION IF NOT EXISTS postgis;
CREATE EXTENSION IF NOT EXISTS postgis_topology;

-- High-performance delivery zones table
CREATE TABLE delivery_zones (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    merchant_id UUID NOT NULL,
    zone_name VARCHAR(100) NOT NULL,
    boundary GEOMETRY(Polygon, 4326) NOT NULL,
    created_at TIMESTAMPTZ DEFAULT clock_timestamp()
);

-- Bounding Box R-Tree Index
CREATE INDEX idx_delivery_zones_boundary ON delivery_zones USING GIST (boundary);

-- Driver tracking with Geography for real-world meter accuracy
CREATE TABLE driver_locations (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    driver_id UUID NOT NULL,
    current_location GEOGRAPHY(Point, 4326) NOT NULL,
    updated_at TIMESTAMPTZ NOT NULL
);

CREATE INDEX idx_driver_locations_geog ON driver_locations USING GIST (current_location);
```

### B. K-Nearest Neighbor (KNN) Index-Accelerated Query

```sql
-- Finds the 5 closest available drivers within 10 km (10,000 meters)
-- PostGIS `<->` operator performs indexed bounding box distance search
WITH target_pickup AS (
    SELECT ST_SetSRID(ST_MakePoint(-122.4194, 37.7749), 4326)::geography AS pickup_geom
)
SELECT 
    d.driver_id,
    ST_Distance(d.current_location, t.pickup_geom) AS distance_meters
FROM driver_locations d, target_pickup t
WHERE ST_DWithin(d.current_location, t.pickup_geom, 10000) -- Restricts search radius
ORDER BY d.current_location <-> t.pickup_geom
LIMIT 5;
```

### C. Spatial Join with Bounding Box Pre-Filter

```sql
-- Check which orders fall inside active merchant delivery zones
SELECT 
    o.id AS order_id,
    z.zone_name,
    z.merchant_id
FROM orders o
JOIN delivery_zones z 
    ON z.boundary && o.delivery_location -- Fast Bounding Box overlap pre-filter
    AND ST_Contains(z.boundary, o.delivery_location) -- Exact polygon evaluation
WHERE z.merchant_id = 'c38a264a-251f-4ffb-88a4-0ef6630f9ec9';
```

---

## 3. Performance Best Practices

1. **Bounding Box Pre-Filtering (`&&`):** PostGIS functions like `ST_Intersects` and `ST_Contains` automatically use bounding box checks, but when writing custom filters, always leverage `&&` to engage GiST indexes.
2. **Transformations in Queries:** Never run `ST_Transform(column, 3857)` in a `WHERE` clause without a functional index; transform input literals instead:
   ```sql
   -- FAST: transforms literal, keeps index active
   WHERE geom && ST_Transform(ST_MakePoint(...), 4326)
   ```
3. **Clustering & Vacuuming:** Regularly execute `CLUSTER delivery_zones USING idx_delivery_zones_boundary` on read-heavy spatial tables to align on-disk storage with Hilbert curve spatial locality.

Versions

The database has no other skills named postgis-spatial-query-optimization.

Database snapshot: 13.11.2026 · package version 5f11d9ff1ef6 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 1 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100postgis
    Use when extending PostgreSQL with PostGIS 3.6.4 — geometry/geography/raster types, GiST and KNN <-> indexes, ST_Intersects/ST_Buffer/ST_Transform/ST_AsMVT, shp2pgsql -I and raster2pgsql import, and fixing \"Operation on mixed SRID\", slow spatial joins, and invalid polygons with ST_MakeValid.
  • 100design-postgis-schema
    Design a PostGIS table for spatial data — pick the CRS (SRID) and geometry-vs-geography type by use-case, declare the column with an explicit SRID, add the right GiST/SP-GiST spatial index, and emit a runnable CREATE TABLE + index. Reach for this when the user wants to store…
  • 100postgis-spatial-sql
    Invoke whenever spatial SQL or its execution backend is the decision: PostGIS, DuckDB Spatial, SpatiaLite, ST_* functions, recurring spatial joins, concurrent/growing workloads, or large GeoParquet queries. Covers backend selection, schemas, GiST/BRIN indexes, KNN, geometry…
  • 100postgis
    PostGIS-specific SQL tips and gotchas. Use when working with geometry, geography, raster, projections, spatial indexes, or geospatial processing in PostgreSQL through PostGIS.
  • 100spatial-sql
    Write correct, fast, read-only spatial SQL for PostGIS, Oracle Spatial (SDO_RELATE, SDO_WITHIN_DISTANCE) and SQL Server (STIntersects, geography), covering intersects, within a distance, nearest, bounding-box filters, areas and lengths. Use when asked to query a spatial…
  • 100spatial-sql
    Write, review, debug or optimize spatial SQL on an already chosen engine, including DuckDB Spatial, PostGIS, BigQuery GIS, Snowflake and Sedona. Use for spatial predicates, joins, indexes, query plans, CRS and metric/geodesic correctness. Route unresolved engine or cross-system…

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.