Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Certified PostGIS User ยท Lesson 4 of 6

Spatial Relationships and Measurements

๐Ÿ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
4
Module 3: Certified PostGIS User โ€“ Spatial Relationships and Measurements

๐Ÿ“˜ Module 3: Certified PostGIS User โ€” Spatial Relationships and Measurements

๐Ÿ”Ž Module Introduction

Welcome back, young map explorer! In Module 1, you learned what spatial data is. You learned about points, lines, and polygons. You learned about coordinates and PostGIS. In Module 2, you learned how to install PostGIS and create spatial databases. You learned how to create spatial tables and add data.

In this module, we are going to learn about spatial relationships and measurements. Spatial relationships tell us how places are connected. For example: "Is this house inside that area?" or "Do these two roads cross each other?" Measurements tell us about size and distance. For example: "How far is the school from the market?" or "How big is this farm?"

Do not worry if some words sound big. We will explain everything in simple language. We will use stories, examples from Nigeria, examples from school, and examples from home. We will use pictures made from keyboard characters (ASCII art) to help you see what we mean. By the end of this module, you will know:

  • How to measure distance between places.
  • How to measure the area of a polygon.
  • How to measure the length of a line.
  • How to check if one shape contains another.
  • How to check if two shapes intersect.
  • How to check if one shape is within another.
  • How to use bounding boxes for faster queries.
  • How to use spatial operators.

This module is long because it is a complete chapter, not just short notes. Take your time. Read one lesson at a time. Do the exercises. Ask questions. Practice on your computer. Are you ready? Let us begin!

๐ŸŽฏ Learning Objectives

After finishing this module, you should be able to:

  1. Explain what a spatial relationship is in your own simple words.
  2. Use ST_Distance to measure the distance between two places.
  3. Use ST_Area to measure the area of a polygon.
  4. Use ST_Length to measure the length of a line.
  5. Use ST_Contains to check if one shape contains another.
  6. Use ST_Intersects to check if two shapes cross each other.
  7. Use ST_Within to check if one shape is inside another.
  8. Explain what a bounding box is.
  9. Use bounding boxes to make queries faster.
  10. Use spatial operators like && and <->.
  11. Run advanced spatial queries.
  12. Understand common errors and how to fix them.

๐Ÿ“– Warm-up Story: Emeka and the Missing Goat

Emeka was a 13-year-old boy who lived in Port Harcourt, Nigeria. His family had a small farm. One day, their favourite goat went missing. The goat was called Bingo.

Emeka's father was worried. "Bingo could be anywhere," he said. "We will never find him."

Emeka remembered his PostGIS lessons. "We can use spatial queries," he said. "We can find all the places within 2 kilometres of our farm. Bingo cannot have gone far."

Emeka opened his spatial database. He had a table of all the farms and houses in the area. He used ST_DWithin to find all places within 2 kilometres of his farm.

Then he used ST_Contains to check which of those places had a fenced area. Bingo might be trapped inside a fence. He found three farms with fences nearby.

Emeka and his father visited each farm. At the third farm, they found Bingo! The goat had wandered into the farm and could not get out.

Moral of the story: Spatial relationships and measurements help us solve real problems. They help us find things, measure distances, and check relationships between places.

๐Ÿ“š Lesson 1: What Is a Spatial Relationship?

Definition

A spatial relationship tells us how two or more places are connected. For example: "Is this house inside that area?" or "Do these two roads cross each other?"

Why It Is Important

Spatial relationships help us answer important questions. They help us find things, plan routes, and make decisions.

Simple Explanation

Imagine you have two toys on a table. One toy is inside a box. The other toy is outside the box. The relationship between the toy and the box is a spatial relationship.

Real-Life Example

A delivery company checks if a customer's address is inside the delivery zone.

School Example

A school checks if a student's house is within walking distance of the school.

Home Example

At home, you check if your house is inside a flood zone.

Nigerian Example

In Lagos, a taxi company checks if a customer is within a certain area for pickup.

Illustration (ASCII)

   SPATIAL RELATIONSHIP:
   +-------------------+
   |     AREA          |
   |   +----+          |
   |   | โ€ข  |  <-- point inside area
   |   +----+          |
   |                   |
   |         โ€ข  <-- point outside area
   +-------------------+
  

Mini Summary

A spatial relationship tells us how two or more places are connected. It helps us answer questions about locations.

Summary of Lesson 1

You learned what a spatial relationship is. You saw examples from home, school, and Nigeria. Now you know that spatial relationships describe connections between places.

๐Ÿ“š Lesson 2: Measuring Distance with ST_Distance

Definition

ST_Distance is a PostGIS function that measures the distance between two places. It returns a number. The number is the distance in the units of the coordinate system.

Why It Is Important

Distance is important for planning routes, estimating travel time, and finding nearby places. ST_Distance helps you measure distance accurately.

Simple Explanation

Imagine you want to know how far your house is from the market. ST_Distance measures the straight-line distance between them.

Real-Life Example

A delivery company measures the distance from the warehouse to the customer.

School Example

A school measures the distance from the school to the nearest bus stop.

Home Example

At home, you measure the distance from your house to the nearest hospital.

Nigerian Example

In Abuja, a taxi driver measures the distance from the airport to the city centre.

SQL Command for ST_Distance

   SELECT ST_Distance(
       ST_GeomFromText('POINT(6.5774 3.3212)', 4326),
       ST_GeomFromText('POINT(6.5780 3.3220)', 4326)
   ) AS distance;
  

Illustration (ASCII)

   ST_DISTANCE:
   [ POINT A ] ------------------- [ POINT B ]
         |                              |
         V                              V
   [ DISTANCE = 100 METRES ]
  

Mini Summary

