Log inSign up

Store and query location data with PostGIS

Install the PostGIS package that matches your PostgreSQL major version (for example postgresql-16-postgis-3 on Ubuntu 24.04), then run CREATE EXTENSION postgis; inside the database that needs it. Store coordinates in a geography(Point, 4326) column, add a GiST index, and use ST_DWithin and the <-> operator for radius searches and nearest results.

Topic: Databases · Tested on: Ubuntu 24.04 and 22.04, Debian 12 and 13, Rocky Linux 9, AlmaLinux 9 · Updated 2026-12-03

What do you need before installing PostGIS?

A running PostgreSQL server and a database to work in. PostGIS is an extension, so it is installed once per server and enabled per database.

If PostgreSQL is not set up yet, follow the PostgreSQL install guide first. Then find out which major version you are running, because the PostGIS package name includes it:

psql --version
sudo -u postgres psql -c "SHOW server_version;"

Spatial queries are mostly CPU and memory bound. A few hundred thousand points run comfortably on a small server; country-scale datasets with polygons benefit from more RAM so indexes stay cached.

How do you install PostGIS on Ubuntu or Debian?

Install the package named after your PostgreSQL version, plus the postgis package for command-line loaders.

apt policy 'postgresql-*-postgis-3' | grep -E "^postgresql|Candidate"
# Ubuntu 24.04 with distro PostgreSQL 16
sudo apt install -y postgresql-16-postgis-3 postgis
# Debian 12 ships PostgreSQL 15, Debian 13 ships 17
sudo apt install -y postgresql-15-postgis-3 postgis
sudo apt install -y postgresql-17-postgis-3 postgis

Run only the line for your release. If you use the PostgreSQL project repository (as in the replication guide), the same names are available for every supported major version, so postgresql-17-postgis-3 works on Ubuntu 22.04 as well. No restart is needed after the install.

How do you install PostGIS on Rocky Linux or AlmaLinux?

Use the PostgreSQL project repository together with EPEL and the CRB repository, which provide the geometry libraries PostGIS links against.

sudo dnf install -y epel-release
sudo dnf config-manager --set-enabled crb
sudo dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-9-x86_64/pgdg-redhat-repo-latest.noarch.rpm
sudo dnf -qy module disable postgresql
sudo dnf list available 'postgis*_17'
sudo dnf install -y postgis35_17

The package name joins the PostGIS series and the PostgreSQL version, so postgis35_17 means PostGIS 3.5 for PostgreSQL 17. Pick the newest series the list shows for your server version. If dnf complains about missing GDAL or PROJ libraries, CRB is not enabled.

How do you enable PostGIS in a database?

Connect to the target database as a superuser and create the extension. Then check the version string to confirm every component loaded.

sudo -u postgres createdb places
sudo -u postgres psql places -c "CREATE EXTENSION IF NOT EXISTS postgis;"
sudo -u postgres psql places -c "SELECT postgis_full_version();"

The output lists PostGIS together with the GEOS, PROJ and GDAL versions it uses. Give your application role rights on the schema rather than superuser powers:

sudo -u postgres psql places -c "CREATE ROLE mapapp LOGIN PASSWORD 'change-me';"
sudo -u postgres psql places -c "GRANT USAGE, CREATE ON SCHEMA public TO mapapp;"

Replace the sample password, and see the roles guide for a tidier permission model. Optional extras such as postgis_topology or postgis_raster are enabled the same way, only when you need them.

Should you use geometry or geography?

Use geography for latitude and longitude data spread across a large area, and geometry for local projected data or heavy polygon work. The difference is how distance is measured.

  • geography works on the sphere. Distances come back in meters and are correct anywhere on Earth, but fewer functions accept it.
  • geometry works on a flat plane in the units of its coordinate system. With SRID 4326 those units are degrees, which is meaningless for distance, so you either transform to a local projection or cast to geography.

SRID 4326 is the WGS 84 system used by GPS and most web maps. Note the order: PostGIS expects longitude first, latitude second, the opposite of how many apps display coordinates. Mixing them up is the most common bug in new spatial code.

How do you store and index points?

Create a table with a geography column, insert points with ST_MakePoint, and add a GiST index so spatial filters do not scan every row.

