PostGIS spatial functions

Updated at:

PostGIS extends Hologres with spatial data types, functions, and operators. Use it to store, query, and analyze geographic data — from bounding box filters and proximity searches to polygon intersection checks and distance calculations.

Hologres supports PostGIS 3.0.0.

Engine support

In Hologres V1.3 and later, most PostGIS functions run on the Hologres Query Engine (HQE) developed by Alibaba Cloud, which delivers better query performance than PQE. In versions earlier than V1.3, functions run on the PostgreSQL Query Engine (PQE), where performance may be lower. For the engine that each function uses, see Spatial functions: each function table either states the engine for the whole group or lists it in the Required engine column.

Install and uninstall the PostGIS extension

Run the following statement as a superuser to install PostGIS in a database. Installation is per-database — repeat this step for each database that needs spatial support.

-- Install PostGIS explicitly into the public schema.
CREATE EXTENSION IF NOT EXISTS postgis SCHEMA public;
PostGIS cannot be installed in the pg_catalog schema.

To verify the installation, run:

SELECT public.postgis_full_version();

A successful install returns a version string such as POSTGIS="3.0.0 ...".

Note

postgis_full_version() is a PL/pgSQL function in the public schema. The default search_path in Hologres includes public, so you can call the function without a schema prefix. If the search_path of the current session does not include public, the call fails with function postgis_full_version() does not exist. The examples in this topic use the public. prefix so that they work under any search_path.

Uninstall PostGIS

To remove the extension:

DROP EXTENSION postgis;

If the database still contains objects that depend on the geometry or geography type — for example, a table created as described in Create and query a geometry table — the statement fails with cannot drop extension postgis because other objects depend on it. Drop the dependent objects first:

  1. Find the objects and columns that still use a spatial type:

    SELECT n.nspname AS schema_name, c.relname AS object_name, a.attname AS column_name, t.typname
    FROM pg_attribute a
      JOIN pg_class c ON c.oid = a.attrelid
      JOIN pg_type t ON t.oid = a.atttypid
      JOIN pg_namespace n ON n.oid = c.relnamespace
    WHERE t.typname IN ('geometry', 'geography')
      AND c.relkind IN ('r', 'p', 'm', 'f')
      AND a.attnum > 0
      AND NOT a.attisdropped
      AND n.nspname NOT LIKE 'pg_%';
  2. Drop each table returned by the query, or drop only its spatial columns:

    DROP TABLE <TABLE_NAME>;
    Note

    If the table recycle bin is enabled — which is the default in Hologres V3.1 and later — DROP TABLE moves the table to the recycle bin, so you must also complete the next step. To bypass the recycle bin and skip the next step, run DROP TABLE <TABLE_NAME> FORCE; instead. For more information, see Table recycle bin.

  3. Empty the recycle bin. Tables in the recycle bin still depend on the spatial types, so the types remain in use until the recycle bin is emptied:

    CALL hologres.hg_purge_all_tables();
    Important

    hg_purge_all_tables() permanently deletes every table in the recycle bin of the current database. This action cannot be undone. Before you run it, confirm that the recycle bin holds no table that you still need. This command must be run by a superuser of the current instance.

  4. Uninstall the extension:

    DROP EXTENSION postgis;
Important

Drop the dependent objects as described above rather than using DROP EXTENSION postgis CASCADE, even though the PostgreSQL error message suggests CASCADE. The CASCADE option drops the extension data (PostGIS, RoaringBitmap, Proxima, Binlog, and BSI data) together with every object that depends on the extension, including metadata, tables, views, and server data. This action cannot be undone.

Resolve the spatial_ref_sys conflict

If CREATE EXTENSION postgis fails with the error relation spatial_ref_sys already exists, the database contains a leftover spatial_ref_sys system table from a previous installation. A normal DROP EXTENSION postgis leaves nothing behind, so this error typically appears after a migration from another database or when a table of the same name was created manually. Resolve the conflict as follows:

  1. Remove the partially installed extension:

    DROP EXTENSION IF EXISTS postgis;
  2. Remove the leftover system table. Before you run this statement, confirm that the table is a leftover from a previous installation rather than a business table:

    DROP TABLE IF EXISTS spatial_ref_sys CASCADE;
  3. Reinstall the PostGIS extension:

    CREATE EXTENSION IF NOT EXISTS postgis SCHEMA public;
  4. Verify the installation:

    SELECT public.postgis_full_version();