ST_Distance measures the distance between two places. It returns a number.

Summary of Lesson 2

You learned how to measure distance with ST_Distance. You saw examples from home, school, and Nigeria. Now you can measure distances in your spatial database.

๐Ÿ“š Lesson 3: Measuring Area with ST_Area

Definition

ST_Area is a PostGIS function that measures the area of a polygon. It returns a number. The number is the area in the units of the coordinate system.

Why It Is Important

Area is important for measuring land, planning farms, and estimating costs. ST_Area helps you measure area accurately.

Simple Explanation

Imagine you want to know the size of your school compound. ST_Area measures the area of the polygon that outlines the compound.

Real-Life Example

A farmer measures the area of his farm to know how much seed to buy.

School Example

A school measures the area of the playground to plan for new equipment.

Home Example

At home, you measure the area of your garden to know how many plants to buy.

Nigerian Example

In Kano, a farmer measures the area of his farmland to plan his crops.

SQL Command for ST_Area

   SELECT ST_Area(
       ST_GeomFromText('POLYGON((0 0, 4 0, 4 4, 0 4, 0 0))', 4326)
   ) AS area;
  

Illustration (ASCII)

   ST_AREA:
   +-------------------+
   |                   |
   |    POLYGON        |
   |                   |
   +-------------------+
         |
         V
   [ AREA = 16 SQUARE METRES ]
  

Mini Summary

ST_Area measures the area of a polygon. It returns a number.

Summary of Lesson 3

You learned how to measure area with ST_Area. You saw examples from home, school, and Nigeria. Now you can measure areas in your spatial database.

๐Ÿ“š Lesson 4: Measuring Length with ST_Length

Definition

ST_Length is a PostGIS function that measures the length of a line. It returns a number. The number is the length in the units of the coordinate system.

Why It Is Important

Length is important for measuring roads, rivers, and paths. ST_Length helps you measure length accurately.

Simple Explanation

Imagine you want to know how long the road from your house to the market is. ST_Length measures the length of the line that represents the road.

Real-Life Example

A road company measures the length of a road to estimate the cost of repairs.

School Example

A school measures the length of the running track for sports day.

Home Example

At home, you measure the length of your garden fence.

Nigerian Example

In Lagos, the government measures the length of the Third Mainland Bridge.

SQL Command for ST_Length

   SELECT ST_Length(
       ST_GeomFromText('LINESTRING(0 0, 3 4)', 4326)
   ) AS length;
  

Illustration (ASCII)

   ST_LENGTH:
   [ POINT A ] ------------------- [ POINT B ]
         |                              |
         V                              V
   [ LENGTH = 5 METRES ]
  

Mini Summary

ST_Length measures the length of a line. It returns a number.

Summary of Lesson 4

You learned how to measure length with ST_Length. You saw examples from home, school, and Nigeria. Now you can measure lengths in your spatial database.

๐Ÿ“š Lesson 5: Checking Containment with ST_Contains

Definition

ST_Contains is a PostGIS function that checks if one shape contains another. It returns TRUE or FALSE. If the first shape contains the second, it returns TRUE.

Why It Is Important

Containment helps us answer questions like: "Is this house inside that flood zone?" or "Is this point inside that country?"

Simple Explanation

Imagine you have a box and a ball. The box contains the ball. ST_Contains tells you if the box contains the ball.

Real-Life Example

A bank checks if a customer's address is inside a branch service area.

School Example

A school checks if a student's house is inside the school bus route.

Home Example

At home, you check if your house is inside a flood zone.

Nigerian Example

In Nigeria, the government checks if a village is inside a protected forest area.

SQL Command for ST_Contains

   SELECT ST_Contains(
       ST_GeomFromText('POLYGON((0 0, 10 0, 10 10, 0 10, 0 0))', 4326),
       ST_GeomFromText('POINT(5 5)', 4326)
   ) AS contains;

   -- Returns TRUE
  

Illustration (ASCII)

   ST_CONTAINS:
   +-------------------+
   |     POLYGON       |
   |                   |
   |        โ€ข  <-- point inside
   |                   |
   +-------------------+
         |
         V
   [ ST_CONTAINS = TRUE ]
  

Mini Summary

ST_Contains checks if one shape contains another. It returns TRUE or FALSE.

Summary of Lesson 5

You learned how to check containment with ST_Contains. You saw examples from home, school, and Nigeria. Now you can check if shapes contain other shapes.

๐Ÿ“š Lesson 6: Checking Intersection with ST_Intersects

Definition

ST_Intersects is a PostGIS function that checks if two shapes cross each other. It returns TRUE or FALSE. If the shapes share any space, it returns TRUE.

Why It Is Important

Intersection helps us answer questions like: "Do these two roads cross?" or "Does this river pass through that farm?"

Simple Explanation

Imagine you draw two lines on a paper. They cross each other. ST_Intersects tells you if the lines cross.

Real-Life Example

A road company checks if a new road will cross an existing pipeline.

School Example

A school checks if the new building will overlap with the playground.

Home Example

At home, you check if your fence crosses your neighbour's fence.

Nigerian Example

In Nigeria, the government checks if a new road will cross a river.

SQL Command for ST_Intersects

   SELECT ST_Intersects(
       ST_GeomFromText('LINESTRING(0 0, 10 10)', 4326),
       ST_GeomFromText('LINESTRING(0 10, 10 0)', 4326)
   ) AS intersects;

   -- Returns TRUE
  

Illustration (ASCII)

   ST_INTERSECTS:
   [ LINE A ] --------\
                       \
                        \
   [ LINE B ] -----------\--------
                          \
                           \
   [ ST_INTERSECTS = TRUE ]
  

Mini Summary