CREATE TABLE shops (
  id    bigserial PRIMARY KEY,
  name  text NOT NULL,
  geog  geography(Point, 4326) NOT NULL
);
INSERT INTO shops (name, geog) VALUES
  ('Harbor Street', ST_SetSRID(ST_MakePoint(4.8952, 52.3702), 4326)::geography),
  ('Station Square', ST_SetSRID(ST_MakePoint(4.9003, 52.3791), 4326)::geography),
  ('Canal Corner', ST_SetSRID(ST_MakePoint(4.8834, 52.3667), 4326)::geography);
CREATE INDEX shops_geog_idx ON shops USING gist (geog);
ANALYZE shops;

For text coming from an API, ST_GeogFromText('POINT(4.8952 52.3702)') does the same job. Points, lines and polygons can all live in geography columns; just change the type modifier.

How do you run distance and radius queries?

Use ST_DWithin for a radius filter (it can use the index), ST_Distance for the actual value, and the <-> operator with ORDER BY and LIMIT for the closest matches.

-- shops within 1 km of a customer
SELECT name, round(ST_Distance(geog, ST_MakePoint(4.8970, 52.3730)::geography)) AS meters
FROM shops
WHERE ST_DWithin(geog, ST_MakePoint(4.8970, 52.3730)::geography, 1000)
ORDER BY meters;

-- the two nearest shops
SELECT name
FROM shops
ORDER BY geog <-> ST_MakePoint(4.8970, 52.3730)::geography
LIMIT 2;

-- confirm the index is used
EXPLAIN ANALYZE SELECT count(*) FROM shops
WHERE ST_DWithin(geog, ST_MakePoint(4.8970, 52.3730)::geography, 1000);

Avoid filtering with ST_Distance(...) < 1000 in the WHERE clause: it computes the distance for every row instead of using the index. On larger tables, the EXPLAIN output should mention an index scan on shops_geog_idx.

How do you import real map data?

Load shapefiles with shp2pgsql, and GeoJSON, GeoPackage or KML with ogr2ogr from GDAL.

# Ubuntu/Debian: shp2pgsql comes with the postgis package
sudo apt install -y gdal-bin
shp2pgsql -s 4326 -I districts.shp public.districts | psql -h localhost -U mapapp places
ogr2ogr -f PostgreSQL "PG:host=localhost dbname=places user=mapapp" parks.geojson -nln parks -lco GEOMETRY_NAME=geom

On Rocky and Alma, shp2pgsql sits in /usr/pgsql-17/bin/ and GDAL comes from EPEL as gdal. Upload the files first with scp or rsync. After importing polygons, a point-in-area lookup is one join: SELECT d.name FROM districts d JOIN shops s ON ST_Intersects(d.geom, s.geog::geometry);.

How do you keep PostGIS updated?

Update the package with the rest of the system, then upgrade the extension inside each database that uses it.

sudo apt update && sudo apt upgrade -y        # or: sudo dnf upgrade -y
sudo -u postgres psql places -c "SELECT postgis_extensions_upgrade();"
sudo -u postgres psql places -c "SELECT postgis_full_version();"

When you move PostgreSQL to a new major version, install the matching PostGIS package for the new version before running pg_upgrade or restoring a dump. Include the spatial databases in your regular PostgreSQL backups; pg_dump handles the extension and data together.

Plans that fit this guide

Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.

All prices
PlanFits becauseSizeMonthlyOrder from
A2-4city or regional datasets2 vCPU, 4 GB RAM, 100 GB NVMe$14.40/mo$43.20 for 3 months
A4-8polygon-heavy national data4 vCPU, 8 GB RAM, 180 GB NVMe$28.80/mo$86.40 for 3 months

Questions about PostGIS for location data

Do I need PostGIS in every database?

Only in the databases that use spatial types. The package is installed once per server and CREATE EXTENSION postgis is run in each database that needs it.

Why are my distances in degrees?

You used a geometry column with SRID 4326. Cast to geography (geog::geography) or store the data as geography to get meters.

Why do my points appear in the ocean?

Latitude and longitude are swapped. ST_MakePoint takes longitude first, then latitude.

Can PostGIS geocode street addresses?

Not on its own. It stores and queries coordinates; turning addresses into coordinates needs a separate geocoder or a dataset you load yourself.

Does the GiST index need maintenance?

Regular autovacuum and ANALYZE keep it efficient. After a very large import, run VACUUM ANALYZE on the table so the planner has fresh statistics.