
# 

PostGIS: Geo queries

* * *

[PostGIS](https://postgis.net/) is a Postgres extension that allows you to interact with Geo data within Postgres. You can sort your data by geographic location, get data within certain geographic boundaries, and do much more with it.

## Overview[#](#overview)

While you may be able to store simple lat/long geographic coordinates as a set of decimals, it does not scale very well when you try to query through a large data set. PostGIS comes with special data types that are efficient, and indexable for high scalability.

The additional data types that PostGIS provides include [Point](https://postgis.net/docs/using_postgis_dbmanagement.html#Point), [Polygon](https://postgis.net/docs/using_postgis_dbmanagement.html#Polygon), [LineString](https://postgis.net/docs/using_postgis_dbmanagement.html#LineString), and many more to represent different types of geographical data. In this guide, we will mainly focus on how to interact with `Point` type, which represents a single set of latitude and longitude. If you are interested in digging deeper, you can learn more about different data types on the [data management section of PostGIS docs](https://postgis.net/docs/using_postgis_dbmanagement.html).

## Enable the extension[#](#enable-the-extension)

You can get started with PostGIS by enabling the PostGIS extension in your Supabase dashboard.

1.  Go to the [Database](/dashboard/project/_/database/tables) page in the Dashboard.
2.  Click on **Extensions** in the sidebar.
3.  Search for `postgis` and enable the extension.
4.  In the confirmation prompt select "Create a new schema" and name it `gis` for example.

## Examples[#](#examples)

Now that we are ready to get started with PostGIS, let’s create a table and see how we can utilize PostGIS for some typical use cases. Let’s imagine we are creating a simple restaurant-searching app.

Let’s create our table. Each row represents a restaurant with its location stored in `location` column as a `Point` type.

```
1create table if not exists public.restaurants (2	id int generated by default as identity primary key,3	name text not null,4	location extensions.geography(POINT) not null5);
```

We can then set a [spatial index](https://postgis.net/docs/using_postgis_dbmanagement.html#build-indexes) on the `location` column of this table.

```
1create index restaurants_geo_index2  on public.restaurants3  using GIST (location);
```

### Inserting data[#](#inserting-data)

You can insert geographical data through SQL or through our API.

#### Restaurants

id

name

location

1

Supa Burger

lat: 40.807416, long: -73.946823

2

Supa Pizza

lat: 40.807475, long: -73.94581

3

Supa Taco

lat: 40.80629, long: -73.945826

Notice the order in which you pass the latitude and longitude. Longitude comes first, and is because longitude represents the x-axis of the location. Another thing to watch for is when inserting data from the client library, there is no comma between the two values, just a single space.

At this point, if you go into your Supabase dashboard and look at the data, you will notice that the value of the `location` column looks something like this.

```
10101000020E6100000A4DFBE0E9C91614044FAEDEBC0494240
```

We can query the `restaurants` table directly, but it will return the `location` column in the format you see above. We will create [database functions](../../functions/index.md) so that we can use the [st\_y()](https://postgis.net/docs/ST_Y.html) and [st\_x()](https://postgis.net/docs/ST_X.html) function to convert it back to lat and long floating values.

### Order by distance[#](#order-by-distance)

Sorting datasets from closest to farthest, sometimes called nearest-neighbor sort, is a very common use case in Geo-queries. PostGIS can handle it with the use of the [`<->`](https://postgis.net/docs/geometry_distance_knn.html) operator. `<->` operator returns the two-dimensional distance between two geometries and will utilize the spatial index when used within `order by` clause. You can create the following database function to sort the restaurants from closest to farthest by passing the current locations as parameters.

```
1create or replace function nearby_restaurants(lat float, long float)2returns table (id public.restaurants.id%TYPE, name public.restaurants.name%TYPE, lat float, long float, dist_meters float)3set search_path = ''4language sql5as $$6  select id, name, extensions.st_y(location::extensions.geometry) as lat, extensions.st_x(location::extensions.geometry) as long, extensions.st_distance(location, extensions.st_point(long, lat)::extensions.geography) as dist_meters7  from public.restaurants8  order by location operator(extensions.<->) extensions.st_point(long, lat)::extensions.geography;9$$;
```

Now you can call this function from your client using `rpc()` like this:

```
1const { data, error } = await supabase.rpc('nearby_restaurants', {2  lat: 40.807313,3  long: -73.946713,4})
```

### Finding all data points within a bounding box[#](#finding-all-data-points-within-a-bounding-box)

![Searching within a bounding box of a map](/docs/img/guides/database/extensions/postgis/map.png)

When you are working on a map-based application where the user scrolls through your map, you might want to load the data that lies within the bounding box of the map every time your users scroll. PostGIS can return the rows that are within the bounding box just by supplying the bottom left and the top right coordinates. Let’s look at what the function would look like:

```
1create or replace function restaurants_in_view(min_lat float, min_long float, max_lat float, max_long float)2returns table (id public.restaurants.id%TYPE, name public.restaurants.name%TYPE, lat float, long float)3set search_path to ''4language sql5as $$6	select id, name, extensions.st_y(location::extensions.geometry) as lat, extensions.st_x(location::extensions.geometry) as long7	from public.restaurants8	where location operator(extensions.&&) extensions.ST_SetSRID(extensions.ST_MakeBox2D(extensions.ST_Point(min_long, min_lat), extensions.ST_Point(max_long, max_lat)), 4326)9$$;
```

The [`&&`](https://postgis.net/docs/geometry_overlaps.html) operator used in the `where` statement here returns a boolean of whether the bounding box of the two geometries intersect or not. We are basically creating a bounding box from the two points and finding those points that fall under the bounding box. We are also utilizing a few different PostGIS functions:

*   [ST\_MakeBox2D](https://postgis.net/docs/ST_MakeBox2D.html): Creates a 2-dimensional box from two points.
*   [ST\_SetSRID](https://postgis.net/docs/ST_SetSRID.html): Sets the [SRID](https://postgis.net/docs/manual-dev/using_postgis_dbmanagement.html#spatial_ref_sys), which is an identifier of what coordinate system to use for the geometry. 4326 is the standard longitude and latitude coordinate system.

You can call this function from your client using `rpc()` like this:

```
1const { data, error } = await supabase.rpc('restaurants_in_view', {2  min_lat: 40.807,3  min_long: -73.946,4  max_lat: 40.808,5  max_long: -73.945,6})
```

## Troubleshooting[#](#troubleshooting)

As of PostGIS 2.3 or newer, the PostGIS extension is no longer relocatable from one schema to another. If you need to move it from one schema to another for any reason (e.g. from the public schema to the extensions schema for security reasons), you would normally run a ALTER EXTENSION to relocate the schema. However, you will now to do the following steps:

1.  Backup your Database to prevent data loss - You can do this through the [CLI](/docs/reference/cli/supabase-db-dump) or Postgres backup tools such as [pg\_dumpall](https://www.postgresql.org/docs/current/backup-dump.html#BACKUP-DUMP-ALL)
    
2.  Drop all dependencies you created and the PostGIS extension - `DROP EXTENSION postgis CASCADE;`
    
3.  Enable PostGIS extension in the new schema - `CREATE EXTENSION postgis SCHEMA extensions;`
    
4.  Restore dropped data via the Backup if necessary from step 1 with your tool of choice.
    

Alternatively, you can contact the [Supabase Support Team](/dashboard/support/new) and ask them to run the following SQL on your instance:

```
1BEGIN;2	UPDATE pg_extension3	  SET extrelocatable = true4	WHERE extname = 'postgis';56	ALTER EXTENSION postgis7	  SET SCHEMA extensions;89	ALTER EXTENSION postgis10	  UPDATE TO "<POSTGIS_VERSION>next";1112	ALTER EXTENSION postgis UPDATE;1314	UPDATE pg_extension15	  SET extrelocatable = false16	WHERE extname = 'postgis';17COMMIT;
```

## Resources[#](#resources)

*   [Official PostGIS documentation](https://postgis.net/documentation/)