ST_Intersects checks if two shapes cross each other. It returns TRUE or FALSE.

Summary of Lesson 6

You learned how to check intersection with ST_Intersects. You saw examples from home, school, and Nigeria. Now you can check if shapes intersect.

๐Ÿ“š Lesson 7: Checking Within with ST_Within

Definition

ST_Within is a PostGIS function that checks if one shape is inside another. It returns TRUE or FALSE. It is the opposite of ST_Contains.

Why It Is Important

Within helps us answer questions like: "Is this point inside that polygon?" or "Is this house inside that neighbourhood?"

Simple Explanation

Imagine you have a ball inside a box. The ball is within the box. ST_Within tells you if the ball is within the box.

Real-Life Example

A delivery company checks if a customer's address is within the delivery zone.

School Example

A school checks if a student's house is within the school district.

Home Example

At home, you check if your house is within a quiet zone.

Nigerian Example

In Nigeria, the government checks if a village is within a flood-prone area.

SQL Command for ST_Within

   SELECT ST_Within(
       ST_GeomFromText('POINT(5 5)', 4326),
       ST_GeomFromText('POLYGON((0 0, 10 0, 10 10, 0 10, 0 0))', 4326)
   ) AS within;

   -- Returns TRUE
  

Illustration (ASCII)

   ST_WITHIN:
   +-------------------+
   |     POLYGON       |
   |                   |
   |        โ€ข  <-- point within
   |                   |
   +-------------------+
         |
         V
   [ ST_WITHIN = TRUE ]
  

Mini Summary

ST_Within checks if one shape is inside another. It returns TRUE or FALSE.

Summary of Lesson 7

You learned how to check within with ST_Within. You saw examples from home, school, and Nigeria. Now you can check if shapes are within other shapes.

๐Ÿ“š Lesson 8: What Is a Bounding Box?

Definition

A bounding box is the smallest rectangle that can contain a shape. It has four sides: top, bottom, left, and right.

Why It Is Important

Bounding boxes make spatial queries faster. The database can quickly check if two shapes might intersect by checking their bounding boxes first.

Simple Explanation

Imagine you draw a rectangle around a shape. The rectangle is the bounding box. It is like a box that holds the shape.

Real-Life Example

A delivery company uses bounding boxes to quickly find drivers near a customer.

School Example

A school uses bounding boxes to quickly find students near the school.

Home Example

At home, you use bounding boxes to quickly find nearby shops.

Nigerian Example

In Lagos, a taxi company uses bounding boxes to quickly find nearby drivers.

Illustration (ASCII)

   BOUNDING BOX:
   +-------------------+
   |  +-----+          |
   |  |     |          |
   |  |  โ€ข  |  <-- shape inside bounding box
   |  |     |          |
   |  +-----+          |
   +-------------------+
  

Mini Summary

A bounding box is the smallest rectangle that can contain a shape. It makes spatial queries faster.

Summary of Lesson 8

You learned what a bounding box is. You saw examples from home, school, and Nigeria. Now you know that bounding boxes speed up queries.

๐Ÿ“š Lesson 9: Using Spatial Operators (&& and <->)

Definition

Spatial operators are special symbols that work with spatial data. The && operator checks if two bounding boxes overlap. The <-> operator calculates the distance between two shapes.

Why It Is Important

Spatial operators make queries faster and easier. They are shortcuts for common spatial operations.

Simple Explanation

Imagine you have two boxes. The && operator tells you if the boxes touch. The <-> operator tells you how far apart the boxes are.

Real-Life Example

A bank uses && to quickly find branches in the same area.

School Example

A school uses && to quickly find students in the same neighbourhood.

Home Example

At home, you use <-> to find the nearest shop.

Nigerian Example

In Lagos, a taxi company uses <-> to find the nearest driver.

SQL Commands for Spatial Operators

   -- Find all buildings in the same area as a point
   SELECT name FROM buildings
   WHERE geom && ST_GeomFromText('POINT(6.5774 3.3212)', 4326);

   -- Find the nearest building to a point
   SELECT name FROM buildings
   ORDER BY geom <-> ST_GeomFromText('POINT(6.5774 3.3212)', 4326)
   LIMIT 1;
  

Illustration (ASCII)

   SPATIAL OPERATORS:
   [ && ] --> [ CHECK IF BOUNDING BOXES OVERLAP ]
   [ <-> ] --> [ CALCULATE DISTANCE ]
         |
         V
   [ FAST SPATIAL QUERIES ]
  

Mini Summary

Spatial operators like && and <-> make queries faster. && checks if bounding boxes overlap. <-> calculates distance.

Summary of Lesson 9

You learned about spatial operators. You saw examples from home, school, and Nigeria. Now you can use && and <-> in your queries.

๐Ÿ“š Lesson 10: Using ST_DWithin for Distance Queries

Definition

ST_DWithin is a PostGIS function that checks if two shapes are within a certain distance. It returns TRUE or FALSE.

Why It Is Important

ST_DWithin is faster than ST_Distance. It is used to find all places within a certain distance of a point.

Simple Explanation

Imagine you want to find all shops within 1 kilometre of your house. ST_DWithin finds them quickly.

Real-Life Example

A delivery company finds all customers within 5 kilometres of a driver.

School Example

A school finds all students within 2 kilometres of the school.

Home Example

At home, you find all hospitals within 3 kilometres of your house.

Nigerian Example

In Abuja, a taxi company finds all customers within 1 kilometre of a driver.

SQL Command for ST_DWithin

   SELECT name FROM buildings
   WHERE ST_DWithin(
       geom,
       ST_GeomFromText('POINT(6.5774 3.3212)', 4326),
       1000
   );
  