Create and query a geometry table

PostGIS supports two spatial data types in Hologres: geometry (planar/Cartesian coordinates) and geography (spherical longitude/latitude coordinates). For details on the geography type, see the PostGIS geography documentation.

The geometry type is more commonly used. The following steps show how to create a geometry table and run spatial queries.

1. Create a geometry table

When creating a table, you can specify a geometry subtype. Supported subtypes: Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon.

Without a subtype:

CREATE TABLE holo_gis_1 (
  id   INT,
  geom geometry,
  PRIMARY KEY (id)
);

With a subtype and spatial reference system identifier (SRID):

CREATE TABLE holo_gis_2 (
  id   INT,
  geom geometry(point, 4326),
  PRIMARY KEY (id)
);

In this example, the subtype is Point and the SRID is 4326 (WGS 84). If no SRID is specified, the default is 0. The SRID of the geometries that you insert or use in query predicates must match the SRID of the column. Otherwise, the statement fails with an error such as Geometry SRID (0) does not match column SRID (4326) or Operation on mixed SRID geometries. For more information about SRIDs, see the PostGIS documentation.

2. Insert spatial data

-- Without SRID
INSERT INTO holo_gis_1 VALUES (1, ST_GeomFromText('point(116 39)'));

-- With SRID 4326
INSERT INTO holo_gis_2 VALUES (1, ST_GeomFromText('point(116 39)', 4326));

For more information about spatial functions, see Spatial functions.

3. Query spatial data

After inserting data, you can run the following types of queries.

Rectangular range query

Returns all points within a bounding box.

Without SRID:

SELECT st_astext(geom)
FROM holo_gis_1
WHERE ST_Covers(
  ST_MakeBox2D(ST_Point(116, 39), ST_Point(117, 40)),
  geom
);

With SRID:

SELECT st_astext(geom)
FROM holo_gis_2
WHERE ST_Covers(
  ST_SetSRID(ST_MakeBox2D(ST_Point(116, 39), ST_Point(117, 40)), 4326),
  geom
);

Both queries return:

st_astext
-------------
POINT(116 39)
Note

For large datasets, use the bounding box operator && as a coarse filter before you run an exact spatial predicate. This reduces the number of rows that reach the exact calculation. The && operator runs on HQE, so it costs less than topological functions such as ST_Intersects and ST_Covers, which are pushed down to PQE. For example:

SELECT st_astext(geom)
FROM holo_gis_1
WHERE geom && ST_MakeBox2D(ST_Point(116, 39), ST_Point(117, 40))
  AND ST_Intersects(ST_GeomFromText('POLYGON((116 39,117 39,117 40,116 40,116 39))'), geom);

If you need only a rectangular range filter and not exact topological semantics, use geom && ST_MakeBox2D(...) on its own. If the column has an SRID, wrap the box in ST_SetSRID with the same SRID. Otherwise, the statement fails with Operation on mixed SRID geometries.

Polygon intersection check

To find points that fall inside an arbitrary polygon or lie on its boundary, use ST_Intersects with the polygon. Unlike the bounding box built by ST_MakeBox2D, the polygon can have any shape, and ST_Intersects counts boundary contact as a match.

Without SRID:

SELECT st_astext(geom)
FROM holo_gis_1
WHERE ST_Intersects(
  ST_GeomFromText('POLYGON((116 39,117 39,117 40,116 40,116 39))'),
  geom
);

With SRID:

SELECT st_astext(geom)
FROM holo_gis_2
WHERE ST_Intersects(
  ST_SetSRID(ST_GeomFromText('POLYGON((116 39,117 39,117 40,116 40,116 39))'), 4326),
  geom
);

Both queries return:

st_astext
-------------
POINT(116 39)

Spatial functions

