SQL & Spatial Queries¶
SQL (Structured Query Language) allows you to interact directly with your PostGIS database. With just a few simple commands, you can filter data, calculate values, and run basic spatial checks. This page introduces the essential SQL and spatial functions you’ll use most often in pgAdmin.
You can download the full dataset used on this page by running the SQL script included here:
This dataset adds:
- places (10 Western Cape towns/cities with point geometry)
- place_types (City, Town, Village, Settlement)
- admin_boundaries (3 Western Cape municipal polygons)
- All constraints, foreign keys, indexes, and geometry types
Step 1: Open the Query Tool¶
You’ll run your SQL statements inside pgAdmin’s built-in editor.
-
In pgAdmin, expand kartoza_postgis → Schemas → public → Tables.
-
Select any table (e.g., places).
-
Click the Query Tool button in the top toolbar.
Step 2: Select Records¶
Begin by exploring your data using simple SELECT statements.
-
Show all rows
-
Show specific fields
-
Filter rows (WHERE)
These simple SELECT queries let you preview and inspect the attribute data stored in your PostGIS tables.
Step 3: Sort and Limit Results¶
Sorting and limiting output helps you quickly find useful information.
-
Sort by population (descending)
-
Show only the first 5 rows
Step 4: Basic Calculations¶
You can use SQL to calculate values on the fly.
-
Calculate population density
-
Count all records
Step 5: Basic Spatial Queries¶
PostGIS extends SQL with geometry functions to allow spatial filtering and analysis.
-
Find features within a bounding box
-
Select features within a radius
(Example: 50 km around a specific coordinate)
SELECT * FROM places WHERE ST_DWithin( ST_Transform(geom, 3857), ST_Transform(ST_SetSRID(ST_Point(18.5, -34.0), 4326), 3857), 50000 ); -
Measure distance between two features
SELECT a.name AS place_a, b.name AS place_b, ST_Distance(a.geom, b.geom) AS distance_m FROM places a, places b WHERE a.id = 1 AND b.id = 2;
Each spatial function returns a true/false result, distance, or filtered rows, perfect for building powerful GIS logic directly in the database.
Step 6: Update Data with SQL¶
SQL can also modify records. Make sure you understand what you’re updating before running these.
-
Update a field value
-
Assign a place type (City, Town, Village, etc.)
-
Delete a record
Step 7: Run Spatial Summaries¶
PostGIS makes it easy to summarise spatial relationships.
-
Count how many features fall inside a polygon
SELECT COUNT(*) FROM places WHERE ST_Within( geom, (SELECT geom FROM admin_boundaries WHERE name = 'Drakenstein') ); -
Calculate total area of polygons
Your database is now ready for real analysis. Even these basic SQL and spatial functions give you powerful control over your data.