Illustration (ASCII)

   ST_DWITHIN:
   [ POINT ] ----- 1 KM ----- [ BUILDING ]
         |
         V
   [ ST_DWITHIN = TRUE ]
  

Mini Summary

ST_DWithin checks if two shapes are within a certain distance. It is faster than ST_Distance.

Summary of Lesson 10

You learned how to use ST_DWithin. You saw examples from home, school, and Nigeria. Now you can find places within a certain distance.

๐Ÿ“š Lesson 11: Using ST_Intersection and ST_Union

Definition

ST_Intersection returns the shape where two shapes overlap. ST_Union returns the combined shape of two shapes.

Why It Is Important

These functions help you combine and compare shapes. They are useful for planning and analysis.

Simple Explanation

Imagine you have two circles that overlap. ST_Intersection gives you the overlapping part. ST_Union gives you the total area of both circles.

Real-Life Example

A city planner uses ST_Union to combine two districts into one.

School Example

A school uses ST_Intersection to find where two playgrounds overlap.

Home Example

At home, you use ST_Union to combine two garden plots.

Nigerian Example

In Nigeria, the government uses ST_Union to combine two local government areas.

SQL Commands for ST_Intersection and ST_Union

   -- Find the intersection of two polygons
   SELECT ST_AsText(ST_Intersection(
       ST_GeomFromText('POLYGON((0 0, 4 0, 4 4, 0 4, 0 0))', 4326),
       ST_GeomFromText('POLYGON((2 2, 6 2, 6 6, 2 6, 2 2))', 4326)
   ));

   -- Find the union of two polygons
   SELECT ST_AsText(ST_Union(
       ST_GeomFromText('POLYGON((0 0, 4 0, 4 4, 0 4, 0 0))', 4326),
       ST_GeomFromText('POLYGON((2 2, 6 2, 6 6, 2 6, 2 2))', 4326)
   ));
  

Illustration (ASCII)

   ST_INTERSECTION:
   +-------+-------+
   |       |       |
   |   +---+---+   |
   |   |   |   |   |
   |   +---+---+   |
   |       |       |
   +-------+-------+
         |
         V
   [ OVERLAPPING AREA ]

   ST_UNION:
   +-------+-------+
   |       |       |
   |       +       |
   |       |       |
   |       +       |
   |       |       |
   +-------+-------+
         |
         V
   [ COMBINED AREA ]
  

Mini Summary

ST_Intersection returns the overlapping part of two shapes. ST_Union returns the combined shape of two shapes.

Summary of Lesson 11

You learned about ST_Intersection and ST_Union. You saw examples from home, school, and Nigeria. Now you can combine and compare shapes.

๐Ÿ“š Lesson 12: Using ST_Buffer

Definition

ST_Buffer creates a new shape that is a certain distance around an existing shape. It is like drawing a circle around a point.

Why It Is Important

Buffers help you find all places within a certain distance of a shape. They are useful for planning and analysis.

Simple Explanation

Imagine you drop a stone in water. Ripples spread out in a circle. ST_Buffer creates a circle around a point.

Real-Life Example

A bank uses ST_Buffer to find all customers within 5 kilometres of a branch.

School Example

A school uses ST_Buffer to find all students within 1 kilometre of the school.

Home Example

At home, you use ST_Buffer to find all shops within 500 metres of your house.

Nigerian Example

In Lagos, a taxi company uses ST_Buffer to find all customers within 2 kilometres of a driver.

SQL Command for ST_Buffer

   SELECT ST_AsText(ST_Buffer(
       ST_GeomFromText('POINT(6.5774 3.3212)', 4326),
       0.01
   )) AS buffer;
  

Illustration (ASCII)

   ST_BUFFER:
         +-------+
       /           \
      |      โ€ข      |  <-- buffer around point
       \           /
         +-------+
  

Mini Summary

ST_Buffer creates a new shape around an existing shape. It helps you find places within a certain distance.

Summary of Lesson 12

You learned about ST_Buffer. You saw examples from home, school, and Nigeria. Now you can create buffers around shapes.

๐Ÿ“š Lesson 13: Common Errors and How to Fix Them

Definition

An error is a mistake. PostGIS tells you when you make a mistake. You can fix the mistake and try again.

Why It Is Important

Everyone makes mistakes. Learning to fix errors makes you a better expert.

Simple Explanation

Imagine you are writing a letter. You spell a word wrong. You erase it and write it correctly. Fixing errors in PostGIS is like that.

Real-Life Example

A bank worker uses the wrong SRID. PostGIS shows an error. The worker corrects the SRID and tries again.

School Example

A student uses the wrong function name. PostGIS shows an error. The student corrects the name and tries again.

Home Example

At home, you use the wrong coordinate. PostGIS shows an error. You correct the coordinate and tries again.

Nigerian Example

In a Nigerian market, a trader uses the wrong polygon. PostGIS shows an error. The trader corrects the polygon and tries again.

Common Errors and Solutions

Error What It Means How to Fix It
function does not exist PostGIS is not installed Run CREATE EXTENSION postgis;
geometry has wrong SRID The SRIDs do not match Use ST_Transform to change the SRID
invalid geometry The shape is not valid Use ST_MakeValid to fix the shape
syntax error You typed a command incorrectly Check your spelling and punctuation
relation does not exist The table does not exist Create the table first

Illustration (ASCII)

   ERROR:
   [ TYPE: SELECT ST_Distance('POINT(0 0)', 'POINT(1 1)'); ]
         |
         V
   [ ERROR: function st_distance(unknown, unknown) is not unique ]
         |
         V
   [ FIX: USE ST_GeomFromText ]
         |
         V
   [ TRY AGAIN ]
  

Mini Summary

