PostGIS: A Practical Introduction

PostGIS: A Practical Introduction

I have a ritual with new colleagues. Sometime in their first months, I ask them to find all the schools within five hundred meters of a main road in a dataset of two million features. Most of them reach for a desktop GIS, run a buffer, wait, grumble at the progress bar, and come back after twenty minutes. Then I show them a single line of SQL that returns the answer in under a second. The room goes quiet. Somebody always says the same thing: “Why didn’t anyone tell me about this earlier?”

The “this” is PostGIS, and I am telling you earlier. It is the single most valuable skill I know of for a GIS professional who has outgrown files and wants speed, scale and reliability. This guide is a practical, hands-on introduction. We will install it, create a spatial table, load data, run the queries that matter, make them fast, and avoid the traps that catch beginners.

You don’t need to be a database expert. If you can follow a recipe, you can follow this guide. For the broader architectural picture of where spatial databases fit, read Enterprise GIS & Spatial Databases: PostGIS, Geodatabases, and Server Architecture.

Diagram: PostGIS adds spatial types, spatial indexes and SQL functions to PostgreSQL so many tools can use the same data.
PostGIS adds spatial types, spatial indexes and SQL functions to PostgreSQL so many tools can use the same data.

What Is PostGIS?

PostGIS is an extension that adds spatial capabilities to PostgreSQL, one of the world’s most respected open-source relational databases. After you enable it, your database understands geometry: points, lines, polygons and more. It gains:

  • Spatial data types (geometry and geography) and raster support.
  • Hundreds of spatial functions, such as distance, intersection, buffer, area, union and containment, all callable from SQL.
  • Spatial indexes, which make location queries fast, even over millions of rows.
  • Standards compliance with the OGC Simple Features model, so data stays portable.

Because it’s PostgreSQL underneath, you also inherit proper transactions, security, backups, multi-user editing and replication. That is why PostGIS powers so many government, commercial and open-source systems, and why QGIS, ArcGIS, GeoServer and Python all connect to it easily.

Why use it instead of files?

Files are perfect for small projects. A database wins when you need:

  • Speed on large data, thanks to indexes.
  • Many people reading and editing the same data without overwriting each other.
  • A single source of truth, instead of copies scattered across folders.
  • Complex queries combining attributes and geometry in one step.
  • Automation: scheduled jobs, views and pipelines.

For small, single-user work, the GeoPackage is wonderful. See Shapefile vs. GeoJSON vs. GeoPackage: Which Format to Use?


Getting PostGIS Running

There are several routes. Pick the one that fits you.

  • Docker: the quickest and cleanest for learning. A ready-made image of PostgreSQL with PostGIS lets you start a database in a minute and throw it away afterward.
  • Installers: on Windows and macOS, PostgreSQL installers offer PostGIS as an additional component. On Linux, use your distribution’s packages.
  • Managed cloud databases: many providers offer PostgreSQL with PostGIS as a service, with backups and scaling handled for you.

You will also want a client to talk to the database:

  • pgAdmin: the standard graphical administration tool.
  • psql: the command-line client.
  • QGIS DB Manager: run SQL and view results as map layers.
  • DBeaver or similar: general-purpose database tools.

Check the official PostGIS and PostgreSQL documentation for current installation instructions, since versions and commands evolve.


Step 1: Create a Database and Enable PostGIS

Create a database (here named gis) and enable the extension inside it. Run these as a user with the right permissions.

CREATE DATABASE gis;
-- connect to the new database, then:
CREATE EXTENSION postgis;

Check that it works:

SELECT postgis_full_version();

If you see a version report, you are in business. The extension is enabled per database, so repeat CREATE EXTENSION postgis; in each database that needs it.


Step 2: Understand Geometry and SRID

Two ideas before writing tables.

Geometry types

PostGIS stores features using geometry types: POINT, LINESTRING, POLYGON, and their multi-part versions MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, plus collections. A column is declared with a type and a coordinate system, for example geometry(Point, 4326).

The SRID

Every geometry carries an SRID (spatial reference ID), the numeric code of its coordinate reference system. It’s usually the EPSG code: 4326 for WGS 84 latitude and longitude, 3857 for Web Mercator, and the many codes of national and UTM systems. PostGIS refuses to combine geometries with different SRIDs without explicit transformation, which protects you from silent mistakes. If the concept is unfamiliar, read Coordinate Reference Systems (CRS) Explained Simply.

Geometry vs. geography

