skip to content

Using PostGIS in PostgreSQL for a delivery-zone feature, how do you store zones and addresses and query them so a GiST index is used?

level: middleimportance: should knowfreq 47%

answer

  1. geometry versus geography
  2. metres or degrees
  3. index-aware predicates
  4. longitude comes first

basics

~20 s

Install PostGIS, store zones and points as geography in SRID 4326, index the columns with GiST, and filter with index-aware predicates such as ST_Covers and ST_DWithin. A comparison like ST_Distance(...) < 3000 cannot use the index.

solid answer

~40 s

PostGIS comes as its own OS package and is installed with `CREATE EXTENSION postgis`, with no preload. For a city-scale delivery feature, store zones as `geography(MultiPolygon, 4326)` and addresses or courier positions as `geography(Point, 4326)`, so distances are in metres. Put a GiST index on each spatial column. Query with predicates PostGIS can turn into an index search: `ST_Covers(zone.area, address.location)` for 'which zone serves this address' (it counts boundary points, where `ST_Contains` would not), and `ST_DWithin(courier.position, address.location, 3000)` for 'couriers within 3 km'. These run a bounding-box test against the index first and the exact calculation only on the candidates. `ST_Distance(a, b) < 3000` computes every row. Two classic bugs: `ST_MakePoint` takes longitude then latitude, and on `geometry` in SRID 4326 a distance of 3000 means degrees.

code

sql · 20 lines
sql
CREATE EXTENSION IF NOT EXISTS postgis;

CREATE TABLE delivery_zone (
  zone_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name    text NOT NULL,
  area    geography(MultiPolygon, 4326) NOT NULL
);
CREATE INDEX delivery_zone_area_gist ON delivery_zone USING gist (area);

-- which zone serves an address at lat 52.3702, lon 4.8952?
SELECT zone_id, name
FROM delivery_zone
WHERE ST_Covers(area,
        ST_SetSRID(ST_MakePoint(4.8952, 52.3702), 4326)::geography);

-- couriers within 3 km of that address (metres, index-aware)
SELECT courier_id
FROM courier
WHERE ST_DWithin(position,
        ST_SetSRID(ST_MakePoint(4.8952, 52.3702), 4326)::geography, 3000);

go deeper

for a junior

Know that PostGIS is installed with CREATE EXTENSION postgis from a separate package and adds geometry and geography types.

for a middle

Explain geometry versus geography and their units, GiST indexes on spatial columns, and why ST_DWithin and ST_Covers use the index while ST_Distance comparisons do not.

for a senior

Show production judgement: typmod-constrained columns, axis order and SRID hygiene, boundary semantics with a tie-break, and PostGIS binaries in place before a major upgrade.

for a principal

Decide where spatial work belongs: in PostgreSQL with PostGIS next to the transactional data, or in a separate service, given team skills and query volume.