Errors are mistakes. PostGIS tells you when you make a mistake. You can fix the mistake and try again.

Summary of Lesson 13

You learned about common errors and how to fix them. You saw a table of errors. Now you can fix mistakes in PostGIS.

๐Ÿ“š Lesson 14: Running Advanced Spatial Queries

Definition

An advanced spatial query is a query that uses multiple spatial functions together. It answers complex questions about locations.

Why It Is Important

Advanced queries help you solve real problems. They help you find answers that simple queries cannot.

Simple Explanation

Imagine you want to find all schools within 2 kilometres of a hospital that are also inside a certain neighbourhood. An advanced query answers that question.

Real-Life Example

A bank finds all customers within 5 kilometres of a branch who have accounts with more than 1 million naira.

School Example

A school finds all students who live within 1 kilometre of the school and have scores above 80.

Home Example

At home, you find all shops within 500 metres of your house that sell bread.

Nigerian Example

In Lagos, a taxi company finds all drivers within 1 kilometre of a customer who have a rating above 4.5.

SQL Command for Advanced Query

   SELECT name FROM buildings
   WHERE ST_DWithin(
       geom,
       ST_GeomFromText('POINT(6.5774 3.3212)', 4326),
       2000
   )
   AND type = 'School'
   AND ST_Contains(
       ST_GeomFromText('POLYGON((6.5 3.3, 6.6 3.3, 6.6 3.4, 6.5 3.4, 6.5 3.3))', 4326),
       geom
   );
  

Illustration (ASCII)

   ADVANCED SPATIAL QUERY:
   [ FIND PLACES WITHIN 2 KM ]
         |
         V
   [ FILTER BY TYPE = 'SCHOOL' ]
         |
         V
   [ FILTER BY CONTAINMENT IN AREA ]
         |
         V
   [ RESULTS: SCHOOL A, SCHOOL B ]
  

Mini Summary

Advanced spatial queries use multiple spatial functions together. They answer complex questions about locations.

Summary of Lesson 14

You learned how to run advanced spatial queries. You saw examples from home, school, and Nigeria. Now you can solve complex problems with spatial data.

๐Ÿ“š Lesson 15: Best Practices for Spatial Queries

Definition

Best practices are the best ways to do things. They help you write clean, fast, and accurate spatial queries.

Why It Is Important

Following best practices makes your queries faster. It prevents problems later.

Simple Explanation

Imagine you are cleaning your room. You put things in the right place. Best practices for spatial queries are like putting things in the right place.

Real-Life Example

A bank follows best practices. Its spatial queries are fast and accurate.

School Example

A school follows best practices. Its spatial queries are fast and accurate.

Home Example

At home, you follow best practices. Your spatial queries are fast and accurate.

Nigerian Example

In a Nigerian market, a trader follows best practices. Spatial queries are fast and accurate.

Best Practices List

  1. Always use an SRID for your geometry columns.
  2. Use spatial indexes for faster queries.
  3. Use ST_DWithin instead of ST_Distance for distance queries.
  4. Use bounding boxes to filter data quickly.
  5. Validate your geometries with ST_IsValid.
  6. Use ST_Transform to match SRIDs when needed.
  7. Test your queries before using them in production.
  8. Keep your data clean and accurate.
  9. Document your queries.
  10. Teach others about spatial queries.

Illustration (ASCII)

   BEST PRACTICES:
   [ USE SRID ] --> [ USE SPATIAL INDEXES ]
         |                        |
         V                        V
   [ USE ST_DWITHIN ] --> [ USE BOUNDING BOXES ]
         |                        |
         V                        V
   [ VALIDATE GEOMETRIES ] --> [ USE ST_TRANSFORM ]
         |                        |
         V                        V
   [ TEST QUERIES ] --> [ KEEP DATA CLEAN ]
         |                        |
         V                        V
   [ DOCUMENT QUERIES ] --> [ TEACH OTHERS ]
         |                        |
         V                        V
   [ FAST, ACCURATE SPATIAL QUERIES ]
  

Mini Summary

Best practices help you write clean, fast, and accurate spatial queries.

Summary of Lesson 15

You learned best practices for spatial queries. You saw a list. Now you can write better spatial queries.

๐Ÿ“– Key Vocabulary

Word Simple Definition
Spatial relationship How two or more places are connected.
ST_Distance A function that measures the distance between two places.
ST_Area A function that measures the area of a polygon.
ST_Length A function that measures the length of a line.
ST_Contains A function that checks if one shape contains another.
ST_Intersects A function that checks if two shapes cross each other.
ST_Within A function that checks if one shape is inside another.
Bounding box The smallest rectangle that can contain a shape.
Spatial operator A special symbol that works with spatial data.
ST_DWithin A function that checks if two shapes are within a certain distance.
ST_Intersection A function that returns the overlapping part of two shapes.
ST_Union A function that returns the combined shape of two shapes.
ST_Buffer A function that creates a new shape around an existing shape.

๐Ÿง  Important Concepts

  • A spatial relationship tells us how places are connected.
  • ST_Distance measures the distance between two places.
  • ST_Area measures the area of a polygon.
  • ST_Length measures the length of a line.
  • ST_Contains checks if one shape contains another.
  • ST_Intersects checks if two shapes cross each other.
  • ST_Within checks if one shape is inside another.
  • A bounding box is the smallest rectangle that can contain a shape.
  • Spatial operators like && and <-> make queries faster.
  • ST_DWithin checks if two shapes are within a certain distance.
  • ST_Intersection returns the overlapping part of two shapes.
  • ST_Union returns the combined shape of two shapes.
  • ST_Buffer creates a new shape around an existing shape.
  • Best practices help you write clean, fast, and accurate spatial queries.