PostGIS has two main types, and choosing between them matters.

  • geometry: works on a flat plane, in the units of the coordinate system. In a projected system such as UTM, distances and areas come out in meters. In latitude and longitude (4326), calculations are in degrees, which is rarely what you want.
  • geography: works on the curved Earth and always returns distances in meters and areas in square meters. It is easier and more accurate over large areas, but fewer functions support it and it can be slower.

A simple rule: store in geometry, in a projected CRS suited to your area, for analysis; use geography (or cast to it) for quick distance and area on global lat/lon data. For choosing a suitable system, see Map Projections: How to Choose the Right One.


Step 3: Create a Spatial Table

Let’s create a table of places, with a point geometry in WGS 84.

CREATE TABLE places (
    id    serial PRIMARY KEY,
    name  text NOT NULL,
    kind  text,
    geom  geometry(Point, 4326)
);

Insert a few rows. ST_MakePoint takes longitude first, then latitude, a classic source of mistakes, and ST_SetSRID labels the result with its SRID.

INSERT INTO places (name, kind, geom) VALUES
  ('Eiffel Tower',   'monument', ST_SetSRID(ST_MakePoint(2.2945, 48.8584), 4326)),
  ('Louvre Museum',  'museum',   ST_SetSRID(ST_MakePoint(2.3376, 48.8606), 4326)),
  ('Gare du Nord',   'station',  ST_SetSRID(ST_MakePoint(2.3553, 48.8809), 4326));

Look at the result as text:

SELECT name, ST_AsText(geom) FROM places;

Step 4: Add a Spatial Index

This is the most important performance step, and the one beginners forget. A spatial index lets the database skip almost all irrelevant rows. PostGIS uses a GiST index.

CREATE INDEX places_geom_idx ON places USING GIST (geom);
ANALYZE places;

ANALYZE updates the statistics that the query planner uses to decide how to run queries. Run it after loading large amounts of data. Without an index, a query over millions of rows scans them all. With one, it is almost instant.


Step 5: Load Your Own Data

You rarely type points by hand. Here are the usual ways to bring data in.

With QGIS

Use Database > DB Manager, connect to your database, and import a layer. You can choose the target table name, the geometry column, the SRID and whether to create a spatial index. It’s the friendliest route for beginners.

With ogr2ogr (GDAL)

A powerful command-line approach, ideal for repeating imports:

ogr2ogr -f PostgreSQL PG:"dbname=gis user=postgres host=localhost" \
  roads.gpkg roads \
  -nln public.roads \
  -lco GEOMETRY_NAME=geom \
  -lco FID=id \
  -nlt PROMOTE_TO_MULTI \
  -t_srs EPSG:4326

This reads a layer from a GeoPackage, creates a table named roads with a geometry column called geom and an id key, promotes geometries to multi-part (avoiding mixed types) and reprojects to 4326. GDAL is described further in Best Free and Open-Source GIS Tools.

With shp2pgsql

A tool bundled with PostGIS, for Shapefiles:

shp2pgsql -s 4326 -I schools.shp public.schools | psql -d gis -U postgres

The -s option sets the SRID and -I creates a spatial index.

With a CSV of coordinates

Import the table, then build the geometry from the coordinate columns:

ALTER TABLE stations ADD COLUMN geom geometry(Point, 4326);
UPDATE stations
SET geom = ST_SetSRID(ST_MakePoint(longitude, latitude), 4326);
CREATE INDEX stations_geom_idx ON stations USING GIST (geom);

After any import, check the SRID, create the index and run ANALYZE:

SELECT Find_SRID('public', 'roads', 'geom');

Step 6: Your First Spatial Queries

Now the fun begins. These examples show the patterns you will use every day.

Select by attribute and by location together

Which places are museums?

SELECT name FROM places WHERE kind = 'museum';

Distance between features

Distance in meters between two places, using geography:

SELECT ST_Distance(a.geom::geography, b.geom::geography) AS meters
FROM places a, places b
WHERE a.name = 'Eiffel Tower' AND b.name = 'Louvre Museum';

Find what is nearby: ST_DWithin

The right way to ask “everything within a distance” is ST_DWithin, which uses the spatial index. This finds places within 3,000 meters of the Eiffel Tower:

SELECT p.name
FROM places p, places ref
WHERE ref.name = 'Eiffel Tower'
  AND p.id <> ref.id
  AND ST_DWithin(p.geom::geography, ref.geom::geography, 3000);