## Installing PostGIS PostGIS is not a contrib module. It ships as its own OS package, built for your PostgreSQL major version, and you then run `CREATE EXTENSION postgis;` in each database that needs it. It adds the spatial types `geometry` and `geography`, a large family of `ST_*` functions, and GiST operator classes for both types. It needs no `shared_preload_libraries` entry. This answer covers **using** the extension in PostgreSQL. How spatial indexes work in general (R-trees, geohash cells, quadtrees) belongs to the system-design topics. ## geometry or geography | | `geometry` | `geography` | |---|---|---| | Model | a flat plane in the coordinate system named by its SRID | longitude/latitude on the WGS 84 spheroid | | Distance units | the SRID's units: **degrees** for SRID 4326 | **metres** | | Functions | the full set (`ST_Contains`, `ST_Union`, `ST_Buffer`, …) | a subset (`ST_DWithin`, `ST_Distance`, `ST_Covers`, `ST_Intersects`, …) | | Cost | cheaper planar maths | slower spherical maths | For a delivery-zone feature that spans one or a few cities, `geography` is the simpler choice. Distances come out in metres with no projection to manage. The few operations it lacks can be done by casting to `geometry` or into a local projected SRID. ## A schema for delivery zones - `delivery_zone.area geography(MultiPolygon, 4326)`: polygons the operations team draws on a web map. - `customer_address.location geography(Point, 4326)`: one geocoded point per address. - `courier.position geography(Point, 4326)`: updated as couriers move. - A **GiST index** on each of those columns: `CREATE INDEX ... USING gist (area)`. The typmod (`Point`, `4326`) makes PostgreSQL reject a polygon in a point column, or a point in another SRID, at insert time instead of producing a wrong answer later. ## Queries that use the index PostGIS's relationship and distance predicates are **index-aware**. Each one includes a bounding-box test that the planner can match to the GiST index, and the exact (expensive) calculation then runs only on the rows that pass. The ones you need here: 1. **Which zone serves this address?** `WHERE ST_Covers(z.area, a.location)`. `ST_Covers` counts points on the boundary. `ST_Contains` (a `geometry` function) treats a point exactly on the edge as not contained, which can leave an address served by no zone. 2. **Which couriers are within 3 km?** `WHERE ST_DWithin(c.position, a.location, 3000)`, with the distance in metres because both sides are `geography`. 3. **Does a new zone overlap an existing one?** `WHERE ST_Intersects(z.area, new_area)`. The tempting `WHERE ST_Distance(c.position, a.location) < 3000` gives the same rows, but the planner sees only a function result compared with a constant. It cannot use the index, so it computes the spheroidal distance for every courier. Ordering by nearest distance with the `<->` operator also uses GiST; that KNN mechanism belongs to the index-types topic. ## Pitfalls interviewers listen for - **Axis order**: `ST_MakePoint(x, y)` means `(longitude, latitude)`. Swapped coordinates put a point in the wrong place without any error, because both values are valid numbers. - **Units on geometry**: `ST_DWithin(geom_a, geom_b, 3000)` on `geometry` in SRID 4326 means 3000 *degrees*, which matches everything. Use `geography`, or a projected SRID in metres. - **Missing SRID**: `ST_MakePoint` returns a `geometry` with no SRID. Wrap it in `ST_SetSRID(..., 4326)` before casting or comparing, because operations on mixed SRIDs fail. - **Casting the column in the query**: `WHERE ST_DWithin(location::geography, ...)` on a `geometry` column cannot use a plain GiST index on that column. Store the type you query, or index the same expression. - **Upgrades**: PostGIS packages are tied to the PostgreSQL major, so a major upgrade needs the new major's PostGIS binaries installed first, followed by the extension's own update steps. ## Checking it works Run the query under `EXPLAIN` and look for an index scan or bitmap scan on the GiST index of `area` or `position`. How to read that plan in detail belongs to the EXPLAIN topic. ## Where this design stops - **Ranking the nearest couriers** rather than filtering by radius uses `ORDER BY position <-> point LIMIT n` on the GiST index. That KNN mechanism is covered by the index-types topic; nearest-N without a radius as a design question belongs to the system-design topics. - **Heavy polygon work**, such as merging zones or buffering them by 500 m, is easier in `geometry` with a projected SRID. Cast or transform for those jobs and keep `geography` for the hot lookups. - **Frequently moving couriers** turn `courier.position` into an update-heavy column. Each update writes a new row version and new index entries, which is a vacuum and bloat concern rather than a PostGIS one. - **Zone ownership rules** (which zone wins on a shared border, or whether zones may overlap) are business decisions. Enforce them in the application or with a constraint, not by hoping the geometry never touches.

  • With PostGIS in PostgreSQL, when would you store the delivery zones as geometry in a projected SRID instead of geography?
    When you need operations `geography` lacks or does slowly, such as unions, buffers, simplification or heavy polygon overlays, and the data covers a limited region. A local projected SRID in metres keeps distances meaningful while using the cheaper planar maths and the full function set. Store and index the column in that SRID, and transform incoming WGS 84 points with `ST_Transform` before comparing.
  • In PostGIS, why can an address lying exactly on the border between two delivery zones match no zone with ST_Contains?
    `ST_Contains(A, B)` requires that no point of B lies outside A *and* that at least one point of B lies in A's interior. A point on A's boundary has no interior point, so it is not contained by either neighbouring zone. `ST_Covers(A, B)` only requires that no point of B lies outside A, so a boundary point is covered by both zones. Pick one with an explicit tie-break, such as the lowest `zone_id`.

  • ST_Distance(a, b) < 3000 uses the GiST index just like ST_DWithin.
  • ST_MakePoint takes latitude first, then longitude.
  • On a geometry column in SRID 4326, ST_DWithin's distance argument is in metres.
  • PostGIS must be listed in shared_preload_libraries before CREATE EXTENSION postgis.
  • A B-tree index on the geography column speeds up radius and containment queries.