๐Ÿ“ Step-by-Step Explanations

How to Measure Distance (Step by Step)

  1. Identify the two points you want to measure.
  2. Use ST_GeomFromText to create the points.
  3. Use ST_Distance to measure the distance.
  4. Run the query.
  5. PostGIS returns the distance.

How to Find Places Within a Distance (Step by Step)

  1. Identify the center point.
  2. Choose the distance.
  3. Use ST_DWithin with the geometry column, the center point, and the distance.
  4. Run the query.
  5. PostGIS returns all places within the distance.

How to Check Containment (Step by Step)

  1. Identify the polygon and the point.
  2. Use ST_Contains with the polygon and the point.
  3. Run the query.
  4. PostGIS returns TRUE or FALSE.

๐ŸŒ Real-Life Examples

  • A bank measures the distance from a customer to the nearest branch.
  • A school measures the area of the playground.
  • A hospital measures the length of the ambulance route.
  • A market checks if a stall is inside the market area.
  • A library checks if a new building will intersect with the existing library.
  • A government checks if a village is within a flood zone.
  • A delivery company finds all customers within 5 kilometres of a driver.
  • A family finds the nearest hospital using ST_DWithin.

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • In Lagos, a taxi company finds all drivers within 1 kilometre of a customer.
  • In Abuja, the government measures the area of a new park.
  • In Enugu, a school checks if a student's house is within the school district.
  • In Kano, a farmer measures the area of his farmland.
  • In Port Harcourt, a hospital finds all patients within 3 kilometres.
  • In Ibadan, a family finds the nearest market using ST_DWithin.
  • In Jos, a library checks if a new building will intersect with the existing library.
  • In Nigeria, many companies use PostGIS for spatial analysis.

๐Ÿ˜„ Fun Examples Children Can Relate To

  • Imagine ST_Distance is like measuring the distance between two dots on a paper.
  • Think of ST_Area as measuring the size of a football field.
  • Pretend ST_Length is like measuring the length of a skipping rope.
  • Imagine ST_Contains is like checking if a toy is inside a box.
  • Think of ST_Intersects as checking if two roads cross each other.
  • Imagine ST_Within is like checking if a ball is inside a basket.
  • Think of a bounding box as a frame around a picture.
  • Imagine ST_Buffer is like drawing a circle around a point.

๐Ÿ  Everyday Examples

  • You measure the distance from your house to the market. That is ST_Distance.
  • You measure the area of your garden. That is ST_Area.
  • You measure the length of your fence. That is ST_Length.
  • You check if your keys are inside your bag. That is ST_Contains.
  • You check if two roads cross. That is ST_Intersects.
  • You check if your phone is inside your pocket. That is ST_Within.
  • You find all shops within 500 metres of your house. That is ST_DWithin.
  • You draw a circle around a point on a map. That is ST_Buffer.

๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ Parent Tips

  • Help your children practice measuring distances with ST_Distance.
  • Show your children how to measure areas with ST_Area.
  • Explain the importance of spatial relationships.
  • Encourage your children to check containment with ST_Contains.
  • Practice finding places within a distance with ST_DWithin.
  • Help your children understand bounding boxes.
  • Celebrate when your child runs a successful spatial query.
  • Support your child if they want to learn more about spatial analysis.

๐Ÿค“ Interesting Facts

  • ST_Distance is one of the oldest spatial functions in PostGIS.
  • ST_Area can measure the area of any polygon, no matter how complex.
  • ST_Length can measure the length of roads, rivers, and even coastlines.
  • ST_Contains is used by many delivery companies around the world.
  • ST_Intersects is used by traffic planners to find dangerous crossings.
  • ST_Within is used by governments to check if villages are in flood zones.
  • Bounding boxes can make queries thousands of times faster.
  • ST_DWithin is faster than ST_Distance for distance queries.
  • ST_Buffer is used by many companies to find customers within a certain distance.
  • PostGIS has more than 300 spatial functions.

โ“ Did You Know?

  • Did you know that ST_Distance measures the distance between two places?
  • Did you know that ST_Area measures the area of a polygon?
  • Did you know that ST_Length measures the length of a line?
  • Did you know that ST_Contains checks if one shape contains another?
  • Did you know that ST_Intersects checks if two shapes cross each other?
  • Did you know that ST_Within checks if one shape is inside another?
  • Did you know that bounding boxes make queries faster?
  • Did you know that ST_DWithin finds places within a certain distance?
  • Did you know that ST_Intersection finds the overlapping part of two shapes?
  • Did you know that ST_Union combines two shapes into one?
  • Did you know that ST_Buffer creates a new shape around an existing shape?

๐Ÿ” Remember This

  • A spatial relationship tells us how places are connected.
  • ST_Distance measures the distance between two places.
  • ST_Area measures the area of a polygon.
  • ST_Length measures the length of a line.
  • ST_Contains checks if one shape contains another.
  • ST_Intersects checks if two shapes cross each other.
  • ST_Within checks if one shape is inside another.
  • A bounding box is the smallest rectangle that can contain a shape.
  • Spatial operators like && and <-> make queries faster.
  • ST_DWithin checks if two shapes are within a certain distance.
  • ST_Intersection returns the overlapping part of two shapes.
  • ST_Union returns the combined shape of two shapes.
  • ST_Buffer creates a new shape around an existing shape.
  • Best practices help you write clean, fast, and accurate spatial queries.

โš ๏ธ Common Mistakes

  1. Forgetting to use ST_GeomFromText when creating geometries.
  2. Using the wrong SRID for your data.
  3. Using ST_Distance instead of ST_DWithin for distance queries.
  4. Not using a spatial index for faster queries.
  5. Forgetting to validate geometries with ST_IsValid.
  6. Using the wrong function name (e.g., ST_Contains instead of ST_Within).
  7. Not checking the units of distance and area.
  8. Panicking when you see an error. Errors can be fixed.
  9. Not testing queries before using them in production.
  10. Not following best practices.