PostGIS provides spatial functions to convert and analyze geometry values. The function syntax uses the following parameters:

  • geom: a geometry value or an expression that evaluates to geometry

  • precision: an INTEGER that controls coordinate output precision. The parameter name, semantics, and default value differ by function:

    • ST_AsText(geom [, precision]): the number of significant digits. Defaults to 15.

    • ST_AsGeoJSON(geom [, maxdecimaldigits]): the maximum number of decimal places. Defaults to 9. Specify this parameter explicitly if you need to retain more precision; otherwise, the exported coordinates lose precision.

    We recommend that you specify a value from 1 to 20. Values outside this range are accepted but produce no meaningful additional digits, because a double-precision float carries about 15 to 17 significant digits.

  • index: INTEGER; a 1-based index unless otherwise noted

  • srid: INTEGER; a spatial reference system identifier

Each function runs on one of the following query engines:

Engine When it applies Performance
HQE (Hologres Query Engine) Hologres V1.3 and later Higher — optimized for analytical workloads
PQE (PostgreSQL Query Engine) All versions; required for certain functions Lower — compatibility mode

For the complete PostGIS function specification, see the PostGIS reference documentation.

Note
  • Engine assignments in the following tables reflect behavior measured on Hologres V4.2 and name only the current engine (HQE or PQE). The engine that a function uses can change across versions. To confirm the engine for your instance, check whether the EXPLAIN output contains a PQE node. For overall engine support by version, see Engine support.

  • The following tables list the commonly used signature of each function. Some functions accept additional overloads — for example, ST_MakeLine also takes an array of geometries, and ST_AddPoint also takes an insert position. See the PostGIS reference documentation for the full list of overloads, as well as for functions that appear in the examples but are not listed in these tables, such as ST_MakeBox2D.

Geometry constructors

All functions in this group run on HQE.

Function Syntax Returns Description
ST_LineFromMultiPoint ST_LineFromMultiPoint(geom) GEOMETRY Creates a linestring from a multipoint geometry, preserving point order. The returned geometry has the same SRID as the input.
ST_MakeEnvelope ST_MakeEnvelope(xmin, ymin, xmax, ymax [, srid]) GEOMETRY (POLYGON) Creates the rectangular polygon defined by the given corner coordinates, where the coordinates specify the lower-left and upper-right corners. The result is always a POLYGON, even when the coordinates collapse to a line or a single point. If an SRID is provided, the returned geometry uses that SRID; otherwise the SRID is 0.
ST_MakeLine ST_MakeLine(geom1, geom2) GEOMETRY (LINESTRING) Creates a linestring from two input geometries.
ST_MakePoint ST_MakePoint(x, y) GEOMETRY (POINT) Creates a point from coordinate values.
ST_Point ST_Point(x, y) GEOMETRY (POINT) Creates a point from coordinate values.
ST_Polygon ST_Polygon(linestring, srid) GEOMETRY (POLYGON) Creates a polygon whose exterior ring is the input linestring, with the given SRID.

Geometry accessors

All functions in this group run on HQE, except ST_IsPolygonCCW, which runs on PQE. They are not complements: when the exterior ring and the interior rings have the same orientation, both return false. Do not negate ST_IsPolygonCW to test for counterclockwise orientation. When you filter a large table by ring orientation, also note that these two functions run on different engines.