A note about performance: casting a column to geography inside the query can prevent PostgreSQL from using a plain index on the geometry column. For large tables, either store a geography column with its own index, or use a projected geometry column and ST_DWithin in meters. The principle is: make sure the function can use an index.

Nearest neighbors with the distance operator

The <-> operator returns an indexed, distance-based ordering, ideal for “closest N”:

SELECT name
FROM places
ORDER BY geom <-> ST_SetSRID(ST_MakePoint(2.3522, 48.8566), 4326)
LIMIT 3;

Which polygon contains this point?

A spatial join, assigning each place to the district it lies in:

SELECT p.name, d.district_name
FROM places p
JOIN districts d ON ST_Intersects(d.geom, p.geom);

ST_Intersects is the workhorse predicate, ST_Within and ST_Contains test stricter relations. These correspond to the spatial relationships explained in How Does GIS Work? Layers, Data, and Analysis Explained.

Count features per polygon

SELECT d.district_name, COUNT(p.id) AS n_places
FROM districts d
LEFT JOIN places p ON ST_Intersects(d.geom, p.geom)
GROUP BY d.district_name
ORDER BY n_places DESC;

Areas and lengths

Area of each district in square kilometers, calculated on the curved Earth:

SELECT district_name,
       ST_Area(geom::geography) / 1000000 AS km2
FROM districts;

Length of roads in kilometers:

SELECT SUM(ST_Length(geom::geography)) / 1000 AS km FROM roads;

Buffers

Buffering in meters is only meaningful in a projected system, or with geography. Here is a 500-meter buffer calculated through geography, returned as a geometry:

SELECT id,
       ST_Buffer(geom::geography, 500)::geometry AS buffer_geom
FROM schools;

Reproject

Convert geometries between coordinate systems with ST_Transform:

SELECT ST_Transform(geom, 3857) FROM places;

A Real Question: Schools Near Main Roads

Remember my ritual? Here is the query, using a projected geometry column for speed. Assume both tables share a projected SRID (here 3857 for the illustration; in real work use a local projected system suited to your area).

SELECT DISTINCT s.id, s.name
FROM schools s
JOIN roads r
  ON ST_DWithin(s.geom, r.geom, 500)
WHERE r.road_class = 'primary';

Because both columns are indexed and share a projected CRS, the database can use the index to find candidate roads near each school and test the distance only for those. On large data, this can return in a fraction of a second what a desktop buffer-and-select would take minutes to do. The result can be loaded directly into QGIS as a layer.


Geometry Maintenance: Validity and Repair

Invalid geometries cause many mysterious errors. PostGIS gives you tools to find and fix them.

-- Find invalid polygons and the reason
SELECT id, ST_IsValidReason(geom)
FROM parcels
WHERE NOT ST_IsValid(geom);

-- Repair them
UPDATE parcels
SET geom = ST_MakeValid(geom)
WHERE NOT ST_IsValid(geom);

Make validity checks part of your routine after importing data. The problems and fixes are described in Top 10 Most Common GIS Errors and How to Fix Them.


Useful Functions to Know

TaskFunction
Create a point from coordinatesST_MakePoint, ST_SetSRID
Show geometry as text or GeoJSONST_AsText, ST_AsGeoJSON
Test relationshipsST_Intersects, ST_Contains, ST_Within, ST_Touches
Distance and proximityST_Distance, ST_DWithin, the <-> operator
Area, length, perimeterST_Area, ST_Length, ST_Perimeter
Create zonesST_Buffer
Combine and cutST_Union, ST_Intersection, ST_Difference
SimplifyST_Simplify, ST_SimplifyPreserveTopology
CentersST_Centroid, ST_PointOnSurface
ReprojectST_Transform
Validate and repairST_IsValid, ST_MakeValid
Collect many into oneST_Collect

Connecting PostGIS to Your Tools

  • QGIS: add a PostGIS connection in the Browser panel, and drag tables onto the map. You can edit data directly, and the changes are saved to the database. You can also add SQL views as layers.
  • ArcGIS Pro: connect with a database connection file and use query layers or enterprise geodatabase features.
  • GeoServer: publish tables as WMS and WFS services.
  • Python: use GeoPandas (read_postgis and to_postgis) or psycopg and SQLAlchemy for scripts. See Geospatial Development & Automation: The Ultimate Guide.
  • Web applications: serve data as GeoJSON or vector tiles from the database.

Views, Materialized Views and Pipelines