โœ… Best Practices

  • Always use an SRID for your geometry columns.
  • Use spatial indexes for faster queries.
  • Use ST_DWithin instead of ST_Distance for distance queries.
  • Use bounding boxes to filter data quickly.
  • Validate your geometries with ST_IsValid.
  • Use ST_Transform to match SRIDs when needed.
  • Test your queries before using them in production.
  • Keep your data clean and accurate.
  • Document your queries.
  • Teach others about spatial queries.
  • Practice measuring distances, areas, and lengths regularly.
  • Learn from errors. They help you improve.

๐Ÿ–ผ๏ธ More ASCII Illustrations, Diagrams, Flowcharts, and Tables

Flowchart: Spatial Relationships

   SPATIAL RELATIONSHIPS
     |
     +---- ST_CONTAINS (shape contains another)
     |
     +---- ST_INTERSECTS (shapes cross)
     |
     +---- ST_WITHIN (shape inside another)
     |
     +---- ST_DWITHIN (shapes within distance)
  

Timeline: Learning Spatial Relationships

   Step 1: Learn what a spatial relationship is.
   Step 2: Learn ST_Distance.
   Step 3: Learn ST_Area.
   Step 4: Learn ST_Length.
   Step 5: Learn ST_Contains.
   Step 6: Learn ST_Intersects.
   Step 7: Learn ST_Within.
   Step 8: Learn about bounding boxes.
   Step 9: Learn spatial operators.
   Step 10: Learn ST_DWithin.
   Step 11: Learn ST_Intersection and ST_Union.
   Step 12: Learn ST_Buffer.
   Step 13: Fix errors.
   Step 14: Run advanced queries.
   Step 15: Learn best practices.
  

Diagram: Spatial Relationship Functions

   [ ST_DISTANCE ] --> [ MEASURE DISTANCE ]
   [ ST_AREA ] --> [ MEASURE AREA ]
   [ ST_LENGTH ] --> [ MEASURE LENGTH ]
   [ ST_CONTAINS ] --> [ CHECK CONTAINMENT ]
   [ ST_INTERSECTS ] --> [ CHECK INTERSECTION ]
   [ ST_WITHIN ] --> [ CHECK WITHIN ]
   [ ST_DWITHIN ] --> [ CHECK DISTANCE ]
  

Table: Spatial Functions and Their Uses

Function What It Does Example Use
ST_Distance Measures distance between two places How far is the school from the market?
ST_Area Measures area of a polygon How big is the farm?
ST_Length Measures length of a line How long is the road?
ST_Contains Checks if one shape contains another Is the house inside the flood zone?
ST_Intersects Checks if two shapes cross Do the roads cross?
ST_Within Checks if one shape is inside another Is the point inside the polygon?
ST_DWithin Checks if shapes are within a distance Find all shops within 1 km.
ST_Intersection Returns overlapping part of two shapes Where do the two areas overlap?
ST_Union Combines two shapes into one Combine two districts.
ST_Buffer Creates a new shape around an existing shape Draw a circle around a point.

Comparison Table: ST_Distance vs ST_DWithin

Feature ST_Distance ST_DWithin
Purpose Measures the exact distance Checks if distance is within a limit
Return value A number TRUE or FALSE
Speed Slower Faster (uses index)
Use case How far is it? Is it within 1 km?

๐Ÿ“Œ End-of-Module Summary

In this module, you learned about spatial relationships and measurements. You learned what a spatial relationship is. You learned how to measure distance with ST_Distance. You learned how to measure area with ST_Area. You learned how to measure length with ST_Length.

You learned how to check containment with ST_Contains. You learned how to check intersection with ST_Intersects. You learned how to check within with ST_Within. You learned about bounding boxes. They make queries faster.

You learned about spatial operators like && and <->. You learned how to use ST_DWithin for distance queries. You learned about ST_Intersection and ST_Union. You learned how to use ST_Buffer.

You learned about common errors and how to fix them. You learned how to run advanced spatial queries. You learned best practices for spatial queries.

Now you are ready to move on to Module 4, where you will learn about spatial indexes and performance. But before you go, make sure you understand the key takeaways below.

โ“ Frequently Asked Questions

  1. What is a spatial relationship?
    A spatial relationship tells us how two or more places are connected.
  2. How do I measure distance?
    Use ST_Distance to measure the distance between two places.
  3. How do I measure area?
    Use ST_Area to measure the area of a polygon.
  4. How do I measure length?
    Use ST_Length to measure the length of a line.
  5. How do I check if one shape contains another?
    Use ST_Contains.
  6. How do I check if two shapes cross?
    Use ST_Intersects.
  7. How do I check if one shape is inside another?
    Use ST_Within.
  8. What is a bounding box?
    A bounding box is the smallest rectangle that can contain a shape.
  9. How do I find places within a certain distance?
    Use ST_DWithin.
  10. How do I combine two shapes?
    Use ST_Union.
  11. How do I create a buffer around a shape?
    Use ST_Buffer.

โœ๏ธ Matching Exercises

Match the function in Column A with what it does in Column B.

Column A Column B
1. ST_Distance A. Checks if one shape contains another
2. ST_Area B. Measures the distance between two places
3. ST_Length C. Checks if two shapes cross each other
4. ST_Contains D. Measures the area of a polygon
5. ST_Intersects E. Measures the length of a line
6. ST_Within F. Checks if two shapes are within a distance
7. ST_DWithin G. Checks if one shape is inside another
8. ST_Buffer H. Creates a new shape around an existing shape

