Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 118/ 160
06. Database Design, Normalization & Semi-Structured SQL

Geospatial SQL Basics (PostGIS Geometry, Geography & Distance Queries)

Query locations and distances with PostGIS geometry and geography types.

AdvancedPostGIS · Geometry / Geography3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Store places as points on a map, then ask the database which points are near you or inside an area.

Think of it like…

A paper map with a grid: the grid (the index) lets you look only at the squares near a point instead of checking every shop in the country, and a piece of string cut to 3 km tells you which of those shops are close enough.

Where you’ve seen it

A food-delivery app lists open restaurants within 3 km of the customer, nearest first: SELECT id, name, ST_Distance(location, ST_MakePoint(73.8567, 18.5204)::geography) AS metres FROM restaurants WHERE is_open AND ST_DWithin(location, ST_MakePoint(73.8567, 18.5204)::geography, 3000) ORDER BY location <-> ST_MakePoint(73.8567, 18.5204)::geography LIMIT 20; A GiST index on location keeps it at a few milliseconds across 200,000 restaurants.

Words you’ll hear

geography
Points and shapes on the earth's surface; distances in metres.
geometry + SRID
Shapes on a plane in a coordinate system; SRID 4326 is longitude/latitude (WGS 84).
ST_DWithin
True if two shapes are within a distance; index-assisted.
<-> (KNN)
Distance operator for ORDER BY … LIMIT nearest-neighbour searches.

Visual diagram

Loading interactive diagram

Theory & example queries

Types, coordinates and indexes

Enable PostGIS with CREATE EXTENSION postgis; and add a column such as location geography(Point, 4326). Points are built with ST_MakePoint(longitude, latitude); the longitude-first order trips up almost everyone, and swapped coordinates put Pune in the Indian Ocean. geography computes distances on the spheroid in metres, which is what most apps want. geometry is faster for heavy analysis, but distances are in the SRID's units (degrees for 4326), so project to a metric SRID for planar measurements.

Create a spatial index with CREATE INDEX ON restaurants USING gist (location). Index-aware functions (ST_DWithin, ST_Intersects, ST_Contains, the <-> operator in ORDER BY) use a bounding-box search on the index first, then check exact shapes only for candidates.

Table and indexQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE EXTENSION IF NOT EXISTS postgis;23CREATE TABLE restaurants (4  id bigint PRIMARY KEY,5  name text,6  is_open boolean,7  location geography (Point, 4326) NOT NULL8);910CREATE INDEX restaurants_location_gist ON restaurants USING gist (location);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/10
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative command status
CREATE EXTENSION CREATE TABLE CREATE INDEX

Note: PostgreSQL command tags are representative. Names already existing or insufficient privileges can produce notices or errors instead.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: geography in metres, longitude first, GiST index on the column.

Radius, nearest and point-in-polygon

For "within 3 km", use ST_DWithin(location, point, 3000), never ST_Distance(location, point) < 3000: the latter computes the distance to every row and can't use the index. For "nearest N", use ORDER BY location <-> point LIMIT N, which walks the index in distance order; combine it with ST_DWithin when you also need a maximum radius.

Delivery zones and city boundaries are polygons: SELECT z.name FROM zones z WHERE ST_Contains(z.boundary, ST_SetSRID(ST_MakePoint(73.8567, 18.5204), 4326)); finds the zone serving a customer (with geometry columns and a GiST index on boundary). MySQL also supports spatial types and SRID-aware functions such as ST_Distance_Sphere, but PostGIS has far more functions and tooling.

Orders per delivery zoneQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  z.name,3  COUNT(o.id) AS orders4FROM5  zones z6  LEFT JOIN orders o ON ST_Contains (z.boundary, o.drop_point)7  AND o.created_at >= '2026-11-01'8GROUP BY9  z.name10ORDER BY11  orders DESC;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/11
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative zone totals3 sample rows
Representative zone totals
nameorders
Central184
East121
Airport0

Note: Assumes sample zone polygons and order drop points for November 2026; COUNT(o.id) keeps the zone with no matching orders.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: ST_DWithin for radius, <-> for nearest, ST_Contains for zones.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Schema

Store points correctly

Use geography(Point, 4326) for lon/lat data and build points with longitude first.

Focus at this step

ST_MakePoint(73.8567, 18.5204)::geography

What to watch at this step
SRID
4326
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

PostGIS adds spatial types and functions to PostgreSQL. A geography column stores longitude/latitude points on the earth and measures distances in metres; a geometry column works on a flat plane in the units of its coordinate system (SRID). The everyday queries are "within X metres" (ST_DWithin), "nearest N" (ORDER BY location <-> point LIMIT N) and "which zone contains this point" (ST_Contains), all made fast by a GiST index.

Why it matters: Delivery radius checks, store finders, ride matching, geofencing and regional reporting are all spatial queries. Doing them with latitude and longitude columns and hand-written formulas is slow and error-prone. PostGIS is the standard tool, and spatial questions appear in interviews for logistics, mobility and marketplace companies.

When to reach for it

  • Store and restaurant finders
  • Delivery-radius and geofence checks
  • Counting events per region or zone

When to avoid or be careful

  • WHERE ST_Distance(…) < x instead of ST_DWithin
  • Swapping latitude and longitude
  • Measuring distances in degrees with SRID 4326 geometry

Ways to answer "what's near me?"

PostGIS geography + GiST
Best for: Accurate distances in metres on real coordinates

Strengths: Correct on the globe; index-assisted radius and KNN queries.

Watch out: Slightly slower than geometry for heavy analysis.

PostGIS geometry in a projected SRID
Best for: City-scale analysis and complex polygon work

Strengths: Fast planar maths; huge function library.

Watch out: Must choose and transform to a suitable projection.

lat/lng columns with a formula
Best for: Tiny datasets or engines without spatial support

Strengths: No extension needed.

Watch out: No spatial index; formula errors; slow at scale.

Interview signals & numbers to know

When this topic comes up

  • “Find drivers within 2 km”
  • “Nearest 10 stores to a user”
  • “Which delivery zone is this address in?”
  • PostGIS
  • Location-based features

Benchmarks & rules of thumb

4326 -
SRID for longitude/latitude (WGS 84)
metres -
geography distance units
lon, lat -
ST_MakePoint argument order

Common mistakes & follow-ups

Common interview mistakes

  • Calling ST_MakePoint(lat, lon) and getting restaurants that are thousands of kilometres away.
  • Filtering with ST_Distance(location, point) < 3000, which computes the distance to every row.
  • Using geometry with SRID 4326 and passing 3000 as a distance, which means 3,000 degrees.

Likely interviewer follow-ups

  • How would you find the 10 nearest stores to a user efficiently?
  • What's the difference between geometry and geography in PostGIS?
  • Why is ST_DWithin preferred to ST_Distance in a WHERE clause?
Interview tip: Mention longitude-first, geography for metres, ST_DWithin and a GiST index. Those four details prevent the bugs interviewers know people hit.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Geospatial SQL Basics (PostGIS Geometry, Geography & Distance Queries) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Full-Text Search in SQL (tsvector, tsquery, GIN Search Indexes)
Next topic
Temporal Tables & System-Versioned History Tracking