Function Syntax Returns Description
GeometryType GeometryType(geom) TEXT Returns the subtype name of the input geometry as a string, without a prefix and in uppercase, such as POINT or POLYGON.
ST_Boundary ST_Boundary(geom) GEOMETRY Returns the boundary of the input geometry. An empty geometry returns the input as-is; a point or non-empty multipoint returns an empty geometry collection; a linestring returns a multipoint of its boundary points; a polygon without interior rings returns a closed linestring; a polygon with interior rings or a multipolygon returns a multilinestring of all boundary rings.
ST_Dimension ST_Dimension(geom) INTEGER Returns the intrinsic dimension of the geometry subtype.
ST_Envelope ST_Envelope(geom) GEOMETRY Returns the minimum bounding box of the input geometry. Returns a point if the box degenerates to a point, a two-point linestring if it is one-dimensional, or a clockwise-oriented polygon otherwise. The returned geometry has the same SRID as the input.
ST_ExteriorRing ST_ExteriorRing(geom) GEOMETRY (LINESTRING) Returns the exterior ring of a polygon as a closed linestring.
ST_GeometryN ST_GeometryN(geom, index) GEOMETRY Returns the geometry at the given 1-based index. For simple geometries (point, linestring, polygon) with index 1, returns the geometry itself; otherwise returns null. For collections, returns the element at the index.
ST_GeometryType ST_GeometryType(geom) TEXT Returns the subtype name of the input geometry as a string, prefixed with ST_, such as ST_Point or ST_Polygon. This prefix is the only difference from GeometryType, so take the format into account when you write equality conditions.
ST_InteriorRingN ST_InteriorRingN(geom, index) GEOMETRY (LINESTRING) Returns the interior ring of a polygon at the given index position as a closed linestring.
ST_IsClosed ST_IsClosed(geom) BOOLEAN Returns true if the geometry is closed. A point or multipoint is always closed. A linestring is closed when its start and end points coincide. A polygon is closed when all rings are non-empty and their start and end points coincide.
ST_IsCollection ST_IsCollection(geom) BOOLEAN Returns true if the geometry is a GEOMETRYCOLLECTION, MULTIPOINT, MULTILINESTRING, or MULTIPOLYGON.
ST_IsEmpty ST_IsEmpty(geom) BOOLEAN Returns true if the geometry contains no points.
ST_IsPolygonCCW ST_IsPolygonCCW(geom) BOOLEAN Returns true if the exterior ring of the input polygon is oriented counterclockwise and all interior rings are oriented clockwise. Returns false if the exterior ring and the interior rings have the same orientation. Also returns true for points, linestrings, multipoints, and multilinestrings, for geometry collections whose polygon elements all meet the preceding condition, and for an empty polygon (POLYGON EMPTY).
ST_IsPolygonCW ST_IsPolygonCW(geom) BOOLEAN Returns true if the exterior ring of the input polygon is oriented clockwise and all interior rings are oriented counterclockwise. Returns false if the exterior ring and the interior rings have the same orientation. Also returns true for points, linestrings, multipoints, and multilinestrings, for geometry collections whose polygon elements all meet the preceding condition, and for an empty polygon (POLYGON EMPTY).
ST_IsSimple ST_IsSimple(geom) BOOLEAN Returns true if the geometry has no anomalous geometric points such as self-intersections.
ST_NPoints ST_NPoints(geom) INTEGER Returns the number of points in the geometry.
ST_NRings ST_NRings(geom) INTEGER Returns the number of rings in the geometry.
ST_NumGeometries ST_NumGeometries(geom) INTEGER Returns the number of elements in a geometry collection.
ST_NumInteriorRings ST_NumInteriorRings(geom) INTEGER Returns the number of interior rings in a polygon.
ST_NumPoints ST_NumPoints(geom) INTEGER Returns the number of points in the geometry.
ST_PointN ST_PointN(geom, index) GEOMETRY (POINT) Returns the point at the given index in a linestring. Negative index values count from the end: -1 returns the last point.
ST_Points ST_Points(geom) GEOMETRY (MULTIPOINT) Returns all non-empty points in the geometry as a multipoint. Duplicate points, including ring start and end points, are preserved.
ST_StartPoint ST_StartPoint(geom) GEOMETRY Returns the first point of a linestring. The returned geometry has the same SRID as the input.
ST_X ST_X(point) DOUBLE PRECISION Returns the X coordinate of a point.
ST_Y ST_Y(point) DOUBLE PRECISION Returns the Y coordinate of a point.

Geometry editors

All functions in this group run on HQE.

Function Syntax Returns Description
ST_AddPoint ST_AddPoint(geom1, geom2) GEOMETRY Returns a linestring with a point added to it.
ST_Multi ST_Multi(geom) GEOMETRY (MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, or GEOMETRYCOLLECTION) Converts a geometry to its corresponding multi-type. If the input is already a multi-type or collection, returns a copy.
ST_RemovePoint ST_RemovePoint(geom, index) GEOMETRY Returns a linestring with the point at the given zero-based index removed. The returned geometry has the same SRID as the input.
ST_Reverse ST_Reverse(geom) GEOMETRY Reverses the vertex order of a linear or areal geometry. For a point or multipoint, returns a copy. For a collection, reverses vertices for each element.
ST_SetPoint ST_SetPoint(geom1, index, geom2) GEOMETRY Returns a linestring with the point at the given index replaced by the input point's coordinates.