Answers: 1-B, 2-D, 3-E, 4-A, 5-C, 6-G, 7-F, 8-H

๐ŸŽญ Scenario-Based Exercises

  1. Scenario: You want to know how far your school is from the market. What function do you use?
    Answer: You use ST_Distance.
  2. Scenario: You want to know the size of your farm. What function do you use?
    Answer: You use ST_Area.
  3. Scenario: You want to know the length of a road. What function do you use?
    Answer: You use ST_Length.
  4. Scenario: You want to check if your house is inside a flood zone. What function do you use?
    Answer: You use ST_Contains or ST_Within.
  5. Scenario: You want to check if two roads cross. What function do you use?
    Answer: You use ST_Intersects.
  6. Scenario: You want to find all shops within 1 kilometre of your house. What function do you use?
    Answer: You use ST_DWithin.
  7. Scenario: You want to combine two districts into one. What function do you use?
    Answer: You use ST_Union.
  8. Scenario: You want to draw a circle around a point. What function do you use?
    Answer: You use ST_Buffer.

๐Ÿ‘ฅ Group Activity

Title: Find the Nearest School
Instructions: In groups of 3 or 4, create a spatial database with at least 5 schools. Add their locations as points. Write a query to find the nearest school to a given point. Write a query to find all schools within 2 kilometres of a given point. Present your results to the class.

Example:
Table: schools (id, name, geom)
Data: School A, School B, School C, etc.
Query: SELECT name FROM schools ORDER BY geom <-> ST_GeomFromText('POINT(6.5774 3.3212)', 4326) LIMIT 1;

๐Ÿง‘ Individual Activity

Title: Measure Your Neighbourhood
Instructions: Create a spatial database for your neighbourhood. Add at least 5 places as points. Add at least 2 roads as lines. Add at least 1 area as a polygon. Measure the distance between two places. Measure the area of the polygon. Write down what you did.

Example:
Database: myneighbourhood
Tables: places (points), roads (lines), parks (polygons).
Query: SELECT ST_Distance(ST_GeomFromText('POINT(6.5774 3.3212)', 4326), ST_GeomFromText('POINT(6.5780 3.3220)', 4326));

๐Ÿ› ๏ธ Mini Project

Title: Build a Spatial Analysis Database
Materials: Computer with PostgreSQL and PostGIS installed.
Steps:

  1. Create a spatial database called "myanalysis".
  2. Create a table for places with a geometry column.
  3. Add at least 5 points for places.
  4. Create a table for roads with a geometry column.
  5. Add at least 2 lines for roads.
  6. Create a table for areas with a geometry column.
  7. Add at least 1 polygon for an area.
  8. Measure the distance between two places.
  9. Measure the area of the polygon.
  10. Find all places within 1 kilometre of a point.
  11. Show your results to your class or family.

๐Ÿ“‹ Practical Assignment

Assignment: For one week, practice spatial relationships and measurements. Keep a diary. Each day, write down:

  • What spatial function you used.
  • What you measured or checked.
  • What you learned.
  • What you will do differently next time.

At the end of the week, write a short report. Share it with your teacher or parent.

๐Ÿ”‘ Key Takeaways

  • A spatial relationship tells us how places are connected.
  • ST_Distance measures the distance between two places.
  • ST_Area measures the area of a polygon.
  • ST_Length measures the length of a line.
  • ST_Contains checks if one shape contains another.
  • ST_Intersects checks if two shapes cross each other.
  • ST_Within checks if one shape is inside another.
  • A bounding box is the smallest rectangle that can contain a shape.
  • Spatial operators like && and <-> make queries faster.
  • ST_DWithin checks if two shapes are within a certain distance.
  • ST_Intersection returns the overlapping part of two shapes.
  • ST_Union returns the combined shape of two shapes.
  • ST_Buffer creates a new shape around an existing shape.
  • Best practices help you write clean, fast, and accurate spatial queries.

๐Ÿ’ฌ Classroom Discussion Questions

  1. What is a spatial relationship? Give an example.
  2. How do you measure distance with ST_Distance?
  3. How do you measure area with ST_Area?
  4. How do you measure length with ST_Length?
  5. How do you check containment with ST_Contains?
  6. How do you check intersection with ST_Intersects?
  7. How do you check within with ST_Within?
  8. What is a bounding box? How does it make queries faster?
  9. What are spatial operators? Give examples.
  10. How do you find places within a distance with ST_DWithin?
  11. What is ST_Intersection? What is ST_Union?
  12. What is ST_Buffer? When would you use it?
  13. How do you run an advanced spatial query?
  14. What are the best practices for spatial queries?

โžก๏ธ Preparation for Module 4

In Module 4, you will learn about spatial indexes and performance. You will learn about:

  • Creating GiST and SP-GiST indexes for spatial columns.
  • Using EXPLAIN ANALYZE to tune spatial queries.
  • Understanding bounding boxes and index selectivity.
  • Clustering spatial data for better performance.
  • Optimizing spatial queries for speed.
  • Monitoring spatial database performance.

Before you start Module 4, make sure you understand everything in this module. Practice measuring distances, areas, and lengths. Practice checking containment and intersection. Practice using ST_DWithin and ST_Buffer. When you are ready, turn the page and continue your journey to becoming a Certified PostGIS User!

End of Module 3.

๐Ÿ† Get Certified

๐Ÿ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (โ‚ฆ2,000 or 20,000 coins), and get a verified certificate with your name on it.

๐ŸŽ“ Sign Up to Get Certified
๐Ÿ› ๏ธ Practice Tools
Hands-on simulators & labs - subscription required.
โ†’
๐ŸŽฏ Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
โ†’