Overlay FunctionsThese functions compute results arising from the overlay of two geometries.
These are also known as point-set theoretic boolean operations.
Some related functions are also provided.
ST_ClipByBox2DComputes the portion of a geometry falling within a rectangle.geometry ST_ClipByBox2Dgeometrygeombox2dboxDescription
Clips a geometry by a 2D box in a fast and tolerant but possibly invalid way.
Topologically invalid input geometries do not result in exceptions being thrown.
The output geometry is not guaranteed to be valid
(in particular, self-intersections for a polygon may be introduced).
Performed by the GEOS module.Availability: 2.2.0ExamplesThis example relies on the implicit cast from geometry to box2d for the second parameter.SELECT ST_ClipByBox2D(geom, ST_MakeEnvelope(0, 0, 10, 10)) FROM mytab;See Also,
,
ST_DifferenceComputes a geometry representing the part of geometry A
that does not intersect geometry B.geometry ST_Differencegeometry geomAgeometry geomBfloat8 gridSize = -1DescriptionReturns a geometry representing the part of geometry A
that does not intersect geometry B.
This is equivalent to A - ST_Intersection(A,B).
If A is completely contained in B
then an empty atomic geometry of appropriate type is returned.This is the only overlay function where input order matters.
ST_Difference(A, B) always returns a portion of A.
&overlay_gridsize_arg;
Performed by the GEOS moduleEnhanced: 3.1.0 accept a gridSize parameter.Requires GEOS >= 3.9.0 to use the gridSize parameter.&sfs_compliant; s2.1.1.3&sqlmm_compliant; SQL-MM 3: 5.1.20&Z_support; However, the result is computed using XY only.
The result Z values are copied, averaged or interpolated.ExamplesThe difference of 2D linestrings.SELECT ST_Difference('LINESTRING(50 100,50 200)'::geometry,
'LINESTRING(50 50,50 150)'::geometry
);LINESTRING(50 150,50 200)The difference of 3D points.SELECT ST_Difference('MULTIPOINT(-118.58 38.38 5,-118.60 38.329 6,-118.614 38.281 7)' :: geometry,
'POINT(-118.614 38.281 5)' :: geometry
);MULTIPOINT(-118.6 38.329 6,-118.58 38.38 5)See Also,
,
,
ST_Intersection
Computes a geometry representing the shared portion of geometries A and B.
geometry ST_IntersectiongeometrygeomAgeometrygeomBfloat8gridSize = -1geography ST_IntersectiongeographygeogAgeographygeogBDescriptionReturns a geometry representing the point-set
intersection of two geometries.
In other words, that portion of geometry A and geometry B
that is shared between the two geometries.If the geometries have no points in common (i.e. are disjoint)
then an empty atomic geometry of appropriate type is returned.
&overlay_gridsize_arg;
ST_Intersection in conjunction with is useful for clipping geometries such as in bounding box, buffer, or region
queries where you only require the portion of a geometry that is inside a country or region of interest.Spatial predicates such as and overlay functions such as
ST_Intersection are computed by different algorithms. For very close or nearly
coincident coordinates, floating-point precision and geometric robustness may make a predicate
return true while the computed intersection is empty, or place an intersection point slightly away
from the input line. For repeatable overlay results, snap inputs to a suitable grid first, for example
with , or use the gridSize parameter when all
input vertices already lie on the grid.&geography_transform; It first determines the best SRID that
fits the bounding box of the 2 geography objects (if geography objects are within one half zone UTM but not same UTM will pick one of those) (favoring UTM or Lambert Azimuthal Equal Area (LAEA) north/south pole, and falling back on mercator in worst case scenario) and then intersection in that best fit planar spatial ref and retransforms back to WGS84 geography.This function will drop the M coordinate values if present.If working with 3D geometries, you may want to use SFCGAL based which does a proper 3D intersection for 3D geometries. Although this function works with Z-coordinate, it does an averaging of Z-Coordinate.Performed by the GEOS moduleEnhanced: 3.1.0 accept a gridSize parameterRequires GEOS >= 3.9.0 to use the gridSize parameterChanged: 3.0.0 does not depend on SFCGAL.Availability: 1.5 support for geography data type was introduced.&sfs_compliant; s2.1.1.3&sqlmm_compliant; SQL-MM 3: 5.1.18&Z_support; However, the result is computed using XY only.
The result Z values are copied, averaged or interpolated.ExamplesSELECT ST_Intersection('POINT(0 0)'::geometry, 'LINESTRING ( 2 0,0 2 )'::geometry);POINT EMPTYSELECT ST_Intersection('POINT(0 0)'::geometry, 'LINESTRING ( 0 0,0 2 )'::geometry);POINT(0 0)
Clip all lines (trails) by country. Here we assume country geom are POLYGON or MULTIPOLYGONS.
NOTE: we are only keeping intersections that result in a LINESTRING or MULTILINESTRING because we don't
care about trails that just share a point. The dump is needed to expand a geometry collection into individual single MULT* parts.
The below is fairly generic and will work for polys, etc. by just changing the where clause.select clipped.gid, clipped.f_name, clipped_geom
from (
select trails.gid, trails.f_name,
(ST_Dump(ST_Intersection(country.geom, trails.geom))).geom clipped_geom
from country
inner join trails on ST_Intersects(country.geom, trails.geom)
) as clipped
where ST_Dimension(clipped.clipped_geom) = 1;For polys e.g. polygon landmarks, you can also use the sometimes faster hack that buffering anything by 0.0 except a polygon results in an empty geometry collection.
(So a geometry collection containing polys, lines and points buffered by 0.0 would only leave the polygons and dissolve the collection shell.)select poly.gid,
ST_Multi(ST_Buffer(ST_Intersection(country.geom, poly.geom),
0.0
)
) clipped_geom
from country
inner join poly on ST_Intersects(country.geom, poly.geom)
where not ST_IsEmpty(ST_Buffer(ST_Intersection(country.geom, poly.geom), 0.0));Note this is not a true 3D intersection. It uses 2.5D geometries (geometries with Z ordinates, but where calculations are performed in 2D). The same input is compared with , which performs a true 3D intersection.WITH data AS (
SELECT 'LINESTRING Z (2 2 6,1.5 1.5 7,1 1 8,0.5 0.5 8,0 0 10)'::geometry AS input_linestring,
'POLYGON Z ((0 0 8,0 1 8,1 1 8,1 0 8,0 0 8))'::geometry AS input_polygon
)
SELECT input_linestring AS input_linestring,
input_polygon AS input_polygon,
ST_Intersection(input_linestring, input_polygon) AS intersection_2d,
CG_3DIntersection(input_linestring, input_polygon) AS intersection_3d
FROM data;LINESTRING Z (2 2 6,1.5 1.5 7,1 1 8,0.5 0.5 8,0 0 10) | POLYGON Z ((0 0 8,0 1 8,1 1 8,1 0 8,0 0 8)) | LINESTRING Z (1 1 8,0.5 0.5 8,0 0 10) | LINESTRING Z (1 1 8,0.5 0.5 8)See Also,
,
,
,
,
,
,
,
,
,
ST_MemUnionAggregate function which unions geometries in a memory-efficent but slower waygeometry ST_MemUniongeometry setgeomfieldDescriptionAn aggregate function that unions the input geometries, merging them to produce a result geometry
with no overlaps.
The output may be a single geometry, a MultiGeometry, or a Geometry Collection.
Produces the same result as , but uses less memory
and more processor time.
This aggregate function works by unioning the geometries incrementally, as opposed to
the ST_Union aggregate which first accumulates an array and then unions the contents
using a fast algorithm.&Z_support; However, the result is computed using XY only.
The result Z values are copied, averaged or interpolated.Examples
SELECT id,
ST_MemUnion(geom) as singlegeom
FROM sometable f
GROUP BY id;
See AlsoST_Node
Nodes a collection of lines.
geometry ST_Nodegeometry geomDescription
Returns a (Multi)LineString representing the fully noded version of a collection of linestrings.
The noding preserves all of the input nodes,
and introduces the least possible number of new nodes.
The resulting linework is dissolved (duplicate lines are removed).
This is a good way to create fully-noded linework suitable for use as input to . can also be used to node and dissolve linework.
It provides an option to specify a gridSize, which can provide simpler and more robust output.
See also for an aggregate variant.
&Z_support;Performed by the GEOS module.Availability: 2.0.0
Changed: 2.4.0 this function uses GEOSNode internally instead of GEOSUnaryUnion.
This may cause the resulting linestrings to have a different order and direction compared to PostGIS < 2.4.
ExamplesNoding a 3D LineString which self-intersects.
SELECT ST_Node('LINESTRINGZ(0 0 0, 10 10 10, 0 10 5, 10 0 3)'::geometry) As output;MULTILINESTRING Z ((0 0 0,5 5 4.5),(5 5 4.5,10 10 10,0 10 5,5 5 4.5),(5 5 4.5,10 0 3))Noding two LineStrings which share common linework.
Note that the result linework is dissolved.
SELECT ST_Node('MULTILINESTRING ((2 5,2 1,7 1),(6 1,4 1,2 3,2 5))'::geometry) As output;MULTILINESTRING((2 5,2 3),(2 3,2 1,4 1),(4 1,2 3),(4 1,6 1),(6 1,7 1))See Also, ST_SplitReturns a collection of geometries created by splitting a geometry by another geometry.geometry ST_SplitgeometryinputgeometrybladeDescription
The function supports splitting a LineString by a (Multi)Point, (Multi)LineString or (Multi)Polygon boundary,
or a (Multi)Polygon by a LineString.
When a (Multi)Polygon is used as as the blade, its linear components
(the boundary) are used for splitting the input.
The result geometry is always a collection.
This function is in a sense the opposite of .
Applying ST_Union to the returned collection should theoretically yield the original geometry
(although due to numerical rounding this may not be exactly the case).
If the the input and blade do not intersect due to numerical precision issues,
the input may not be split as expected.
To avoid this situation it may be necessary
to snap the input to the blade first, using with a small tolerance.
Availability: 2.0.0 requires GEOSEnhanced: 2.2.0 support for splitting a line by a multiline, a multipoint or (multi)polygon boundary was introduced.Enhanced: 2.5.0 support for splitting a polygon by a multiline was introduced.ExamplesSplit a circular polygon by a diagonal line.
SELECT
ST_Split(
ST_Buffer('POINT(100 90)'::geometry, 50),
'LINESTRING(10 10,190 190)'::geometry
);GEOMETRYCOLLECTION(POLYGON((150 90,149 80.2,146.2 70.9,141.6 62.2,135.4 54.6,127.8 48.4,119.1 43.8,109.8 41,100 40,90.2 41,80.9 43.8,72.2 48.4,64.6 54.6,60.1 60.1,129.9 129.9,135.4 125.4,141.6 117.8,146.2 109.1,149 99.8,150 90)), POLYGON((60.1 60.1,58.4 62.2,53.8 70.9,51 80.2,50 90,51 99.8,53.8 109.1,58.4 117.8,64.6 125.4,72.2 131.6,80.9 136.2,90.2 139,100 140,109.8 139,119.1 136.2,127.8 131.6,129.9 129.9,60.1 60.1)))Split a MultiLineString by a Point, where the point lies exactly on both LineStrings elements.SELECT ST_Split('MULTILINESTRING((10 10,190 190),(15 15,30 30,100 90))',
ST_Point(30, 30));GEOMETRYCOLLECTION(
LINESTRING(10 10,30 30),
LINESTRING(30 30,190 190),
LINESTRING(15 15,30 30),
LINESTRING(30 30,100 90)
)Split a LineString by a Point, where the point does not lie exactly on the line.
Shows using to snap the line to the point to allow it to be split.
WITH data AS (SELECT
'LINESTRING(0 0,100 100)'::geometry AS line,
'POINT(51 50)':: geometry AS point
)
SELECT ST_Split(ST_Snap(line, point, 1), point) AS snapped_split,
ST_Split(line, point) AS not_snapped_not_split
FROM data;-[ RECORD 1 ]---------
snapped_split | GEOMETRYCOLLECTION(LINESTRING(0 0,51 50), LINESTRING(51 50,100 100))
not_snapped_not_split | GEOMETRYCOLLECTION(LINESTRING(0 0,100 100))See Also, ST_SubdivideComputes a rectilinear subdivision of a geometry.setof geometry ST_Subdividegeometrygeomintegermax_vertices=256float8gridSize = -1Description
Returns a set of geometries that are the result of dividing geom
into parts using rectilinear lines,
with each part containing no more than max_vertices.
max_vertices must be 5 or more, as 5 points are needed to represent a closed box.
&overlay_gridsize_arg;
Point-in-polygon and other spatial operations are normally faster for indexed subdivided datasets.
Since the bounding boxes for the parts usually cover a smaller area than the original geometry bbox,
index queries produce fewer "hit" cases.
The "hit" cases are faster because the spatial operations
executed by the index recheck process fewer points.
When casting a subdivided geometry to geography, the resulting geography may differ from the original.
Subdivision adds vertices in planar (geometry) space. If vertices are inserted along the boundary, they will alter the geographical representation, where edges are interpreted as geodesic segments.
To minimize distortion, first densify the geography using to add geodesic vertices, then cast to geometry before subdivision.
This is a set-returning function
(SRF) that return a set of rows containing single geometry values.
It can be used in a SELECT list or a FROM clause
to produce a result set with one record for each result geometry.
Performed by the GEOS module.Availability: 2.2.0Enhanced: 2.5.0 reuses existing points on polygon split, vertex count is lowered from 8 to 5.Enhanced: 3.1.0 accept a gridSize parameter.Requires GEOS >= 3.9.0 to use the gridSize parameterExamplesExample:
Subdivide a polygon into parts with no more than 10 vertices,
and assign each part a unique id.
SELECT row_number() OVER() As rn,geom As wkt
FROM (SELECT ST_Subdivide('POLYGON((132 10,119 23,85 35,68 29,66 28,49 42,32 56,22 64,32 110,40 119,36 150,
57 158,75 171,92 182,114 184,132 186,146 178,176 184,179 162,184 141,190 122,
190 100,185 79,186 56,186 52,178 34,168 18,147 13,132 10))'::geometry, 10)) AS f(geom);
rn │ wkt
────┼────────────────────────────────────────────────────────────────────────────────────────────────────────────────
1 │ POLYGON((85 35,68 29,66 28,32 56,22 64,29.82608695652174 100,119 100,119 23,85 35))
2 │ POLYGON((186 52,178 34,168 18,147 13,132 10,119 23,119 56,186 56,186 52))
3 │ POLYGON((185 79,186 56,119 56,119 100,190 100,185 79))
4 │ POLYGON((40 119,36 150,57 158,75 171,92 182,114 184,114 100,29.82608695652174 100,32 110,40 119))
5 │ POLYGON((132 186,146 178,176 184,179 162,184 141,190 122,190 100,114 100,114 184,132 186))
Example:
Densify a long geography line using ST_Segmentize(geography, distance),
and use ST_Subdivide to split the resulting line into sublines of 8 vertices.
Densification minimizes the impact of changes to the geography representation of a geometry
when subdividing.
SELECT ST_Subdivide(ST_Segmentize('LINESTRING(0 0,85 85)'::geography,
1200000)::geometry, 8);
LINESTRING(0 0,0.487578359029357 5.57659056746196,0.984542144675897 11.1527721155093,1.50101059639722 16.7281035483571,1.94532113630331 21.25)
LINESTRING(1.94532113630331 21.25,2.04869538062779 22.3020741387339,2.64204641967673 27.8740533545155,3.29994062412787 33.443216802941,4.04836719489742 39.0084282520239,4.59890468420694 42.5)
LINESTRING(4.59890468420694 42.5,4.92498503922732 44.5680389206321,5.98737409390639 50.1195229244701,7.3290919767674 55.6587646879025,8.79638749938413 60.1969505994924)
LINESTRING(8.79638749938413 60.1969505994924,9.11375579533779 61.1785363177625,11.6558166691368 66.6648504160202,15.642041247655 72.0867690601745,22.8716627200212 77.3609628116894,24.6991785131552 77.8939011989848)
LINESTRING(24.6991785131552 77.8939011989848,39.4046096622744 82.1822848017636,44.7994523421035 82.5156766227011)
LINESTRING(44.7994523421035 82.5156766227011,85 85)
Example:
Subdivide the complex geometries of a table in-place.
The original geometry records are deleted from the source table,
and new records for each subdivided result geometry are inserted.
255
RETURNING id, column1, column2, column3, geom
)
INSERT INTO polygons_table (fid, column1, column2, column3, geom)
SELECT fid, column1, column2, column3,
ST_Subdivide(geom, 255) as geom
FROM complex_areas_to_subdivide;
]]>Example:
Create a new table containing subdivided geometries,
retaining the key of the original geometry so that the new table
can be joined to the source table.
Since ST_Subdivide is a set-returning (table) function
that returns a set of single-value rows,
this syntax automatically produces a table with one row for each result part.
CREATE TABLE subdivided_geoms AS
SELECT pkey, ST_Subdivide(geom) AS geom
FROM original_geoms;
See Also,
,
,
,
ST_SymDifferenceComputes a geometry representing the portions of geometries A and B
that do not intersect.geometry ST_SymDifferencegeometry geomAgeometry geomBfloat8 gridSize = -1DescriptionReturns a geometry representing the portions of geometries A and B
that do not intersect.
This is equivalent to ST_Union(A,B) - ST_Intersection(A,B).
It is called a symmetric difference because ST_SymDifference(A,B) = ST_SymDifference(B,A).
&overlay_gridsize_arg;
Performed by the GEOS moduleEnhanced: 3.1.0 accept a gridSize parameter.Requires GEOS >= 3.9.0 to use the gridSize parameter&sfs_compliant; s2.1.1.3&sqlmm_compliant; SQL-MM 3: 5.1.21&Z_support; However, the result is computed using XY only.
The result Z values are copied, averaged or interpolated.ExamplesThis example shows a 2D-safe symmetric difference of two LineStrings.SELECT ST_SymDifference('LINESTRING(50 100,50 200)',
'LINESTRING(50 50,50 150)'
);MULTILINESTRING((50 150,50 200),(50 50,50 100))In 3D, this example does not produce the expected result.SELECT ST_SymDifference('LINESTRING(1 2 1,1 4 2)',
'LINESTRING(1 1 3,1 3 4)');MULTILINESTRING((1 3 4,1 4 2),(1 1 3,1 2 1))See Also,
,
,
ST_UnaryUnionComputes the union of the components of a single geometry.geometry ST_UnaryUniongeometry geomfloat8 gridSize = -1Description
A single-input variant of .
The input may be a single geometry, a MultiGeometry, or a GeometryCollection.
The union is applied to the individual elements of the input.
This function can be used to fix MultiPolygons which are
invalid due to overlapping components.
However, the input components must each be valid.
An invalid input component such as a bow-tie polygon may cause an error.
For this reason it may be better to use .
Another use of this function is to node and dissolve a collection of
linestrings which cross or overlap
to make them simple.
( also does this,
but it does not provide the gridSize option.)
It is possible to combine ST_UnaryUnion with to fine-tune
how many geometries are be unioned at once.
This allows trading off between memory usage and compute time,
striking a balance between ST_Union and .
&overlay_gridsize_arg;
&Z_support; However, the result is computed using XY only.
The result Z values are copied, averaged or interpolated.Enhanced: 3.1.0 accept a gridSize parameter.Requires GEOS >= 3.9.0 to use the gridSize parameterAvailability: 2.0.0See Also,
,
,
,
,
ST_UnionComputes a geometry representing the point-set union of
the input geometries.geometry ST_Uniongeometryg1geometryg2geometry ST_Uniongeometryg1geometryg2float8gridSizegeometry ST_Uniongeometry[]g1_arraygeometry ST_Uniongeometry setg1fieldgeometry ST_Uniongeometry setg1fieldfloat8gridSizeDescriptionUnions the input geometries, merging geometry to produce a result geometry
with no overlaps.
The output may be an atomic geometry, a MultiGeometry, or a Geometry Collection.
Comes in several variants:Two-input variant:
returns a geometry that is the union of two input geometries.
If either input is NULL, then NULL is returned.
Array variant:
returns a geometry that is the union of an array of geometries.
Aggregate variant:
returns a geometry that is the union of a rowset of geometries.
The ST_Union() function is an "aggregate"
function in the terminology of PostgreSQL. That means that it
operates on rows of data, in the same way the SUM() and AVG()
functions do and like most aggregates, it also ignores NULL geometries.See for a non-aggregate, single-input variant.The ST_Union array and set variants use the fast Cascaded Union algorithm described in http://blog.cleverelephant.ca/2009/01/must-faster-unions-in-postgis-14.html
&overlay_gridsize_arg;
may sometimes be used in place of ST_Union,
if the result is not required to be non-overlapping.
ST_Collect is usually faster than ST_Union because it performs no processing
on the collected geometries.
Performed by the GEOS module.ST_Union creates MultiLineString and does not sew LineStrings into a single LineString.
Use to sew LineStrings.NOTE: this function was formerly called GeomUnion(), which
was renamed from "Union" because UNION is an SQL reserved
word.Enhanced: 3.1.0 accept a gridSize parameter.Requires GEOS >= 3.9.0 to use the gridSize parameterChanged: 3.0.0 does not depend on SFCGAL.Availability: 1.4.0 - ST_Union was enhanced. ST_Union(geomarray) was introduced and also faster aggregate collection in PostgreSQL.&sfs_compliant; s2.1.1.3Aggregate version is not explicitly defined in OGC SPEC.&sqlmm_compliant; SQL-MM 3: 5.1.19
the z-index (elevation) when polygons are involved.&Z_support; However, the result is computed using XY only.
The result Z values are copied, averaged or interpolated.ExamplesAggregate example
SELECT id,
ST_Union(geom) as singlegeom
FROM sometable f
GROUP BY id;
Non-Aggregate exampleSELECT ST_Union('POINT(1 2)'::geometry, 'POINT(-2 3)'::geometry);MULTIPOINT((1 2),(-2 3))SELECT ST_Union('POINT(1 2)'::geometry, 'POINT(1 2)'::geometry);POINT(1 2)3D example - sort of supports 3D (and with mixed geometry types!)SELECT ST_Union(geom)
FROM (
SELECT 'POLYGON Z((-7 4.2 5,-7.1 4.2 5,-7.1 4.3 5,-7 4.2 5))'::geometry geom
UNION ALL
SELECT 'POINT Z(5 5 5)'::geometry geom
UNION ALL
SELECT 'POINT Z(-2 3 1)'::geometry geom
UNION ALL
SELECT 'LINESTRING Z(5 5 5,10 10 10)'::geometry geom
) AS foo;GEOMETRYCOLLECTION(POINT(-2 3 1), LINESTRING(5 5 5,10 10 10), POLYGON((-7 4.2 5,-7.1 4.2 5,-7.1 4.3 5,-7 4.2 5)))This 3D example does not mix dimensions.SELECT ST_Union(geom)
FROM (
SELECT 'POLYGON((-7 4.2 2,-7.1 4.2 3,-7.1 4.3 2,-7 4.2 2))'::geometry geom
UNION ALL
SELECT 'POINT(5 5 5)'::geometry geom
UNION ALL
SELECT 'POINT(-2 3 1)'::geometry geom
UNION ALL
SELECT 'LINESTRING(5 5 5,10 10 10)'::geometry geom
) AS foo;GEOMETRYCOLLECTION(POINT(-2 3 1), LINESTRING(5 5 5,10 10 10), POLYGON((-7 4.2 2,-7.1 4.2 3,-7.1 4.3 2,-7 4.2 2)))This example unions an array built from a query.SELECT ST_Union(ARRAY(SELECT geom FROM sometable));This example unions an array of linestrings.SELECT ST_Union(ARRAY[
'LINESTRING(1 2,3 4)'::geometry,
'LINESTRING(4 5,5 6)'::geometry
]) As wktunion;MULTILINESTRING((1 2,3 4),(4 5,5 6))See Also,
,
,
,
,
,
,