A view is a saved query that behaves like a table, a great way to publish a tidy, always-current layer without duplicating data.

CREATE VIEW primary_roads AS
SELECT id, name, geom FROM roads WHERE road_class = 'primary';

A materialized view stores the result physically and is refreshed on demand, which is useful for expensive calculations that you want to read quickly:

CREATE MATERIALIZED VIEW district_stats AS
SELECT d.district_name, COUNT(p.id) AS n_places
FROM districts d
LEFT JOIN places p ON ST_Intersects(d.geom, p.geom)
GROUP BY d.district_name;

REFRESH MATERIALIZED VIEW district_stats;

Views and scheduled jobs turn a database into a small analysis pipeline: raw data arrives, queries clean and aggregate it, and tools like QGIS or a web map read the finished result.


Performance Tips

  • Always create a spatial index (GiST) on geometry columns.
  • Run ANALYZE after bulk loads, and let autovacuum maintain the database.
  • Use the index-friendly functions: ST_DWithin rather than ST_Distance(...) < x, and ST_Intersects rather than computing intersections just to test emptiness.
  • Keep one SRID per column and store data in a projected CRS suited to your work, to avoid transforming inside every query.
  • Use EXPLAIN ANALYZE to see how PostgreSQL runs a query, and whether it uses your index.
  • Simplify geometries for display with ST_Simplify, not for analysis.
  • Filter early, with attribute conditions that reduce rows before expensive geometry work.
  • Store large datasets as multi-part types consistently, to avoid type mixing.
  • Avoid selecting more columns than you need, especially big geometries, when you only need counts.

Backups, Security and Maintenance

A database holding valuable data deserves care.

  • Back up regularly with pg_dump for logical backups, and consider continuous archiving for critical systems. Test restoring, not just backing up.
  • Use roles and permissions: give users only the access they need. Separate roles for reading, editing and administration.
  • Never use the superuser account for everyday work or applications.
  • Keep PostgreSQL and PostGIS updated, following the documented upgrade procedures.
  • Protect network access: restrict connections, use encrypted connections and strong passwords.
  • Document your schema: tables, columns, SRIDs and the meaning of fields, as described in Metadata in GIS: Why It Matters and How to Create It.

Common Beginner Mistakes

  • Forgetting the spatial index. The number one reason for slow queries.
  • Swapping longitude and latitude in ST_MakePoint. Longitude is X and comes first.
  • Measuring in degrees. Use geography or a projected SRID for meters.
  • Mixing SRIDs and then wondering why PostGIS complains. Fix them with ST_Transform.
  • Forgetting to label the SRID with ST_SetSRID when creating geometries.
  • Using ST_Distance in a filter instead of ST_DWithin, which defeats the index.
  • Storing mixed geometry types in one column when a single type is expected.
  • Skipping validity checks on imported data.
  • Editing production data without a backup.
  • Running everything as the superuser.

Where PostGIS Fits in Your Learning Path

PostGIS is a natural next step after you are comfortable with a desktop GIS such as QGIS, and before you tackle larger systems. A sensible path:

  1. Learn desktop GIS concepts and tools.
  2. Learn basic SQL: SELECT, WHERE, JOIN, GROUP BY.
  3. Add PostGIS: spatial types, indexes and the functions above.
  4. Connect it to QGIS and use it for real projects.
  5. Explore views, scripting and publishing.
  6. Study architecture and administration for shared systems.

If you plan a career in GIS, spatial SQL is among the most requested skills, as described in How to Become a GIS Analyst: Roadmap.


Final Thoughts

PostGIS changed how I work more than any other tool in the last twenty years. It taught me to think of spatial data as sets of rows to be queried, not pictures to be pushed around, and that shift makes many problems small. The learning curve is gentle if you take it one step at a time: enable the extension, create a table, add an index, run a query.

Today, take any layer of your own, load it into a PostGIS database, add a spatial index, and ask it one question with SQL. When the answer comes back in a blink, you will understand why I tell every new colleague about it.

Where to go next: continue with Enterprise GIS & Spatial Databases: PostGIS, Geodatabases, and Server Architecture for the architecture around your database, and Best Free and Open-Source GIS Tools for the rest of the open ecosystem.

Rachid Khouri

Rachid Khouri

Rachid Khouri is a CAD, BIM and GIS professional, Autodesk Authorized Developer, trainer and technical author with more than 30 years of experience, working with AutoCAD since 1992. He founded GISauthority.com to share practical guidance on GIS and spatial technologies.