Geometry validation

Function Syntax Returns Required engine Description
ST_IsValid ST_IsValid(geom) BOOLEAN PQE Returns true if the geometry is valid according to the OGC specification.

Spatial reference system functions

All functions in this group run on HQE.

Function Syntax Returns Description
ST_SetSRID ST_SetSRID(geom, srid) GEOMETRY Returns the input geometry with its SRID updated to the given value. Does not reproject the coordinates.
ST_SRID ST_SRID(geom) INTEGER Returns the SRID of the input geometry.

Geometry input

Function Syntax Returns Required engine Description
ST_GeomFromText ST_GeomFromText(wkt_string [, srid]) GEOMETRY PQE Constructs a geometry from its well-known text (WKT) representation.

Geometry output

All functions in this group run on HQE.

Function Syntax Returns Description
ST_AsBinary ST_AsBinary(geom) BYTEA Returns the well-known binary (WKB) representation of the geometry, encoded as a hex string using ASCII characters 09 and AF.
ST_AsEWKB ST_AsEWKB(geom) BYTEA Returns the extended well-known binary (EWKB) representation of the geometry.
ST_AsEWKT ST_AsEWKT(geom) TEXT Returns the extended well-known text (EWKT) representation of the geometry.
ST_AsGeoJSON ST_AsGeoJSON(geom [, maxdecimaldigits]) TEXT Returns the GeoJSON representation of the geometry.
ST_AsText ST_AsText(geom [, precision]) TEXT Returns the WKT representation of the geometry.

Spatial relationship predicates

The engine varies by function in this group. See the Required engine column.

Function Syntax Returns Required engine Description
ST_Contains ST_Contains(geom1, geom2) BOOLEAN PQE Returns true if every point of geom2 is in geom1 and their interiors intersect. Equivalent to ST_Within(geom2, geom1).
ST_ContainsProperly ST_ContainsProperly(geom1, geom2) BOOLEAN PQE Returns true if both geometries are non-empty and all points of geom2 lie in the interior (not the boundary) of geom1.
ST_CoveredBy ST_CoveredBy(geom1, geom2) BOOLEAN HQE Returns true if every point of geom1 is in geom2. Equivalent to ST_Covers(geom2, geom1).
ST_Covers ST_Covers(geom1, geom2) BOOLEAN PQE Returns true if every point of geom2 is in geom1. Equivalent to ST_CoveredBy(geom2, geom1).
ST_Crosses ST_Crosses(geom1, geom2) BOOLEAN HQE Returns true if the two geometries intersect.
ST_Disjoint ST_Disjoint(geom1, geom2) BOOLEAN HQE Returns true if the two geometries share no points.
ST_DWithin ST_DWithin(geom1, geom2, threshold) BOOLEAN PQE Returns true if the Euclidean distance between the two geometries does not exceed the threshold.
ST_DWithin_S2 ST_DWithin_S2(x1, y1, x2, y2, threshold) BOOLEAN HQE Returns true if the spherical distance between two geographic locations is less than or equal to threshold (unit: meters). Parameters in order: longitude of Location 1, latitude of Location 1, longitude of Location 2, latitude of Location 2, distance threshold. Supported in Hologres V2.0.8 and later. Constant inputs are not supported in the current version.
ST_Equals ST_Equals(geom1, geom2) BOOLEAN HQE Returns true if the two geometries have equal point sets and their interiors intersect.
ST_Intersects ST_Intersects(geom1, geom2) BOOLEAN PQE Returns true if the two geometries share at least one point.
ST_Touches ST_Touches(geom1, geom2) BOOLEAN HQE Returns true if the two geometries touch — they intersect but share no interior points.
ST_Within ST_Within(geom1, geom2) BOOLEAN PQE Returns true if every point of geom1 is in geom2 and their interiors intersect. Equivalent to ST_Contains(geom2, geom1).

Measurement functions

Function Syntax Returns Required engine Description
ST_Angle ST_Angle(geom1, geom2, geom3 [, geom4]) DOUBLE PRECISION HQE Returns the clockwise angle in radians in the range [0, 2π). With three points, measures the rotation from P1 to P3 around P2. With four points, measures the angle between directed lines P1–P2 and P3–P4; returns null if P1 equals P2 or P3 equals P4.
ST_Area ST_Area(geom) DOUBLE PRECISION HQE Returns the Cartesian area of the geometry in the same units as the coordinate system. Returns 0 for points, linestrings, and their multi-types. For collections, returns the sum of all element areas.
ST_Azimuth ST_Azimuth(point1, point2) DOUBLE PRECISION HQE Returns the north-based Cartesian azimuth defined by two points.
ST_Distance ST_Distance(geom1, geom2) DOUBLE PRECISION HQE Returns the Cartesian distance between two geometries, expressed in the same units as the input coordinates. To calculate spherical distance in meters, use ST_Distance_Sphere_S2, which takes longitude and latitude values rather than geometries.
ST_Distance_Sphere_S2 ST_Distance_Sphere_S2(x1, y1, x2, y2) DOUBLE PRECISION HQE Returns the spherical distance between two geographic locations in meters. Parameters in order: longitude of Location 1, latitude of Location 1, longitude of Location 2, latitude of Location 2. Valid latitude range: [-90, +90]. Valid longitude range: [-180, +180]. Supported in Hologres V2.0.8 and later. Constant inputs are not supported in the current version.
ST_Length ST_Length(geom) DOUBLE PRECISION HQE Returns the Cartesian length of a linear geometry in the same units as the coordinate system. Returns 0 for points, multipoints, and areal geometries. For collections, returns the total length.
ST_Perimeter ST_Perimeter(geom) DOUBLE PRECISION HQE Returns the Cartesian perimeter (boundary length) of an areal geometry in the same units as the coordinate system. Returns 0 for points, multipoints, and linear geometries. For collections, returns the sum of all element perimeters.

Overlay function

Function Syntax Returns Required engine Description
ST_Intersection ST_Intersection(geom1, geom2) GEOMETRY HQE Returns the geometric intersection of two geometries.

Geometry processing functions

Function Syntax Returns Required engine Description
ST_Buffer ST_Buffer(geom, radius) Same as the input type: GEOMETRY for a geometry input, GEOGRAPHY for a geography input PQE Returns the geometry representing all points within the given radius of the input geometry.
ST_ConvexHull ST_ConvexHull(geom) GEOMETRY HQE Returns the convex hull of all non-empty points in the input geometry.
ST_Simplify ST_Simplify(geom, tolerance) GEOMETRY HQE Returns a simplified copy of the geometry using the Ramer-Douglas-Peucker algorithm with the given tolerance. Topology may not be preserved.

Bounding box functions

All functions in this group run on PQE.

Function Syntax Returns Description
ST_XMax ST_XMax(geom) DOUBLE PRECISION Returns the maximum X coordinate of the bounding box of the geometry. The parameter type is box3d; a geometry input is cast implicitly.
ST_XMin ST_XMin(geom) DOUBLE PRECISION Returns the minimum X coordinate of the bounding box of the geometry. The parameter type is box3d; a geometry input is cast implicitly.
ST_YMax ST_YMax(geom) DOUBLE PRECISION Returns the maximum Y coordinate of the bounding box of the geometry. The parameter type is box3d; a geometry input is cast implicitly.
ST_YMin ST_YMin(geom) DOUBLE PRECISION Returns the minimum Y coordinate of the bounding box of the geometry. The parameter type is box3d; a geometry input is cast implicitly.

Linear referencing function

Function Syntax Returns Required engine Description
ST_LineInterpolatePoint ST_LineInterpolatePoint(geom, fraction) GEOMETRY (POINT) HQE Returns the point at a fractional distance along the line, measured from the start. For example, fraction=0.5 returns the midpoint.

Best practices for using spatial functions

For end-to-end examples of common geographic analysis patterns, see Use spatial functions to query data.