Postgis 3
Postgis 3
Postgis 3
2 Manual
PostGIS 3.3.2 Manual ii
Contents
1 Introduction 1
1.1 Project Steering Committee . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Core Contributors Present . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3 Core Contributors Past . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4 Other Contributors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2 PostGIS Installation 5
2.1 Short Version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Compiling and Install from Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2.1 Getting the Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2.2 Install Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2.3 Build configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2.4 Building . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2.5 Building PostGIS Extensions and Deploying them . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2.6 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.2.7 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.3 Installing and Using the address standardizer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.3.1 Installing Regex::Assemble . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.4 Installing, Upgrading Tiger Geocoder and loading data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.4.1 Tiger Geocoder Enabling your PostGIS database: Using Extension . . . . . . . . . . . . . . . . . . . . . 15
2.4.1.1 Converting a Tiger Geocoder Regular Install to Extension Model . . . . . . . . . . . . . . . . 18
2.4.2 Tiger Geocoder Enabling your PostGIS database: Not Using Extensions . . . . . . . . . . . . . . . . . . 18
2.4.3 Using Address Standardizer Extension with Tiger geocoder . . . . . . . . . . . . . . . . . . . . . . . . 19
2.4.4 Loading Tiger Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.4.5 Upgrading your Tiger Geocoder Install . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.5 Common Problems during installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
PostGIS 3.3.2 Manual iii
3 PostGIS Administration 21
3.1 Performance Tuning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.1.1 Startup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.1.2 Runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.2 Configuring raster support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.3 Creating spatial databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.3.1 Spatially enable database using EXTENSION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.3.2 Spatially enable database without using EXTENSION (discouraged) . . . . . . . . . . . . . . . . . . . . 23
3.3.3 Create a spatially-enabled database from a template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.4 Upgrading spatial databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.4.1 Soft upgrade . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.4.1.1 Soft Upgrade 9.1+ using extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.4.1.2 Soft Upgrade Pre 9.1+ or without extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.4.2 Hard upgrade . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4 Data Management 28
4.1 Spatial Data Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.1.1 OGC Geometry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.1.1.1 Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.1.1.2 LineString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.1.1.3 LinearRing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.1.1.4 Polygon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.1.1.5 MultiPoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.1.1.6 MultiLineString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.1.1.7 MultiPolygon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.1.1.8 GeometryCollection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.1.1.9 PolyhedralSurface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.1.1.10 Triangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.1.1.11 TIN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.1.2 SQL/MM Part 3 - Curves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.1.2.1 CircularString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.1.2.2 CompoundCurve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.1.2.3 CurvePolygon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.1.2.4 MultiCurve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.1.2.5 MultiSurface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.1.3 WKT and WKB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
4.2 Geometry Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.2.1 PostGIS EWKB and EWKT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.3 Geography Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
PostGIS 3.3.2 Manual iv
5 Spatial Queries 57
5.1 Determining Spatial Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.1.1 Dimensionally Extended 9-Intersection Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.1.2 Named Spatial Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
5.1.3 General Spatial Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.2 Using Spatial Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
5.3 Examples of Spatial SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
6 Performance Tips 65
6.1 Small tables of large geometries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
6.1.1 Problem description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
6.1.2 Workarounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
6.2 CLUSTERing on geometry indices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
6.3 Avoiding dimension conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
PostGIS 3.3.2 Manual v
7 Building Applications 67
7.1 Using MapServer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
7.1.1 Basic Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
7.1.2 Frequently Asked Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
7.1.3 Advanced Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
7.1.4 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
7.2 Java Clients (JDBC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
7.3 C Clients (libpq) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
7.3.1 Text Cursors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
7.3.2 Binary Cursors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
8 PostGIS Reference 73
8.1 PostGIS Geometry/Geography/Box Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
8.1.1 box2d . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
8.1.2 box3d . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
8.1.3 geometry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
8.1.4 geometry_dump . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
8.1.5 geography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
8.2 Table Management Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
8.2.1 AddGeometryColumn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
8.2.2 DropGeometryColumn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
8.2.3 DropGeometryTable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
8.2.4 Find_SRID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
8.2.5 Populate_Geometry_Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
8.2.6 UpdateGeometrySRID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
8.3 Geometry Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
8.3.1 ST_Collect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
8.3.2 ST_LineFromMultiPoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
8.3.3 ST_MakeEnvelope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
8.3.4 ST_MakeLine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
8.3.5 ST_MakePoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
8.3.6 ST_MakePointM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
8.3.7 ST_MakePolygon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
8.3.8 ST_Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
8.3.9 ST_PointZ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
8.3.10 ST_PointM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
8.3.11 ST_PointZM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
8.3.12 ST_Polygon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
8.3.13 ST_TileEnvelope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
PostGIS 3.3.2 Manual vi
8.3.14 ST_HexagonGrid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
8.3.15 ST_Hexagon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
8.3.16 ST_SquareGrid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
8.3.17 ST_Square . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
8.3.18 ST_Letters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
8.4 Geometry Accessors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
8.4.1 GeometryType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
8.4.2 ST_Boundary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
8.4.3 ST_BoundingDiagonal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
8.4.4 ST_CoordDim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
8.4.5 ST_Dimension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
8.4.6 ST_Dump . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
8.4.7 ST_DumpPoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
8.4.8 ST_DumpSegments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
8.4.9 ST_DumpRings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
8.4.10 ST_EndPoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
8.4.11 ST_Envelope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
8.4.12 ST_ExteriorRing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
8.4.13 ST_GeometryN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
8.4.14 ST_GeometryType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
8.4.15 ST_HasArc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
8.4.16 ST_InteriorRingN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
8.4.17 ST_IsClosed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
8.4.18 ST_IsCollection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
8.4.19 ST_IsEmpty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
8.4.20 ST_IsPolygonCCW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
8.4.21 ST_IsPolygonCW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
8.4.22 ST_IsRing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
8.4.23 ST_IsSimple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
8.4.24 ST_M . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
8.4.25 ST_MemSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
8.4.26 ST_NDims . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
8.4.27 ST_NPoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
8.4.28 ST_NRings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
8.4.29 ST_NumGeometries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
8.4.30 ST_NumInteriorRings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
8.4.31 ST_NumInteriorRing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
8.4.32 ST_NumPatches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
8.4.33 ST_NumPoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
PostGIS 3.3.2 Manual vii
10 Topology 483
10.1 Topology Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
10.1.1 getfaceedges_returntype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
10.1.2 TopoGeometry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
10.1.3 validatetopology_returntype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
10.2 Topology Domains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
10.2.1 TopoElement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
10.2.2 TopoElementArray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
10.3 Topology and TopoGeometry Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
10.3.1 AddTopoGeometryColumn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
10.3.2 DropTopology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
10.3.3 DropTopoGeometryColumn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
10.3.4 Populate_Topology_Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
PostGIS 3.3.2 Manual xvi
A Appendix 833
A.1 PostGIS 3.3.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 833
A.1.1 Bug and Security Fixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 833
A.2 PostGIS 3.3.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 833
A.2.1 Bug Fixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 834
A.3 PostGIS 3.3.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 834
A.3.1 New features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 834
A.3.2 Breaking Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 834
A.3.3 Enhancements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 834
A.3.4 Bug Fixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835
A.4 PostGIS 3.3.0rc2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835
A.4.1 Bug Fixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835
PostGIS 3.3.2 Manual xxv
PostGIS is an extension to the PostgreSQL object-relational database system which allows GIS (Geographic Information Sys-
tems) objects to be stored in the database. PostGIS includes support for GiST-based R-Tree spatial indexes, and functions for
analysis and processing of GIS objects.
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 License. Feel free to use
this material any way you like, but we ask that you attribute credit to the PostGIS Project and wherever possible, a link back to
http://postgis.net.
PostGIS 3.3.2 Manual 1 / 902
Chapter 1
Introduction
PostGIS is a spatial extension for the PostgreSQL relational database that was created by Refractions Research Inc, as a spatial
database technology research project. Refractions is a GIS and database consulting company in Victoria, British Columbia,
Canada, specializing in data integration and custom software development.
PostGIS is now a project of the OSGeo Foundation and is developed and funded by many FOSS4G developers and organizations
all over the world that gain great benefit from its functionality and versatility.
The PostGIS project development group plans on supporting and enhancing PostGIS to better support a range of important
GIS functionality in the areas of OGC and SQL/MM spatial standards, advanced topological constructs (coverages, surfaces,
networks), data source for desktop user interface tools for viewing and editing GIS data, and web-based access tools.
The PostGIS Project Steering Committee (PSC) coordinates the general direction, release cycles, documentation, and outreach
efforts for the PostGIS project. In addition the PSC provides general user support, accepts and approves patches from the general
PostGIS community and votes on miscellaneous issues involving PostGIS such as developer commit access, new PSC members
or significant API changes.
Raúl Marín Rodríguez MVT support, Bug fixing, Performance and stability improvements, GitHub curation, alignment of
PostGIS with PostgreSQL releases
Regina Obe Buildbot Maintenance, Windows production and experimental builds, documentation, alignment of PostGIS with
PostgreSQL releases, X3D support, TIGER geocoder support, management functions.
Darafei Praliaskouski Index improvements, bug fixing and geometry/geography function improvements, SFCGAL, raster,
GitHub curation, and bot maintenance.
Paul Ramsey (Chair) Co-founder of PostGIS project. General bug fixing, geography support, geography and geometry index
support (2D, 3D, nD index and anything spatial index), underlying geometry internal structures, GEOS functionality inte-
gration and alignment with GEOS releases, alignment of PostGIS with PostgreSQL releases, loader/dumper, and Shapefile
GUI loader.
Sandro Santilli Bug fixes and maintenance, buildbot maintenance, git mirror management, management functions, integration
of new GEOS functionality and alignment with GEOS releases, topology support, and raster framework and low level API
functions.
Nicklas Avén Distance function enhancements (including 3D distance and relationship functions) and additions, Tiny WKB
(TWKB) output format and general user support
PostGIS 3.3.2 Manual 2 / 902
Dan Baston Geometry clustering function additions, other geometry algorithm enhancements, GEOS enhancements and general
user support
Martin Davis GEOS enhancements and documentation
Björn Harrtell MapBox Vector Tile and GeoBuf functions. Gogs testing and GitLab experimentation.
Aliaksandr Kalenik Geometry Processing, PostgreSQL gist, general bug fixing
Bborie Park Prior PSC Member. Raster development, integration with GDAL, raster loader, user support, general bug fixing,
testing on various OS (Slackware, Mac, Windows, and more)
Mark Cave-Ayland Prior PSC Member. Coordinated bug fixing and maintenance effort, spatial index selectivity and binding,
loader/dumper, and Shapefile GUI Loader, integration of new and new function enhancements.
Jorge Arévalo Raster development, GDAL driver support, loader
Olivier Courtin (Emeritus) Input/output XML (KML,GML)/GeoJSON functions, 3D support and bug fixes.
Chris Hodgson Prior PSC Member. General development, site and buildbot maintenance, OSGeo incubation management
Mateusz Loskot CMake support for PostGIS, built original raster loader in python and low level raster API functions
Kevin Neufeld Prior PSC Member. Documentation and documentation support tools, buildbot maintenance, advanced user
support on PostGIS newsgroup, and PostGIS maintenance function enhancements.
Dave Blasby The original developer/Co-founder of PostGIS. Dave wrote the server side objects, index bindings, and many of
the server side analytical functions.
Jeff Lounsbury Original development of the Shapefile loader/dumper.
Mark Leslie Ongoing maintenance and development of core functions. Enhanced curve support. Shapefile GUI loader.
Pierre Racine Architect of PostGIS raster implementation. Raster overall architecture, prototyping, programming support
David Zwarg Raster development (mostly map algebra analytic functions)
• Cooperativa Alveo
• Deimos Space
• Faunalia
• Geographic Data BC
• Hunter Systems Group
• ISciences, LLC
• Kontur
• Lidwala Consulting Engineers
• LISAsoft
• Logical Tracking & Tracing International AG
• Maponics
• Michigan Tech Research Institute
• Natural Resources Canada
• Norwegian Forest and Landscape Institue
• Norwegian Institute of Bioeconomy Research (NIBIO)
• OSGeo
• Oslandia
• Palantir Technologies
• Paragon Corporation
• R3 GIS
• Refractions Research
• Regione Toscana - SITA
• Safe Software
• Sirius Corporation plc
• Stadt Uster
• UC Davis Center for Vectorborne Diseases
• Université Laval
• U.S. Department of State (HIU)
• Zonar Systems
Crowd Funding Campaigns Crowd funding campaigns are campaigns we run to get badly wanted features funded that can
service a large number of people. Each campaign is specifically focused on a particular feature or set of features. Each
sponsor chips in a small fraction of the needed funding and with enough people/organizations contributing, we have the
funds to pay for the work that will help many. If you have an idea for a feature you think many others would be willing to
co-fund, please post to the PostGIS newsgroup your thoughts and together we can make it happen.
PostGIS 2.0.0 was the first release we tried this strategy. We used PledgeBank and we got two successful campaigns out
of it.
postgistopology - 10 plus sponsors each contributed $250 USD to build toTopoGeometry function and beef up topology
support in 2.0.0. It happened.
postgis64windows - 20 someodd sponsors each contributed $100 USD to pay for the work needed to work out PostGIS
64-bit issues on windows. It happened.
Important Support Libraries The GEOS geometry operations library
The GDAL Geospatial Data Abstraction Library used to power much of the raster functionality introduced in PostGIS 2.
In kind, improvements needed in GDAL to support PostGIS are contributed back to the GDAL project.
The PROJ cartographic projection library
Last but not least, PostgreSQL, the giant that PostGIS stands on. Much of the speed and flexibility of PostGIS would not be
possible without the extensibility, great query planner, GIST index, and plethora of SQL features provided by PostgreSQL.
PostGIS 3.3.2 Manual 5 / 902
Chapter 2
PostGIS Installation
To compile assuming you have all the dependencies in your search path:
tar -xvfz postgis-3.3.2.tar.gz
cd postgis-3.3.2
./configure
make
make install
Once PostGIS is installed, it needs to be enabled (Section 3.3) or upgraded (Section 3.4) in each individual database you want to
use it in.
Note
Many OS systems now include pre-built packages for PostgreSQL/PostGIS. In many cases compilation is only neces-
sary if you want the most bleeding edge versions or you are a package maintainer.
This section includes general compilation instructions, if you are compiling for Windows etc or another OS, you may
find additional more detailed help at PostGIS User contributed compile guides and PostGIS Dev Wiki.
Pre-Built Packages for various OS are listed in PostGIS Pre-built Packages
If you are a windows user, you can get stable builds via Stackbuilder or PostGIS Windows download site We also
have very bleeding-edge windows experimental builds that are built usually once or twice a week or whenever anything
exciting happens. You can use these to experiment with the in progress releases of PostGIS
The PostGIS module is an extension to the PostgreSQL backend server. As such, PostGIS 3.3.2 requires full PostgreSQL server
headers access in order to compile. It can be built against PostgreSQL versions 11 - 15. Earlier versions of PostgreSQL are not
supported.
Refer to the PostgreSQL installation guides if you haven’t already installed PostgreSQL. http://www.postgresql.org .
PostGIS 3.3.2 Manual 6 / 902
Note
For GEOS functionality, when you install PostgresSQL you may need to explicitly link PostgreSQL against the standard
C++ library:
LDFLAGS=-lstdc++ ./configure [YOUR OPTIONS HERE]
This is a workaround for bogus C++ exceptions interaction with older development tools. If you experience weird
problems (backend unexpectedly closed or similar things) try this trick. This will require recompiling your PostgreSQL
from scratch, of course.
The following steps outline the configuration and compilation of the PostGIS source. They are written for Linux users and will
not work on Windows or Mac.
Retrieve the PostGIS source archive from the downloads website http://download.osgeo.org/postgis/source/postgis-3.3.2.tar.gz
wget http://download.osgeo.org/postgis/source/postgis-3.3.2.tar.gz
tar -xvzf postgis-3.3.2.tar.gz
cd postgis-3.3.2
This will create a directory called postgis-3.3.2 in the current working directory.
Alternatively, checkout the source from the git repository https://git.osgeo.org/gitea/postgis/postgis/ .
git clone https://git.osgeo.org/gitea/postgis/postgis.git postgis
cd postgis
sh autogen.sh
Change into the newly created postgis directory to continue the installation.
./configure
• PostgreSQL 11 - 15. A complete installation of PostgreSQL (including server headers) is required. PostgreSQL is available
from http://www.postgresql.org .
For a full PostgreSQL / PostGIS support matrix and PostGIS/GEOS support matrix refer to http://trac.osgeo.org/postgis/wiki/-
UsersWikiPostgreSQLPostGIS
• GNU C compiler (gcc). Some other ANSI C compilers can be used to compile PostGIS, but we find far fewer problems when
compiling with gcc.
• GNU Make (gmake or make). For many systems, GNU make is the default version of make. Check the version by invoking
make -v. Other versions of make may not process the PostGIS Makefile properly.
• Proj reprojection library. Proj 4.9 or above is required. The Proj library is used to provide coordinate reprojection support
within PostGIS. Proj is available for download from https://proj.org/ .
• GEOS geometry library, version 3.6 or greater, but GEOS 3.9+ is required to take full advantage of all the new functions and
features. GEOS is available for download from http://trac.osgeo.org/geos/ .
• LibXML2, version 2.5.x or higher. LibXML2 is currently used in some imports functions (ST_GeomFromGML and ST_GeomFromKM
LibXML2 is available for download from https://gitlab.gnome.org/GNOME/libxml2/-/releases.
PostGIS 3.3.2 Manual 7 / 902
• JSON-C, version 0.9 or higher. JSON-C is currently used to import GeoJSON via the function ST_GeomFromGeoJson.
JSON-C is available for download from https://github.com/json-c/json-c/releases/.
• GDAL, version 2+ is required 3+ is preferred. This is required for raster support. https://gdal.org/download.html.
• If compiling with PostgreSQL+JIT, LLVM version >=6 is required https://trac.osgeo.org/postgis/ticket/4125.
Optional
• GDAL (pseudo optional) only if you don’t want raster you can leave it out. Also make sure to enable the drivers you want to
use as described in Section 3.2.
• GTK (requires GTK+2.0, 2.8+) to compile the shp2pgsql-gui shape file loader. http://www.gtk.org/ .
• SFCGAL, version 1.3.1 (or higher), 1.4.1 or higher is recommended. SFCGAL can be used to provide additional 2D and
3D advanced analysis functions to PostGIS cf Section 8.20. And also allow to use SFCGAL rather than GEOS for some 2D
functions provided by both backends (like ST_Intersection or ST_Area, for instance). A PostgreSQL configuration vari-
able postgis.backend allow end user to control which backend he want to use if SFCGAL is installed (GEOS by
default). Nota: SFCGAL 1.2 require at least CGAL 4.3 and Boost 1.54 (cf: https://oslandia.gitlab.io/SFCGAL/dev.html)
https://gitlab.com/Oslandia/SFCGAL/.
• In order to build the Section 14.1 you will also need PCRE http://www.pcre.org (which generally is already installed on nix sys-
tems). Regex::Assemble perl CPAN package is only needed if you want to rebuild the data encoded in parseaddress-stciti
h. Section 14.1 will automatically be built if it detects a PCRE library, or you pass in a valid --with-pcre-dir=/path/to/pcre
during configure.
• To enable ST_AsMVT protobuf-c library 1.1.0 or higher (for usage) and the protoc-c compiler (for building) are required.
Also, pkg-config is required to verify the correct minimum version of protobuf-c. See protobuf-c. By default, Postgis will use
Wagyu to validate MVT polygons faster which requires a c++11 compiler. It will use CXXFLAGS and the same compiler as
the PostgreSQL installation. To disable this and use GEOS instead use the --without-wagyu during the configure step.
• CUnit (CUnit). This is needed for regression testing. http://cunit.sourceforge.net/
• DocBook (xsltproc) is required for building the documentation. Docbook is available from http://www.docbook.org/ .
• DBLatex (dblatex) is required for building the documentation in PDF format. DBLatex is available from http://dblatex.sourceforge.n
.
• ImageMagick (convert) is required to generate the images used in the documentation. ImageMagick is available from
http://www.imagemagick.org/ .
As with most linux installations, the first step is to generate the Makefile that will be used to build the source code. This is done
by running the shell script
./configure
With no additional parameters, this command will attempt to automatically locate the required components and libraries needed
to build the PostGIS source code on your system. Although this is the most common usage of ./configure, the script accepts
several parameters for those who have the required libraries and programs in non-standard locations.
The following list shows only the most commonly used parameters. For a complete list, use the --help or --help=short parame-
ters.
--with-library-minor-version Starting with PostGIS 3.0, the library files generated by default will no longer have the minor
version as part of the file name. This means all PostGIS 3 libs will end in postgis-3. This was done to make pg_upgrade
easier, with downside that you can only install one version PostGIS 3 series in your server. To get the old behavior of file
including the minor version: e.g. postgis-3.0 add this switch to your configure statement.
--prefix=PREFIX This is the location the PostGIS loader executables and shared libs will be installed. By default, this location
is the same as the detected PostgreSQL installation.
PostGIS 3.3.2 Manual 8 / 902
Caution
This parameter is currently broken, as the package will only install into the PostgreSQL installation directory. Visit
http://trac.osgeo.org/postgis/ticket/635 to track this bug.
--with-pgconfig=FILE PostgreSQL provides a utility called pg_config to enable extensions like PostGIS to locate the Post-
greSQL installation directory. Use this parameter (--with-pgconfig=/path/to/pg_config) to manually specify a particular
PostgreSQL installation that PostGIS will build against.
--with-gdalconfig=FILE GDAL, a required library, provides functionality needed for raster support gdal-config to enable soft-
ware installations to locate the GDAL installation directory. Use this parameter (--with-gdalconfig=/path/to/gdal-config)
to manually specify a particular GDAL installation that PostGIS will build against.
--with-geosconfig=FILE GEOS, a required geometry library, provides a utility called geos-config to enable software installa-
tions to locate the GEOS installation directory. Use this parameter (--with-geosconfig=/path/to/geos-config) to manually
specify a particular GEOS installation that PostGIS will build against.
--with-xml2config=FILE LibXML is the library required for doing GeomFromKML/GML processes. It normally is found
if you have libxml installed, but if not or you want a specific version used, you’ll need to point PostGIS at a specific
xml2-config confi file to enable software installations to locate the LibXML installation directory. Use this parameter
(>--with-xml2config=/path/to/xml2-config) to manually specify a particular LibXML installation that PostGIS will build
against.
--with-projdir=DIR Proj is a reprojection library required by PostGIS. Use this parameter (--with-projdir=/path/to/projdir)
to manually specify a particular Proj installation directory that PostGIS will build against.
--with-libiconv=DIR Directory where iconv is installed.
--with-jsondir=DIR JSON-C is an MIT-licensed JSON library required by PostGIS ST_GeomFromJSON support. Use this
parameter (--with-jsondir=/path/to/jsondir) to manually specify a particular JSON-C installation directory that PostGIS
will build against.
--with-pcredir=DIR PCRE is an BSD-licensed Perl Compatible Regular Expression library required by address_standardizer
extension. Use this parameter (--with-pcredir=/path/to/pcredir) to manually specify a particular PCRE installation di-
rectory that PostGIS will build against.
--with-gui Compile the data import GUI (requires GTK+2.0). This will create shp2pgsql-gui graphical interface to shp2pgsql.
--without-raster Compile without raster support.
--without-topology Disable topology support. There is no corresponding library as all logic needed for topology is in postgis-
3.3.2 library.
--with-gettext=no By default PostGIS will try to detect gettext support and compile with it, however if you run into incompatibil-
ity issues that cause breakage of loader, you can disable it entirely with this command. Refer to ticket http://trac.osgeo.org/-
postgis/ticket/748 for an example issue solved by configuring with this. NOTE: that you aren’t missing much by turning
this off. This is used for international help/label support for the GUI loader which is not yet documented and still experi-
mental.
--with-sfcgal=PATH By default PostGIS will not install with sfcgal support without this switch. PATH is an optional argument
that allows to specify an alternate PATH to sfcgal-config.
--without-phony-revision Disable updating postgis_revision.h to match current HEAD of the git repository.
Note
If you obtained PostGIS from the code repository , the first step is really to run the script
./autogen.sh
This script will generate the configure script that in turn is used to customize the installation of PostGIS.
If you instead obtained PostGIS as a tarball, running ./autogen.sh is not necessary as configure has already been
generated.
PostGIS 3.3.2 Manual 9 / 902
2.2.4 Building
Once the Makefile has been generated, building PostGIS is as simple as running
make
The last line of the output should be "PostGIS was built successfully. Ready to install."
As of PostGIS v1.4.0, all the functions have comments generated from the documentation. If you wish to install these comments
into your spatial databases later, run the command which requires docbook. The postgis_comments.sql and other package
comments files raster_comments.sql, topology_comments.sql are also packaged in the tar.gz distribution in the doc folder so no
need to make comments if installing from the tar ball. Comments are also included as part of the CREATE EXTENSION install.
make comments
Introduced in PostGIS 2.0. This generates html cheat sheets suitable for quick reference or for student handouts. This requires
xsltproc to build and will generate 4 files in doc folder topology_cheatsheet.html, tiger_geocoder_cheatsheet.
html, raster_cheatsheet.html, postgis_cheatsheet.html
You can download some pre-built ones available in html and pdf from PostGIS / PostgreSQL Study Guides
make cheatsheets
The PostGIS extensions are built and installed automatically if you are using PostgreSQL 9.1+.
If you are building from source repository, you need to build the function descriptions first. These get built if you have docbook
installed. You can also manually build with the statement:
make comments
Building the comments is not necessary if you are building from a release tar ball since these are packaged pre-built with the tar
ball already.
The extensions should automatically build as part of the make install process. You can if needed build from the extensions folders
or copy files if you need them on a different server.
cd extensions
cd postgis
make clean
make
export PGUSER=postgres #overwrite psql variables
make check #to test before install
make install
# to test extensions
make check RUNTESTFLAGS=--extension
Note
make check uses psql to run tests and as such can use psql environment variables. Common ones useful to override
are PGUSER,PGPORT, and PGHOST. Refer to psql environment variables
The extension files will always be the same for the same version of PostGIS and PostgreSQL regardless of OS, so it is fine to
copy over the extension files from one OS to another as long as you have the PostGIS binaries already installed on your servers.
If you want to install the extensions manually on a separate server different from your development, You need to copy the
following files from the extensions folder into the PostgreSQL / share / extension folder of your PostgreSQL install
as well as the needed binaries for regular PostGIS if you don’t have them already on the server.
• These are the control files that denote information such as the version of the extension to install if not specified. postgis.
control, postgis_topology.control.
PostGIS 3.3.2 Manual 10 / 902
• All the files in the /sql folder of each extension. Note that these need to be copied to the root of the PostgreSQL share/extension
folder extensions/postgis/sql/*.sql, extensions/postgis_topology/sql/*.sql
Once you do that, you should see postgis, postgis_topology as available extensions in PgAdmin -> extensions.
If you are using psql, you can verify that the extensions are installed by running this query:
SELECT name, default_version,installed_version
FROM pg_available_extensions WHERE name LIKE 'postgis%' or name LIKE 'address%';
If you have the extension installed in the database you are querying, you’ll see mention in the installed_version column.
If you get no records back, it means you don’t have postgis extensions installed on the server at all. PgAdmin III 1.14+ will also
provide this information in the extensions section of the database browser tree and will even allow upgrade or uninstall by
right-clicking.
If you have the extensions available, you can install postgis extension in your database of choice by either using pgAdmin
extension interface or running these sql commands:
CREATE EXTENSION postgis;
CREATE EXTENSION postgis_raster;
CREATE EXTENSION postgis_sfcgal;
CREATE EXTENSION fuzzystrmatch; --needed for postgis_tiger_geocoder
--optional used by postgis_tiger_geocoder, or can be used standalone
CREATE EXTENSION address_standardizer;
CREATE EXTENSION address_standardizer_data_us;
CREATE EXTENSION postgis_tiger_geocoder;
CREATE EXTENSION postgis_topology;
In psql you can use to see what versions you have installed and also what schema they are installed.
\connect mygisdb
\x
\dx postgis*
Name | postgis_topology
Version | 3.3.2
Schema | topology
Description | PostGIS topology spatial types and functions
Warning
Extension tables spatial_ref_sys, layer, topology can not be explicitly backed up. They can only be backed
up when the respective postgis or postgis_topology extension is backed up, which only seems to happen
when you backup the whole database. As of PostGIS 2.0.1, only srid records not packaged with PostGIS are backed
up when the database is backed up so don’t go around changing srids we package and expect your changes to be
there. Put in a ticket if you find an issue. The structures of extension tables are never backed up since they are created
with CREATE EXTENSION and assumed to be the same for a given version of an extension. These behaviors are
built into the current PostgreSQL extension model, so nothing we can do about it.
If you installed 3.3.2, without using our wonderful extension system, you can change it to be extension based by running the below
commands to package the functions in their respective extension. Installing using `unpackaged` was removed in PostgreSQL 13,
so you are advised to switch to an extension build before upgrading to PostgreSQL 13.
CREATE EXTENSION postgis FROM unpackaged;
CREATE EXTENSION postgis_raster FROM unpackaged;
CREATE EXTENSION postgis_topology FROM unpackaged;
CREATE EXTENSION postgis_tiger_geocoder FROM unpackaged;
2.2.6 Testing
Note
If you configured PostGIS using non-standard PostgreSQL, GEOS, or Proj locations, you may need to add their library
locations to the LD_LIBRARY_PATH environment variable.
Caution
Currently, the make check relies on the PATH and PGPORT environment variables when performing the checks - it
does not use the PostgreSQL version that may have been specified using the configuration parameter --with-pgconfig.
So make sure to modify your PATH to match the detected PostgreSQL installation during configuration or be prepared
to deal with the impending headaches.
If successful, make check will produce the output of almost 500 tests. The results will look similar to the following (numerous
lines omitted below):
.
.
.
PostGIS 3.3.2 Manual 12 / 902
.
.
.
Running tests
.
.
.
.
.
.
Running tests
.
.
.
Run tests: 13
Failed: 0
.
.
.
.
.
.
Running tests
.
.
.
-- topology regress
PostGIS 3.3.2 Manual 13 / 902
.
.
.
Running tests
.
.
.
Run tests: 51
Failed: 0
.
.
.
The postgis_tiger_geocoder and address_standardizer extensions, currently only support the standard Post-
greSQL installcheck. To test these use the below. Note: the make install is not necessary if you already did make install at root
of PostGIS code folder.
For address_standardizer:
cd extensions/address_standardizer
make install
make installcheck
=====================
All 4 tests passed.
=====================
For tiger geocoder, make sure you have postgis and fuzzystrmatch extensions available in your PostgreSQL instance. The
address_standardizer tests will also kick in if you built postgis with address_standardizer support:
cd extensions/postgis_tiger_geocoder
make install
make installcheck
PostGIS 3.3.2 Manual 14 / 902
=====================
All 2 tests passed.
=====================
2.2.7 Installation
If you previously ran the make comments command to generate the postgis_comments.sql, raster_comments.sql
file, install the sql file by running
make comments-install
Note
postgis_comments.sql, raster_comments.sql, topology_comments.sql was separated from the
typical build and installation targets since with it comes the extra dependency of xsltproc.
The address_standardizer extension used to be a separate package that required separate download. From PostGIS 2.2
on, it is now bundled in. For more information about the address_standardize, what it does, and how to configure it for your
needs, refer to Section 14.1.
This standardizer can be used in conjunction with the PostGIS packaged tiger geocoder extension as a replacement for the
Normalize_Address discussed. To use as replacement refer to Section 2.4.3. You can also use it as a building block for your own
geocoder or use it to standardize your addresses for easier compare of addresses.
PostGIS 3.3.2 Manual 15 / 902
The address standardizer relies on PCRE which is usually already installed on many Nix systems, but you can download the
latest at: http://www.pcre.org. If during Section 2.2.3, PCRE is found, then the address standardizer extension will automatically
be built. If you have a custom pcre install you want to use instead, pass to configure --with-pcredir=/path/to/pcre
where /path/to/pcre is the root folder for your pcre include and lib directories.
For Windows users, the PostGIS 2.1+ bundle is packaged with the address_standardizer already so no need to compile and can
move straight to CREATE EXTENSION step.
Once you have installed, you can connect to your database and run the SQL:
CREATE EXTENSION address_standardizer;
Output should be
num | street | city | state | zip
-----+------------------------+--------+-------+-------
1 | Devonshire Place PH301 | Boston | MA | 02109
Perl Regex:Assemble is no longer needed for compiling address_standardizer extension since the files it generates are part of the
source tree. However if you need to edit the usps-st-city-orig.txt or usps-st-city-orig.txt usps-st-city-add
tx, you need to rebuild parseaddress-stcities.h which does require Regex:Assemble.
cpan Regexp::Assemble
Extras like Tiger geocoder may not be packaged in your PostGIS distribution. If you are missing the tiger geocoder extension or
want a newer version than what your install comes with, then use the share/extension/postgis_tiger_geocoder.*
files from the packages in Windows Unreleased Versions section for your version of PostgreSQL. Although these packages are for
windows, the postgis_tiger_geocoder extension files will work on any OS since the extension is an SQL/plpgsql only extension.
If you are using PostgreSQL 9.1+ and PostGIS 2.1+, you can take advantage of the new extension model for installing tiger
geocoder. To do so:
1. First get binaries for PostGIS 2.1+ or compile and install as usual. This should install the necessary extension files as well
for tiger geocoder.
2. Connect to your database via psql or pgAdmin or some other tool and run the following SQL commands. Note that if you
are installing in a database that already has postgis, you don’t need to do the first step. If you have fuzzystrmatch
extension already installed, you don’t need to do the second step either.
PostGIS 3.3.2 Manual 16 / 902
If you already have postgis_tiger_geocoder extension installed, and just want to update to the latest run:
ALTER EXTENSION postgis UPDATE;
ALTER EXTENSION postgis_tiger_geocoder UPDATE;
If you made custom entries or changes to tiger.loader_platform and tiger.loader_variables you may
need to update these.
3. To confirm your install is working correctly, run this sql in your database:
SELECT na.address, na.streetname,na.streettypeabbrev, na.zip
FROM normalize_address('1 Devonshire Place, Boston, MA 02109') AS na;
4. Create a new record in tiger.loader_platform table with the paths of your executables and server.
So for example to create a profile called debbie that follows sh convention. You would do:
INSERT INTO tiger.loader_platform(os, declare_sect, pgbin, wget, unzip_command, psql, ←-
path_sep,
loader, environ_set_command, county_process_command)
SELECT 'debbie', declare_sect, pgbin, wget, unzip_command, psql, path_sep,
loader, environ_set_command, county_process_command
FROM tiger.loader_platform
WHERE os = 'sh';
And then edit the paths in the declare_sect column to those that fit Debbie’s pg, unzip,shp2pgsql, psql, etc path locations.
If you don’t edit this loader_platform table, it will just contain common case locations of items and you’ll have to
edit the generated script after the script is generated.
5. As of PostGIS 2.4.1 the Zip code-5 digit tabulation area zcta5 load step was revised to load current zcta5 data and is part
of the Loader_Generate_Nation_Script when enabled. It is turned off by default because it takes quite a bit of time to load
(20 to 60 minutes), takes up quite a bit of disk space, and is not used that often.
To enable it, do the following:
UPDATE tiger.loader_lookuptables SET load = true WHERE table_name = 'zcta520';
If present the Geocode function can use it if a boundary filter is added to limit to just zips in that boundary. The Re-
verse_Geocode function uses it if the returned address is missing a zip, which often happens with highway reverse geocod-
ing.
6. Create a folder called gisdata on root of server or your local pc if you have a fast network connection to the server.
This folder is where the tiger files will be downloaded to and processed. If you are not happy with having the folder on
the root of the server, or simply want to change to a different folder for staging, then edit the field staging_fold in the
tiger.loader_variables table.
7. Create a folder called temp in the gisdata folder or wherever you designated the staging_fold to be. This will be
the folder where the loader extracts the downloaded tiger data.
PostGIS 3.3.2 Manual 17 / 902
8. Then run the Loader_Generate_Nation_Script SQL function make sure to use the name of your custom profile and copy
the script to a .sh or .bat file. So for example to build the nation load:
psql -c "SELECT Loader_Generate_Nation_Script('debbie')" -d geocoder -tA > /gisdata/ ←-
nation_script_load.sh
10. After you are done running the nation script, you should have three tables in your tiger_data schema and they should
be filled with data. Confirm you do by doing the following queries from psql or pgAdmin
SELECT count(*) FROM tiger_data.county_all;
count
-------
3233
(1 row)
count
-------
56
(1 row)
11. By default the tables corresponding to bg, tract, tabblock are not loaded. These tables are not used by the geocoder
but are used by folks for population statistics. If you wish to load them as part of your state loads, run the following
statement to enable them.
UPDATE tiger.loader_lookuptables SET load = true WHERE load = false AND lookup_name IN ←-
('tract', 'bg', 'tabblock');
Alternatively you can load just these tables after loading state data using the Loader_Generate_Census_Script
12. For each state you want to load data for, generate a state script Loader_Generate_Script.
Warning
DO NOT Generate the state script until you have already loaded the nation data, because the state script utilizes
county list loaded by nation script.
13.
psql -c "SELECT Loader_Generate_Script(ARRAY['MA'], 'debbie')" -d geocoder -tA > / ←-
gisdata/ma_load.sh
15. After you are done loading all data or at a stopping point, it’s a good idea to analyze all the tiger tables to update the stats
(include inherited stats)
PostGIS 3.3.2 Manual 18 / 902
SELECT install_missing_indexes();
vacuum (analyze, verbose) tiger.addr;
vacuum (analyze, verbose) tiger.edges;
vacuum (analyze, verbose) tiger.faces;
vacuum (analyze, verbose) tiger.featnames;
vacuum (analyze, verbose) tiger.place;
vacuum (analyze, verbose) tiger.cousub;
vacuum (analyze, verbose) tiger.county;
vacuum (analyze, verbose) tiger.state;
vacuum (analyze, verbose) tiger.zip_lookup_base;
vacuum (analyze, verbose) tiger.zip_state;
vacuum (analyze, verbose) tiger.zip_state_loc;
If you installed the tiger geocoder without using the extension model, you can convert to the extension model as follows:
2.4.2 Tiger Geocoder Enabling your PostGIS database: Not Using Extensions
The normalizing address functionality works more or less without any data except for tricky addresses. Run this test and verify
things look like this:
SELECT pprint_addy(normalize_address('202 East Fremont Street, Las Vegas, Nevada 89101')) ←-
As pretty_address;
pretty_address
---------------------------------------
202 E Fremont St, Las Vegas, NV 89101
PostGIS 3.3.2 Manual 19 / 902
One of the many complaints of folks is the address normalizer function Normalize_Address function that normalizes an address
for prepping before geocoding. The normalizer is far from perfect and trying to patch its imperfectness takes a vast amount of
resources. As such we have integrated with another project that has a much better address standardizer engine. To use this new
address_standardizer, you compile the extension as described in Section 2.3 and install as an extension in your database.
Once you install this extension in the same database as you have installed postgis_tiger_geocoder, then the Pagc_Normalize_Ad
can be used instead of Normalize_Address. This extension is tiger agnostic, so can be used with other data sources such
as international addresses. The tiger geocoder extension does come packaged with its own custom versions of rules table (
tiger.pagc_rules) , gaz table (tiger.pagc_gaz), and lex table (tiger.pagc_lex). These you can add and update
to improve your standardizing experience for your own needs.
The instructions for loading data are available in a more detailed form in the extras/tiger_geocoder/tiger_2011/
README. This just includes the general steps.
The load process downloads data from the census website for the respective nation files, states requested, extracts the files,
and then loads each state into its own separate set of state tables. Each state table inherits from the tables defined in tiger
schema so that its sufficient to just query those tables to access all the data and drop a set of state tables at any time using the
Drop_State_Tables_Generate_Script if you need to reload a state or just don’t need a state anymore.
In order to be able to load data you’ll need the following tools:
If you are upgrading from tiger_2010, you’ll need to first generate and run Drop_Nation_Tables_Generate_Script. Before you
load any state data, you need to load the nation wide data which you do with Loader_Generate_Nation_Script. Which will
generate a loader script for you. Loader_Generate_Nation_Script is a one-time step that should be done for upgrading (from
2010) and for new installs.
To load state data refer to Loader_Generate_Script to generate a data load script for your platform for the states you desire. Note
that you can install these piecemeal. You don’t have to load all the states you want all at once. You can load them as you need
them.
After the states you desire have been loaded, make sure to run the:
SELECT install_missing_indexes();
as described in Install_Missing_Indexes.
To test that things are working as they should, try to run a geocode on an address in your state using Geocode
If you have Tiger Geocoder packaged with 2.0+ already installed, you can upgrade the functions at any time even from an interim
tar ball if there are fixes you badly need. This will only work for Tiger geocoder not installed with extensions.
If you don’t have an extras folder, download http://download.osgeo.org/postgis/source/postgis-3.3.2.tar.gz
tar xvfz postgis-3.3.2.tar.gz
PostGIS 3.3.2 Manual 20 / 902
cd postgis-3.3.2/extras/tiger_geocoder/tiger_2011
Locate the upgrade_geocoder.bat script If you are on windows or the upgrade_geocoder.sh if you are on Linux/U-
nix/Mac OSX. Edit the file to have your postgis database credentials.
If you are upgrading from 2010 or 2011, make sure to unremark out the loader script line so you get the latest script for loading
2012 data.
Then run th corresponding script from the commandline.
Next drop all nation tables and load up the new ones. Generate a drop script with this SQL statement as detailed in Drop_Nation_Tables_G
SELECT drop_nation_tables_generate_script();
For unix/linux
SELECT loader_generate_nation_script('sh');
Refer to Section 2.4.4 for instructions on how to run the generate script. This only needs to be done once.
Note
You can have a mix of 2010/2011 state tables and can upgrade each state separately. Before you upgrade a state to
2011, you first need to drop the 2010 tables for that state using Drop_State_Tables_Generate_Script.
There are several things to check when your installation or upgrade doesn’t go as you expected.
1. Check that you have installed PostgreSQL 11 or newer, and that you are compiling against the same version of the Post-
greSQL source as the version of PostgreSQL that is running. Mix-ups can occur when your (Linux) distribution has already
installed PostgreSQL, or you have otherwise installed PostgreSQL before and forgotten about it. PostGIS will only work
with PostgreSQL 11 or newer, and strange, unexpected error messages will result if you use an older version. To check the
version of PostgreSQL which is running, connect to the database using psql and run this query:
SELECT version();
If you are running an RPM based distribution, you can check for the existence of pre-installed packages using the rpm
command as follows: rpm -qa | grep postgresql
2. If your upgrade fails, make sure you are restoring into a database that already has PostGIS installed.
SELECT postgis_full_version();
Also check that configure has correctly detected the location and version of PostgreSQL, the Proj library and the GEOS library.
1. The output from configure is used to generate the postgis_config.h file. Check that the POSTGIS_PGSQL_VERSION,
POSTGIS_PROJ_VERSION and POSTGIS_GEOS_VERSION variables have been set correctly.
PostGIS 3.3.2 Manual 21 / 902
Chapter 3
PostGIS Administration
Tuning for PostGIS performance is much like tuning for any PostgreSQL workload. The only additional consideration is that
geometries and rasters are usually large, so memory-related optimizations generally have more of an impact on PostGIS than
other types of PostgreSQL queries.
For general details about optimizing PostgreSQL, refer to Tuning your PostgreSQL Server.
For PostgreSQL 9.4+ configuration can be set at the server level without touching postgresql.conf or postgresql.auto.conf
by using the ALTER SYSTEM command.
ALTER SYSTEM SET work_mem = '256MB';
-- this forces non-startup configs to take effect for new connections
SELECT pg_reload_conf();
-- show current setting value
-- use SHOW ALL to see all settings
SHOW work_mem;
In addition to the Postgres settings, PostGIS has some custom settings which are listed in Section 8.23.
3.1.1 Startup
• Default: partition
• This is generally used for table partitioning. The default for this is set to "partition" which is ideal for PostgreSQL 8.4 and
above since it will force the planner to only analyze tables for constraint consideration if they are in an inherited hierarchy and
not pay the planner penalty otherwise.
shared_buffers
max_worker_processes This setting is only available for PostgreSQL 9.4+. For PostgreSQL 9.6+ this setting has additional
importance in that it controls the max number of processes you can have for parallel queries.
• Default: 8
• Sets the maximum number of background processes that the system can support. This parameter can only be set at server start.
PostGIS 3.3.2 Manual 22 / 902
3.1.2 Runtime
work_mem - sets the size of memory used for sort operations and complex queries
• Default: 1-4MB
• Adjust up for large dbs, complex queries, lots of RAM
• Adjust down for many concurrent users or low RAM.
maintenance_work_mem - the memory size used for VACUUM, CREATE INDEX, etc.
• Default: 16-64MB
• Generally too low - ties up I/O, locks objects while swapping memory
• Recommend 32MB to 1GB on production servers w/lots of RAM, but depends on the # of concurrent users. If you have lots
of RAM and few developers:
SET maintenance_work_mem TO '1GB';
max_parallel_workers_per_gather
This setting is only available for PostgreSQL 9.6+ and will only affect PostGIS 2.3+, since only PostGIS 2.3+ supports parallel
queries. If set to higher than 0, then some queries such as those involving relation functions like ST_Intersects can use
multiple processes and can run more than twice as fast when doing so. If you have a lot of processors to spare, you should change
the value of this to as many processors as you have. Also make sure to bump up max_worker_processes to at least as high
as this number.
• Default: 0
• Sets the maximum number of workers that can be started by a single Gather node. Parallel workers are taken from the pool
of processes established by max_worker_processes. Note that the requested number of workers may not actually be
available at run time. If this occurs, the plan will run with fewer workers than expected, which may be inefficient. Setting this
value to 0, which is the default, disables parallel query execution.
If you enabled raster support you may want to read below how to properly configure it.
As of PostGIS 2.1.3, out-of-db rasters and all raster drivers are disabled by default. In order to re-enable these, you need to set the
following environment variables POSTGIS_GDAL_ENABLED_DRIVERS and POSTGIS_ENABLE_OUTDB_RASTERS in the
server environment. For PostGIS 2.2, you can use the more cross-platform approach of setting the corresponding Section 8.23.
If you want to enable offline raster:
POSTGIS_ENABLE_OUTDB_RASTERS=1
If you want to only enable specific drivers, set your environment variable as follows:
POSTGIS_GDAL_ENABLED_DRIVERS="GTiff PNG JPEG GIF XYZ"
Note
If you are on windows, do not quote the driver list
Setting environment variables varies depending on OS. For PostgreSQL installed on Ubuntu or Debian via apt-postgresql, the
preferred way is to edit /etc/postgresql/10/main/environment where 10 refers to version of PostgreSQL and main
refers to the cluster.
On windows, if you are running as a service, you can set via System variables which for Windows 7 you can get to by right-
clicking on Computer->Properties Advanced System Settings or in explorer navigating to Control Panel\All Control
Panel Items\System. Then clicking Advanced System Settings ->Advanced->Environment Variables and adding new sys-
tem variables.
After you set the environment variables, you’ll need to restart your PostgreSQL service for the changes to take effect.
If you are using PostgreSQL 9.1+ and have compiled and installed the extensions/postgis modules, you can turn a database into
a spatial one using the EXTENSION mechanism.
Core postgis extension includes geometry, geography, spatial_ref_sys and all the functions and comments. Raster and topology
are packaged as a separate extension.
Run the following SQL snippet in the database you want to enable spatially:
CREATE EXTENSION IF NOT EXISTS plpgsql;
CREATE EXTENSION postgis;
CREATE EXTENSION postgis_raster; -- OPTIONAL
CREATE EXTENSION postgis_topology; -- OPTIONAL
Note
This is generally only needed if you cannot or don’t want to get PostGIS installed in the PostgreSQL extension directory
(for example during testing, development or in a restricted environment).
Adding PostGIS objects and function definitions into your database is done by loading the various sql files located in [prefix]
/share/contrib as specified during the build phase.
The core PostGIS objects (geometry and geography types, and their support functions) are in the postgis.sql script. Raster
objects are in the rtpostgis.sql script. Topology objects are in the topology.sql script.
For a complete set of EPSG coordinate system definition identifiers, you can also load the spatial_ref_sys.sql definitions
file and populate the spatial_ref_sys table. This will permit you to perform ST_Transform() operations on geometries.
If you wish to add comments to the PostGIS functions, you can find them in the postgis_comments.sql script. Comments
can be viewed by simply typing \dd [function_name] from a psql terminal window.
Run the following Shell commands in your terminal:
PostGIS 3.3.2 Manual 24 / 902
DB=[yourdatabase]
SCRIPTSDIR= `pg_config --sharedir`/contrib/postgis-3.2/
# Core objects
psql -d ${DB} -f ${SCRIPTSDIR}/postgis.sql
psql -d ${DB} -f ${SCRIPTSDIR}/spatial_ref_sys.sql
psql -d ${DB} -f ${SCRIPTSDIR}/postgis_comments.sql # OPTIONAL
Some packaged distributions of PostGIS (in particular the Win32 installers for PostGIS >= 1.1.5) load the PostGIS functions
into a template database called template_postgis. If the template_postgis database exists in your PostgreSQL
installation then it is possible for users and/or applications to create spatially-enabled databases using a single command. Note
that in both cases, the database user must have been granted the privilege to create new databases.
From the shell:
# createdb -T template_postgis my_spatial_db
From SQL:
postgres=# CREATE DATABASE my_spatial_db TEMPLATE=template_postgis
Upgrading existing spatial databases can be tricky as it requires replacement or introduction of new PostGIS object definitions.
Unfortunately not all definitions can be easily replaced in a live database, so sometimes your best bet is a dump/reload process.
PostGIS provides a SOFT UPGRADE procedure for minor or bugfix releases, and a HARD UPGRADE procedure for major
releases.
Before attempting to upgrade PostGIS, it is always worth to backup your data. If you use the -Fc flag to pg_dump you will
always be able to restore the dump with a HARD UPGRADE.
If you installed your database using extensions, you’ll need to upgrade using the extension model as well. If you installed using
the old sql script way, you are advised to switch your install to extensions because the script way is no longer supported.
If you originally installed PostGIS with extensions, then you need to upgrade using extensions as well. Doing a minor upgrade
with extensions, is fairly painless.
If you are running PostGIS 3 or above, then you should use the PostGIS_Extensions_Upgrade function to upgrade to the latest
version you have installed.
PostGIS 3.3.2 Manual 25 / 902
SELECT postgis_extensions_upgrade();
If you have multiple versions of PostGIS installed, and you don’t want to upgrade to the latest, you can explicitly specify the
version as follows:
ALTER EXTENSION postgis UPDATE TO "3.3.2";
ALTER EXTENSION postgis_topology UPDATE TO "3.3.2";
Then you’ll need to backup your database, create a fresh one as described in Section 3.3.1 and then restore your backup on top
of this new database.
If you get a notice message like:
Version "3.3.2" of extension "postgis" is already installed
Then everything is already up to date and you can safely ignore it. UNLESS you’re attempting to upgrade from an development
version to the next (which doesn’t get a new version number); in that case you can append "next" to the version string, and next
time you’ll need to drop the "next" suffix again:
ALTER EXTENSION postgis UPDATE TO "3.3.2next";
ALTER EXTENSION postgis_topology UPDATE TO "3.3.2next";
Note
If you installed PostGIS originally without a version specified, you can often skip the reinstallation of postgis extension
before restoring since the backup just has CREATE EXTENSION postgis and thus picks up the newest latest
version during restore.
Note
If you are upgrading PostGIS extension from a version prior to 3.0.0, you will have a new extension postgis_raster which
you can safely drop, if you don’t need raster support. You can drop as follows:
DROP EXTENSION postgis_raster;
This section applies only to those who installed PostGIS not using extensions. If you have extensions and try to upgrade with
this approach you’ll get messages like:
can't drop ... because postgis extension depends on it
NOTE: if you are moving from PostGIS 1.* to PostGIS 2.* or from PostGIS 2.* prior to r7409, you cannot use this procedure
but would rather need to do a HARD UPGRADE.
After compiling and installing (make install) you should find a set of *_upgrade.sql files in the installation folders. You can
list them all with:
PostGIS 3.3.2 Manual 26 / 902
ls `pg_config --sharedir`/contrib/postgis-3.3.2/*_upgrade.sql
The same procedure applies to raster, topology and sfcgal extensions, with upgrade files named rtpostgis_upgrade.sql,
topology_upgrade.sql and sfcgal_upgrade.sql respectively. If you need them:
psql -f rtpostgis_upgrade.sql -d your_spatial_database
Note
If you can’t find the postgis_upgrade.sql specific for upgrading your version you are using a version too early
for a soft upgrade and need to do a HARD UPGRADE.
The PostGIS_Full_Version function should inform you about the need to run this kind of upgrade using a "procs need upgrade"
message.
By HARD UPGRADE we mean full dump/reload of postgis-enabled databases. You need a HARD UPGRADE when PostGIS
objects’ internal storage changes or when SOFT UPGRADE is not possible. The Release Notes appendix reports for each version
whether you need a dump/reload (HARD UPGRADE) to upgrade.
The dump/reload process is assisted by the postgis_restore.pl script which takes care of skipping from the dump all definitions
which belong to PostGIS (including old ones), allowing you to restore your schemas and data into a database with PostGIS
installed without getting duplicate symbol errors or bringing forward deprecated objects.
Supplementary instructions for windows users are available at Windows Hard upgrade.
The Procedure is as follows:
1. Create a "custom-format" dump of the database you want to upgrade (let’s call it olddb) include binary blobs (-b) and
verbose (-v) output. The user can be the owner of the db, need not be postgres super account.
pg_dump -h localhost -p 5432 -U postgres -Fc -b -v -f "/somepath/olddb.backup" olddb
2. Do a fresh install of PostGIS in a new database -- we’ll refer to this database as newdb. Please refer to Section 3.3.2 and
Section 3.3.1 for instructions on how to do this.
The spatial_ref_sys entries found in your dump will be restored, but they will not override existing ones in spatial_ref_sys.
This is to ensure that fixes in the official set will be properly propagated to restored databases. If for any reason you really
want your own overrides of standard entries just don’t load the spatial_ref_sys.sql file when creating the new db.
If your database is really old or you know you’ve been using long deprecated functions in your views and functions, you
might need to load legacy.sql for all your functions and views etc. to properly come back. Only do this if _really_
needed. Consider upgrading your views and functions before dumping instead, if possible. The deprecated functions can
be later removed by loading uninstall_legacy.sql.
PostGIS 3.3.2 Manual 27 / 902
3. Restore your backup into your fresh newdb database using postgis_restore.pl. Unexpected errors, if any, will be printed
to the standard error stream by psql. Keep a log of those.
perl utils/postgis_restore.pl "/somepath/olddb.backup" | psql -h localhost -p 5432 -U ←-
postgres newdb 2> errors.txt
1. Some of your views or functions make use of deprecated PostGIS objects. In order to fix this you may try loading
legacy.sql script prior to restore or you’ll have to restore to a version of PostGIS which still contains those objects
and try a migration again after porting your code. If the legacy.sql way works for you, don’t forget to fix your code to
stop using deprecated functions and drop them loading uninstall_legacy.sql.
2. Some custom records of spatial_ref_sys in dump file have an invalid SRID value. Valid SRID values are bigger than 0 and
smaller than 999000. Values in the 999000.999999 range are reserved for internal use while values > 999999 can’t be used
at all. All your custom records with invalid SRIDs will be retained, with those > 999999 moved into the reserved range,
but the spatial_ref_sys table would lose a check constraint guarding for that invariant to hold and possibly also its primary
key ( when multiple invalid SRIDS get converted to the same reserved SRID value ).
In order to fix this you should copy your custom SRS to a SRID with a valid value (maybe in the 910000..910999 range),
convert all your tables to the new srid (see UpdateGeometrySRID), delete the invalid entry from spatial_ref_sys and re-
construct the check(s) with:
ALTER TABLE spatial_ref_sys ADD CONSTRAINT spatial_ref_sys_srid_check check (srid > 0 ←-
AND srid < 999000 );
If you are upgrading an old database containing french IGN cartography, you will have probably SRIDs out of range and
you will see, when importing your database, issues like this :
WARNING: SRID 310642222 converted to 999175 (in reserved zone)
In this case, you can try following steps : first throw out completely the IGN from the sql which is resulting from post-
gis_restore.pl. So, after having run :
perl utils/postgis_restore.pl "/somepath/olddb.backup" > olddb.sql
Create then your newdb, activate the required Postgis extensions, and insert properly the french system IGN with : this
script After these operations, import your data :
psql -h localhost -p 5432 -U postgres -d newdb -f olddb-without-IGN.sql 2> errors.txt
PostGIS 3.3.2 Manual 28 / 902
Chapter 4
Data Management
The Open Geospatial Consortium (OGC) developed the Simple Features Access standard (SFA) to provide a model for geospatial
data. It defines the fundamental spatial type of Geometry, along with operations which manipulate and transform geometry
values to perform spatial analysis tasks. PostGIS implements the OGC Geometry model as the PostgreSQL data types geometry
and geography.
Geometry is an abstract type. Geometry values belong to one of its concrete subtypes which represent various kinds and
dimensions of geometric shapes. These include the atomic types Point, LineString, LinearRing and Polygon, and the collection
types MultiPoint, MultiLineString, MultiPolygon and GeometryCollection. The Simple Features Access - Part 1: Common
architecture v1.2.1 adds subtypes for the structures PolyhedralSurface, Triangle and TIN.
Geometry models shapes in the 2-dimensional Cartesian plane. The PolyhedralSurface, Triangle, and TIN types can also repre-
sent shapes in 3-dimensional space. The size and location of shapes are specified by their coordinates. Each coordinate has a
X and Y ordinate value determining its location in the plane. Shapes are constructed from points or line segments, with points
specified by a single coordinate, and line segments by two coordinates.
Coordinates may contain optional Z and M ordinate values. The Z ordinate is often used to represent elevation. The M ordinate
contains a measure value, which may represent time or distance. If Z or M values are present in a geometry value, they must be
defined for each point in the geometry. If a geometry has Z or M ordinates the coordinate dimension is 3D; if it has both Z and
M the coordinate dimension is 4D.
Geometry values are associated with a spatial reference system indicating the coordinate system in which it is embedded. The
spatial reference system is identified by the geometry SRID number. The units of the X and Y axes are determined by the
spatial reference system. In planar reference systems the X and Y coordinates typically represent easting and northing, while in
geodetic systems they represent longitude and latitude. SRID 0 represents an infinite Cartesian plane with no units assigned to
its axes. See Section 4.5.
The geometry dimension is a property of geometry types. Point types have dimension 0, linear types have dimension 1, and
polygonal types have dimension 2. Collections have the dimension of the maximum element dimension.
A geometry value may be empty. Empty values contain no vertices (for atomic geometry types) or no elements (for collections).
An important property of geometry values is their spatial extent or bounding box, which the OGC model calls envelope. This is
the 2 or 3-dimensional box which encloses the coordinates of a geometry. It is an efficient way to represent a geometry’s extent
in coordinate space and to check whether two geometries interact.
The geometry model allows evaluating topological spatial relationships as described in Section 5.1.1. To support this the concepts
of interior, boundary and exterior are defined for each geometry type. Geometries are topologically closed, so they always
contain their boundary. The boundary is a geometry of dimension one less than that of the geometry itself.
PostGIS 3.3.2 Manual 29 / 902
The OGC geometry model defines validity rules for each geometry type. These rules ensure that geometry values represents
realistic situations (e.g. it is possible to specify a polygon with a hole lying outside the shell, but this makes no sense geometrically
and is thus invalid). PostGIS also allows storing and manipulating invalid geometry values. This allows detecting and fixing them
if needed. See Section 4.4
4.1.1.1 Point
4.1.1.2 LineString
A LineString is a 1-dimensional line formed by a contiguous sequence of line segments. Each line segment is defined by two
points, with the end point of one segment forming the start point of the next segment. An OGC-valid LineString has either zero
or two or more points, but PostGIS also allows single-point LineStrings. LineStrings may cross themselves (self-intersect). A
LineString is closed if the start and end points are the same. A LineString is simple if it does not self-intersect.
LINESTRING (1 2, 3 4, 5 6)
4.1.1.3 LinearRing
A LinearRing is a LineString which is both closed and simple. The first and last points must be equal, and the line must not
self-intersect.
LINEARRING (0 0 0, 4 0 0, 4 4 0, 0 4 0, 0 0 0)
4.1.1.4 Polygon
A Polygon is a 2-dimensional planar region, delimited by an exterior boundary (the shell) and zero or more interior boundaries
(holes). Each boundary is a LinearRing.
POLYGON ((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2 0,1 1 0))
4.1.1.5 MultiPoint
4.1.1.6 MultiLineString
4.1.1.7 MultiPolygon
A MultiPolygon is a collection of non-overlapping, non-adjacent Polygons. Polygons in the collection may touch only at a finite
number of points.
MULTIPOLYGON (((1 5, 5 5, 5 1, 1 1, 1 5)), ((6 5, 9 1, 6 1, 6 5)))
4.1.1.8 GeometryCollection
4.1.1.9 PolyhedralSurface
A PolyhedralSurface is a contiguous collection of patches or facets which share some edges. Each patch is a planar Polygon. If
the Polygon coordinates have Z ordinates then the surface is 3-dimensional.
POLYHEDRALSURFACE Z (
((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)),
((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)),
((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)),
((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)),
((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)),
((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )
4.1.1.10 Triangle
A Triangle is a polygon defined by three distinct non-collinear vertices. Because a Triangle is a polygon it is specified by four
coordinates, with the first and fourth being equal.
TRIANGLE ((0 0, 0 9, 9 0, 0 0))
4.1.1.11 TIN
The ISO/IEC 13249-3 SQL Multimedia - Spatial standard (SQL/MM) extends the OGC SFA to define Geometry subtypes con-
taining curves with circular arcs. The SQL/MM types support 3DM, 3DZ and 4D coordinates.
Note
All floating point comparisons within the SQL-MM implementation are performed to a specified tolerance, currently 1E-
8.
PostGIS 3.3.2 Manual 31 / 902
4.1.2.1 CircularString
CircularString is the basic curve type, similar to a LineString in the linear world. A single arc segment is specified by three
points: the start and end points (first and third) and some other point on the arc. To specify a closed circle the start and end points
are the same and the middle point is the opposite point on the circle diameter (which is the center of the arc). In a sequence of
arcs the end point of the previous arc is the start point of the next arc, just like the segments of a LineString. This means that a
CircularString must have an odd number of points greater than 1.
CIRCULARSTRING(0 0, 1 1, 1 0)
CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0)
4.1.2.2 CompoundCurve
A CompoundCurve is a single continuous curve that may contain both circular arc segments and linear segments. That means
that in addition to having well-formed components, the end point of every component (except the last) must be coincident with
the start point of the following component.
COMPOUNDCURVE( CIRCULARSTRING(0 0, 1 1, 1 0),(1 0, 0 1))
4.1.2.3 CurvePolygon
A CurvePolygon is like a polygon, with an outer ring and zero or more inner rings. The difference is that a ring can be a
CircularString or CompoundCurve as well as a LineString.
As of PostGIS 1.4 PostGIS supports compound curves in a curve polygon.
CURVEPOLYGON(
CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0),
(1 1, 3 3, 3 1, 1 1) )
Example: A CurvePolygon with the shell defined by a CompoundCurve containing a CircularString and a LineString, and a hole
defined by a CircularString
CURVEPOLYGON(
COMPOUNDCURVE( CIRCULARSTRING(0 0,2 0, 2 1, 2 3, 4 3),
(4 3, 4 5, 1 4, 0 0)),
CIRCULARSTRING(1.7 1, 1.4 0.4, 1.6 0.4, 1.6 0.5, 1.7 1) )
4.1.2.4 MultiCurve
4.1.2.5 MultiSurface
The OGC SFA specification defines two formats for representing geometry values for external use: Well-Known Text (WKT) and
Well-Known Binary (WKB). Both WKT and WKB include information about the type of the object and the coordinates which
define it.
Well-Known Text (WKT) provides a standard textual representation of spatial data. Examples of WKT representations of spatial
objects are:
• POINT(0 0)
• POINT Z (0 0 0)
• POINT ZM (0 0 0 0)
• POINT EMPTY
• LINESTRING(0 0,1 1,1 2)
• LINESTRING EMPTY
• POLYGON((0 0,4 0,4 4,0 4,0 0),(1 1, 2 1, 2 2, 1 2,1 1))
• MULTIPOINT((0 0),(1 2))
• MULTIPOINT Z ((0 0 0),(1 2 3))
• MULTIPOINT EMPTY
• MULTILINESTRING((0 0,1 1,1 2),(2 3,3 2,5 4))
• MULTIPOLYGON(((0 0,4 0,4 4,0 4,0 0),(1 1,2 1,2 2,1 2,1 1)), ((-1 -1,-1 -2,-2 -2,-2 -1,-1 -1)))
• GEOMETRYCOLLECTION(POINT(2 3),LINESTRING(2 3,3 4))
• GEOMETRYCOLLECTION EMPTY
Input and output of WKT is provided by the functions ST_AsText and ST_GeomFromText:
text WKT = ST_AsText(geometry);
geometry = ST_GeomFromText(text WKT, SRID);
For example, a statement to create and insert a spatial object from WKT and a SRID is:
INSERT INTO geotable ( geom, name )
VALUES ( ST_GeomFromText('POINT(-126.4 45.32)', 312), 'A Place');
Well-Known Binary (WKB) provides a portable, full-precision representation of spatial data as binary data (arrays of bytes).
Examples of the WKB representations of spatial objects are:
• WKT: POINT(1 1)
WKB: 0101000000000000000000F03F000000000000F03
• WKT: LINESTRING (2 2, 9 9)
WKB: 0102000000020000000000000000000040000000000000004000000000000022400000000000002240
Input and output of WKB is provided by the functions ST_AsBinary and ST_GeomFromWKB:
bytea WKB = ST_AsBinary(geometry);
geometry = ST_GeomFromWKB(bytea WKB, SRID);
For example, a statement to create and insert a spatial object from WKB is:
INSERT INTO geotable ( geom, name )
VALUES ( ST_GeomFromWKB('\x0101000000000000000000f03f000000000000f03f', 312), 'A Place');
PostGIS 3.3.2 Manual 33 / 902
PostGIS implements the OGC Simple Features model by defining a PostgreSQL data type called geometry. It represents all of
the geometry subtypes by using an internal type code (see GeometryType and ST_GeometryType). This allows modelling spatial
features as rows of tables defined with a column of type geometry.
The geometry data type is opaque, which means that all access is done via invoking functions on geometry values. Functions
allow creating geometry objects, accessing or updating all internal fields, and compute new geometry values. PostGIS supports
all the functions specified in the OGC Simple feature access - Part 2: SQL option (SFS) specification, as well many others. See
Chapter 8 for the full list of functions.
Note
PostGIS follows the SFA standard by prefixing spatial functions with "ST_". This was intended to stand for "Spatial and
Temporal", but the temporal part of the standard was never developed. Instead it can be interpreted as "Spatial Type".
The SFA standard specifies that spatial objects include a Spatial Reference System identifier (SRID). The SRID is required when
creating spatial objects for insertion into the database (it may be defaulted to 0). See ST_SRID and Section 4.5
To make querying geometry efficient PostGIS defines various kinds of spatial indexes, and spatial operators to use them. See
Section 4.9 and Section 5.2 for details.
OGC SFA specifications initially supported only 2D geometries, and the geometry SRID is not included in the input/output
representations. The OGC SFA specification 1.2.1 (which aligns with the ISO 19125 standard) adds support for 3D (ZYZ) and
measured (XYM and XYZM) coordinates, but still does not include the SRID value.
Because of these limitations PostGIS defined extended EWKB and EWKT formats. They provide 3D (XYZ and XYM) and 4D
(XYZM) coordinate support and include SRID information. Including all geometry information allows PostGIS to use EWKB
as the format of record (e.g. in DUMP files).
EWKB and EWKT are used for the "canonical forms" of PostGIS data objects. For input, the canonical form for binary data is
EWKB, and for text data either EWKB or EWKT is accepted. This allows geometry values to be created by casting a text value
in either HEXEWKB or EWKT to a geometry value using ::geometry. For output, the canonical form for binary is EWKB,
and for text it is HEXEWKB (hex-encoded EWKB).
For example this statement creates a geometry by casting from an EWKT text value, and outputs it using the canonical form of
HEXEWKB:
SELECT 'SRID=4;POINT(0 0)'::geometry;
geometry
----------------------------------------------------
01010000200400000000000000000000000000000000000000
EWKT avoids over-specifying dimensionality and the inconsistencies that can occur with the OGC/ISO format, such as:
• POINT ZM (1 1)
• POINT ZM (1 1 1)
• POINT (1 1 1 1)
Caution
PostGIS extended formats are currently a superset of the OGC ones, so that every valid OGC WKB/WKT is also valid
EWKB/EWKT. However, this might vary in the future, if the OGC extends a format in a way that conflicts with the PosGIS
definition. Thus you SHOULD NOT rely on this compatibility!
• POINT(0 0 0) -- XYZ
• SRID=32632;POINT(0 0) -- XY with SRID
• POINTM(0 0 0) -- XYM
• POINT(0 0 0 0) -- XYZM
• MULTIPOLYGON(((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2 0,1 1 0)),((-1 -1 0,-1 -2 0,-2 -2 0,-2 -1 0,-1 -1 0)))
• GEOMETRYCOLLECTIONM( POINTM(2 3 9), LINESTRINGM(2 3 4, 3 4 5) )
• MULTICURVE( (0 0, 5 5), CIRCULARSTRING(4 0, 4 4, 8 4) )
• POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0
0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )
• TRIANGLE ((0 0, 0 10, 10 0, 0 0))
• TIN( ((0 0 0, 0 0 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 0 0 0)) )
Input and output using these formats is available using the following functions:
bytea EWKB = ST_AsEWKB(geometry);
text EWKT = ST_AsEWKT(geometry);
geometry = ST_GeomFromEWKB(bytea EWKB);
geometry = ST_GeomFromEWKT(text EWKT);
For example, a statement to create and insert a PostGIS spatial object using EWKT is:
INSERT INTO geotable ( geom, name )
VALUES ( ST_GeomFromEWKT('SRID=312;POINTM(-126.4 45.32 15)'), 'A Place' )
PostGIS 3.3.2 Manual 35 / 902
The PostGIS geography data type provides native support for spatial features represented on "geographic" coordinates (some-
times called "geodetic" coordinates, or "lat/lon", or "lon/lat"). Geographic coordinates are spherical coordinates expressed in
angular units (degrees).
The basis for the PostGIS geometry data type is a plane. The shortest path between two points on the plane is a straight line.
That means functions on geometries (areas, distances, lengths, intersections, etc) are calculated using straight line vectors and
cartesian mathematics. This makes them simpler to implement and faster to execute, but also makes them inaccurate for data on
the spheroidal surface of the earth.
The PostGIS geography data type is based on a spherical model. The shortest path between two points on the sphere is a great
circle arc. Functions on geographies (areas, distances, lengths, intersections, etc) are calculated using arcs on the sphere. By
taking the spheroidal shape of the world into account, the functions provide more accurate results.
Because the underlying mathematics is more complicated, there are fewer functions defined for the geography type than for the
geometry type. Over time, as new algorithms are added the capabilities of the geography type will expand. As a workaround one
can convert back and forth between geometry and geography types.
Like the geometry data type, geography data is associated with a spatial reference system via a spatial reference system identifier
(SRID). Any geodetic (long/lat based) spatial reference system defined in the spatial_ref_sys table can be used. (Prior to
PostGIS 2.2, the geography type supported only WGS 84 geodetic (SRID:4326)). You can add your own custom geodetic spatial
reference system as described in Section 4.5.2.
For all spatial reference systems the units returned by measurement functions (e.g. ST_Distance, ST_Length, ST_Perimeter,
ST_Area) and for the distance argument of ST_DWithin are in meters.
You can create a table to store geography data using the CREATE TABLE SQL statement with a column of type geography.
The following example creates a table with a geography column storing 2D LineStrings in the WGS84 geodetic coordinate
system (SRID 4326):
CREATE TABLE global_points (
id SERIAL PRIMARY KEY,
name VARCHAR(64),
location geography(POINT,4326)
);
• the spatial type modifier restricts the kind of shapes and dimensions allowed in the column. Values allowed for the spatial type
are: POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, GEOMETRYCOLLEC-
TION. The geography type does not support curves, TINS, or POLYHEDRALSURFACEs. The modifier supports coordinate
dimensionality restrictions by adding suffixes: Z, M and ZM. For example, a modifier of ’LINESTRINGM’ only allows
linestrings with three dimensions, and treats the third dimension as a measure. Similarly, ’POINTZM’ requires four dimen-
sional (XYZM) data.
• the SRID modifier restricts the spatial reference system SRID to a particular number. If omitted, the SRID defaults to 4326
(WGS84 geodetic), and all calculations are performed using WGS84.
• Create a table with 2D POINT geography with the default SRID 4326 (WGS84 long/lat):
CREATE TABLE ptgeogwgs(gid serial PRIMARY KEY, geog geography(POINT) );
• Create a table with 2D LINESTRING geography with the default SRID 4326:
CREATE TABLE lgeog(gid serial PRIMARY KEY, geog geography(LINESTRING) );
• Create a table with 2D POLYGON geography with the SRID 4267 (NAD 1927 long lat):
CREATE TABLE lgeognad27(gid serial PRIMARY KEY, geog geography(POLYGON,4267) );
Geography fields are registered in the geography_columns system view. You can query the geography_columns view
and see that the table is listed:
SELECT * FROM geography_columns;
Creating a spatial index works the same as for geometry columns. PostGIS will note that the column type is GEOGRAPHY and
create an appropriate sphere-based index instead of the usual planar index used for GEOMETRY.
-- Index the test table with a spherical index
CREATE INDEX global_points_gix ON global_points USING GIST ( location );
You can insert data into geography tables in the same way as geometry. Geometry data will autocast to the geography type if it
has SRID 4326. The EWKT and EWKB formats can also be used to specify geography values.
-- Add some data into the test table
INSERT INTO global_points (name, location) VALUES ('Town', 'SRID=4326;POINT(-110 30)');
INSERT INTO global_points (name, location) VALUES ('Forest', 'SRID=4326;POINT(-109 29)');
INSERT INTO global_points (name, location) VALUES ('London', 'SRID=4326;POINT(0 49)');
Any geodetic (long/lat) spatial reference system listed in spatial_ref_sys table may be specified as a geography SRID.
Non-geodetic coordinate systems raise an error if used.
-- NAD 83 lon/lat
SELECT 'SRID=4269;POINT(-123 34)'::geography;
geography
----------------------------------------------------
0101000020AD1000000000000000C05EC00000000000004140
-- NAD27 lon/lat
SELECT 'SRID=4267;POINT(-123 34)'::geography;
geography
----------------------------------------------------
0101000020AB1000000000000000C05EC00000000000004140
-- NAD83 UTM zone meters - gives an error since it is a meter-based planar projection
SELECT 'SRID=26910;POINT(-123 34)'::geography;
Query and measurement functions use units of meters. So distance parameters should be expressed in meters, and return values
should be expected in meters (or square meters for areas).
PostGIS 3.3.2 Manual 37 / 902
You can see the power of geography in action by calculating how close a plane flying a great circle route from Seattle to London
(LINESTRING(-122.33 47.606, 0.0 51.5)) comes to Reykjavik (POINT(-21.96 64.15)) (map the route).
The geography type calculates the true shortest distance of 122.235 km over the sphere between Reykjavik and the great circle
flight path between Seattle and London.
-- Distance calculation using GEOGRAPHY
SELECT ST_Distance('LINESTRING(-122.33 47.606, 0.0 51.5)'::geography, 'POINT(-21.96 64.15) ←-
'::geography);
st_distance
-----------------
122235.23815667
The geometry type calculates a meaningless cartesian distance between Reykjavik and the straight line path from Seattle to
London plotted on a flat map of the world. The nominal units of the result is "degrees", but the result doesn’t correspond to any
true angular difference between the points, so even calling them "degrees" is inaccurate.
-- Distance calculation using GEOMETRY
SELECT ST_Distance('LINESTRING(-122.33 47.606, 0.0 51.5)'::geometry, 'POINT(-21.96 64.15) ←-
'::geometry);
st_distance
--------------------
13.342271221453624
The geography data type allows you to store data in longitude/latitude coordinates, but at a cost: there are fewer functions defined
on GEOGRAPHY than there are on GEOMETRY; those functions that are defined take more CPU time to execute.
The data type you choose should be determined by the expected working area of the application you are building. Will your data
span the globe or a large continental area, or is it local to a state, county or municipality?
• If your data is contained in a small area, you might find that choosing an appropriate projection and using GEOMETRY is the
best solution, in terms of performance and functionality available.
• If your data is global or covers a continental region, you may find that GEOGRAPHY allows you to build a system without
having to worry about projection details. You store your data in longitude/latitude, and use the functions that have been defined
on GEOGRAPHY.
• If you don’t understand projections, and you don’t want to learn about them, and you’re prepared to accept the limitations in
functionality available in GEOGRAPHY, then it might be easier for you to use GEOGRAPHY than GEOMETRY. Simply load
your data up as longitude/latitude and go from there.
Refer to Section 15.11 for compare between what is supported for Geography vs. Geometry. For a brief listing and description
of Geography functions, refer to Section 15.4
4. Why is it so slow to calculate the area of Europe / Russia / insert big geographic region here ?
Because the polygon is so darned huge! Big areas are bad for two reasons: their bounds are huge, so the index tends to pull
the feature no matter what query you run; the number of vertices is huge, and tests (distance, containment) have to traverse
the vertex list at least once and sometimes N times (with N being the number of vertices in the other candidate feature).
As with GEOMETRY, we recommend that when you have very large polygons, but are doing queries in small areas, you
"denormalize" your geometric data into smaller chunks so that the index can effectively subquery parts of the object and
so queries don’t have to pull out the whole object every time. Please consult ST_Subdivide function documentation. Just
because you *can* store all of Europe in one polygon doesn’t mean you *should*.
PostGIS is compliant with the Open Geospatial Consortium’s (OGC) Simple Features specification. That standard defines the
concepts of geometry being simple and valid. These definitions allow the Simple Features geometry model to represent spatial
objects in a consistent and unambiguous way that supports efficient computation. (Note: the OGC SF and SQL/MM have the
same definitions for simple and valid.)
A simple geometry is one that has no anomalous geometric points, such as self intersection or self tangency.
A POINT is inherently simple as a 0-dimensional geometry object.
MULTIPOINTs are simple if no two coordinates (POINTs) are equal (have identical coordinate values).
A LINESTRING is simple if it does not pass through the same point twice, except for the endpoints. If the endpoints of a simple
LineString are identical it is called closed and referred to as a Linear Ring.
(a) and (c) are simple LINESTRINGs. (b) and (d) are not simple. (c) is a closed Linear Ring.
PostGIS 3.3.2 Manual 39 / 902
(a) (b)
(c) (d)
A MULTILINESTRING is simple only if all of its elements are simple and the only intersection between any two elements
occurs at points that are on the boundaries of both elements.
POLYGONs are formed from linear rings, so valid polygonal geometry is always simple.
To test if a geometry is simple use the ST_IsSimple function:
SELECT
ST_IsSimple('LINESTRING(0 0, 100 100)') AS straight,
ST_IsSimple('LINESTRING(0 0, 100 100, 100 0, 0 100)') AS crossing;
straight | crossing
----------+----------
t | f
Generally, PostGIS functions do not require geometric arguments to be simple. Simplicity is primarily used as a basis for defining
geometric validity. It is also a requirement for some kinds of spatial data models (for example, linear networks often disallow
lines that cross). Multipoint and linear geometry can be made simple using ST_UnaryUnion.
Geometry validity primarily applies to 2-dimensional geometries (POLYGONs and MULTIPOLYGONs) . Validity is defined by
rules that allow polygonal geometry to model planar areas unambiguously.
A POLYGON is valid if:
1. the polygon boundary rings (the exterior shell ring and interior hole rings) are simple (do not cross or self-touch). Because
of this a polygon cannnot have cut lines, spikes or loops. This implies that polygon holes must be represented as interior
rings, rather than by the exterior ring self-touching (a so-called "inverted hole").
2. boundary rings do not cross
3. boundary rings may touch at points but only as a tangent (i.e. not in a line)
(h) and (i) are valid POLYGONs. (j-m) are invalid. (j) can be represented as a valid MULTIPOLYGON.
PostGIS 3.3.2 Manual 41 / 902
PostGIS allows creating and storing both valid and invalid Geometry. This allows invalid geometry to be detected and flagged or
fixed. There are also situations where the OGC validity rules are stricter than desired (examples of this are zero-length linestrings
and polygons with inverted holes.)
Many of the functions provided by PostGIS rely on the assumption that geometry arguments are valid. For example, it does not
make sense to calculate the area of a polygon that has a hole defined outside of the polygon, or to construct a polygon from a
non-simple boundary line. Assuming valid geometric inputs allows functions to operate more efficiently, since they do not need
to check for topological correctness. (Notable exceptions are that zero-length lines and polygons with inversions are generally
handled correctly.) Also, most PostGIS functions produce valid geometry output if the inputs are valid. This allows PostGIS
functions to be chained together safely.
If you encounter unexpected error messages when calling PostGIS functions (such as "GEOS Intersection() threw an error!"),
you should first confirm that the function arguments are valid. If they are not, then consider using one of the techniques below to
ensure the data you are processing is valid.
Note
If a function reports an error with valid inputs, then you may have found an error in either PostGIS or one of the libraries
it uses, and you should report this to the PostGIS project. The same is true if a PostGIS function returns an invalid
geometry for valid input.
SELECT ST_IsValid('POLYGON ((20 180, 180 180, 180 20, 20 20, 20 180))');
-----------------
t
Information about the nature and location of an geometry invalidity are provided by the ST_IsValidDetail function:
SELECT valid, reason, ST_AsText(location) AS location
FROM ST_IsValidDetail('POLYGON ((20 20, 120 190, 50 190, 170 50, 20 20))') AS t;
In some situations it is desirable to correct invalid geometry automatically. Use the ST_MakeValid function to do this. (ST_MakeValid
is a case of a spatial function that does allow invalid input!)
By default, PostGIS does not check for validity when loading geometry, because validity testing can take a lot of CPU time for
complex geometries. If you do not trust your data sources, you can enforce a validity check on your tables by adding a check
constraint:
ALTER TABLE mytable
ADD CONSTRAINT geometry_valid_check
CHECK (ST_IsValid(geom));
A Spatial Reference System (SRS) (also called a Coordinate Reference System (CRS)) defines how geometry is referenced to
locations on the Earth’s surface. There are three types of SRS:
• A geodetic SRS uses angular coordinates (longitude and latitude) which map directly to the surface of the earth.
• A projected SRS uses a mathematical projection transformation to "flatten" the surface of the spheroidal earth onto a plane.
It assigns location coordinates in a way that allows direct measurement of quantities such as distance, area, and angle. The
coordinate system is Cartesian, which means it has a defined origin point and two perpendicular axes (usually oriented North
and East). Each projected SRS uses a stated length unit (usually metres or feet). A projected SRS may be limited in its area of
applicability to avoid distortion and fit within the defined coordinate bounds.
• A local SRS is a Cartesian coordinate system which is not referenced to the earth’s surface. In PostGIS this is specified by a
SRID value of 0.
There are many different spatial reference systems in use. Common SRSes are standardized in the European Petroleum Survey
Group EPSG database. For convenience PostGIS (and many other spatial systems) refers to SRS definitions using an integer
identifier called a SRID.
A geometry is associated with a Spatial Reference System by its SRID value, which is accessed by ST_SRID. The SRID for a
geometry can be assigned using ST_SetSRID. Some geometry constructor functions allow supplying a SRID (such as ST_Point
and ST_MakeEnvelope). The EWKT format supports SRIDs with the SRID=n; prefix.
Spatial functions processing pairs of geometries (such as overlay and relationship functions) require that the input geometries are
in the same spatial reference system (have the same SRID). Geometry data can be transformed into a different spatial reference
system using ST_Transform. Geometry returned from functions has the same SRS as the input geometries.
The SPATIAL_REF_SYS table used by PostGIS is an OGC-compliant database table that defines the available spatial reference
systems. It holds the numeric SRIDs and textual descriptions of the coordinate systems.
The spatial_ref_sys table definition is:
PostGIS 3.3.2 Manual 44 / 902
srid An integer code that uniquely identifies the Spatial Reference System (SRS) within the database.
auth_name The name of the standard or standards body that is being cited for this reference system. For example, "EPSG" is a
valid auth_name.
auth_srid The ID of the Spatial Reference System as defined by the Authority cited in the auth_name. In the case of EPSG,
this is the EPSG code.
srtext The Well-Known Text representation of the Spatial Reference System. An example of a WKT SRS representation is:
PROJCS["NAD83 / UTM Zone 10N",
GEOGCS["NAD83",
DATUM["North_American_Datum_1983",
SPHEROID["GRS 1980",6378137,298.257222101]
],
PRIMEM["Greenwich",0],
UNIT["degree",0.0174532925199433]
],
PROJECTION["Transverse_Mercator"],
PARAMETER["latitude_of_origin",0],
PARAMETER["central_meridian",-123],
PARAMETER["scale_factor",0.9996],
PARAMETER["false_easting",500000],
PARAMETER["false_northing",0],
UNIT["metre",1]
]
For a discussion of SRS WKT, see the OGC standard Well-known text representation of coordinate reference systems.
proj4text PostGIS uses the PROJ library to provide coordinate transformation capabilities. The proj4text column contains
the PROJ coordinate definition string for a particular SRID. For example:
+proj=utm +zone=10 +ellps=clrk66 +datum=NAD27 +units=m
For more information see the PROJ web site. The spatial_ref_sys.sql file contains both srtext and proj4text
definitions for all EPSG projections.
When retrieving spatial reference system definitions for use in transformations, PostGIS uses fhe following strategy:
• If auth_name and auth_srid are present (non-NULL) use the PROJ SRS based on those entries (if one exists).
• If srtext is present create a SRS using it, if possible.
• If proj4text is present create a SRS using it, if possible.
PostGIS 3.3.2 Manual 45 / 902
The PostGIS spatial_ref_sys table contains over 3000 of the most common spatial reference system definitions that are
handled by the PROJ projection library. But there are many coordinate systems that it does not contain. You can add SRS
definitions to the table if you have the required information about the spatial reference system. Or, you can define your own
custom spatial reference system if you are familiar with PROJ constructs. Keep in mind that most spatial reference systems are
regional and have no meaning when used outside of the bounds they were intended for.
A resource for finding spatial reference systems not defined in the core set is http://spatialreference.org/
Some commonly used spatial reference systems are: 4326 - WGS 84 Long Lat, 4269 - NAD 83 Long Lat, 3395 - WGS 84 World
Mercator, 2163 - US National Atlas Equal Area, and the 60 WGS84 UTM zones. UTM zones are one of the most ideal for
measurement, but only cover 6-degree regions. (To determine which UTM zone to use for your area of interest, see the utmzone
PostGIS plpgsql helper function.)
US states use State Plane spatial reference systems (meter or feet based) - usually one or 2 exists per state. Most of the meter-based
ones are in the core set, but many of the feet-based ones or ESRI-created ones will need to be copied from spatialreference.org.
You can even define non-Earth-based coordinate systems, such as Mars 2000 This Mars coordinate system is non-planar (it’s in
degrees spheroidal), but you can use it with the geography type to obtain length and proximity measurements in meters instead
of degrees.
Here is an example of loading a custom coordinate system using an unassigned SRID and the PROJ definition for a US-centric
Lambert Conformal projection:
INSERT INTO spatial_ref_sys (srid, proj4text)
VALUES ( 990000,
'+proj=lcc +lon_0=-95 +lat_0=25 +lat_1=25 +lat_2=25 +x_0=0 +y_0=0 +datum=WGS84 +units=m ←-
+no_defs'
);
You can create a table to store geometry data using the CREATE TABLE SQL statement with a column of type geometry.
The following example creates a table with a geometry column storing 2D (XY) LineStrings in the BC-Albers coordinate system
(SRID 3005):
CREATE TABLE roads (
id SERIAL PRIMARY KEY,
name VARCHAR(64),
geom geometry(LINESTRING,3005)
);
• the spatial type modifier restricts the kind of shapes and dimensions allowed in the column. The value can be any of the
supported geometry subtypes (e.g. POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLY-
GON, GEOMETRYCOLLECTION, etc). The modifier supports coordinate dimensionality restrictions by adding suffixes: Z,
M and ZM. For example, a modifier of ’LINESTRINGM’ allows only linestrings with three dimensions, and treats the third
dimension as a measure. Similarly, ’POINTZM’ requires four dimensional (XYZM) data.
• the SRID modifier restricts the spatial reference system SRID to a particular number. If omitted, the SRID defaults to 0.
• Create a table holding any kind of geometry with the default SRID:
PostGIS 3.3.2 Manual 46 / 902
• Create a table with 4D (XYZM) LINESTRING geometry with the default SRID:
CREATE TABLE lines(gid serial PRIMARY KEY, geom geometry(LINESTRINGZM) );
• Create a table with 2D POLYGON geometry with the SRID 4267 (NAD 1927 long lat):
CREATE TABLE polys(gid serial PRIMARY KEY, geom geometry(POLYGON,4267) );
It is possible to have more than one geometry column in a table. This can be specified when the table is created, or a column can
be added using the ALTER TABLE SQL statement. This example adds a column that can hold 3D LineStrings:
ALTER TABLE roads ADD COLUMN geom2 geometry(LINESTRINGZ,4326);
The OGC Simple Features Specification for SQL defines the GEOMETRY_COLUMNS metadata table to describe geometry table
structure. In PostGIS geometry_columns is a view reading from database system catalog tables. This ensures that the spatial
metadata information is always consistent with the currently defined tables and views. The view structure is:
\d geometry_columns
View "public.geometry_columns"
Column | Type | Modifiers
-------------------+------------------------+-----------
f_table_catalog | character varying(256) |
f_table_schema | character varying(256) |
f_table_name | character varying(256) |
f_geometry_column | character varying(256) |
coord_dimension | integer |
srid | integer |
type | character varying(30) |
f_table_catalog, f_table_schema, f_table_name The fully qualified name of the feature table containing the geometry column.
There is no PostgreSQL analogue of "catalog" so that column is left blank. For "schema" the PostgreSQL schema name is
used (public is the default).
f_geometry_column The name of the geometry column in the feature table.
coord_dimension The coordinate dimension (2, 3 or 4) of the column.
srid The ID of the spatial reference system used for the coordinate geometry in this table. It is a foreign key reference to the
spatial_ref_sys table (see Section 4.5.1).
type The type of the spatial object. To restrict the spatial column to a single type, use one of: POINT, LINESTRING, POLY-
GON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, GEOMETRYCOLLECTION or corresponding XYM
versions POINTM, LINESTRINGM, POLYGONM, MULTIPOINTM, MULTILINESTRINGM, MULTIPOLYGONM,
GEOMETRYCOLLECTIONM. For heterogeneous (mixed-type) collections, you can use "GEOMETRY" as the type.
PostGIS 3.3.2 Manual 47 / 902
Two of the cases where you may need this are the case of SQL Views and bulk inserts. For bulk insert case, you can correct
the registration in the geometry_columns table by constraining the column or doing an alter table. For views, you could expose
using a CAST operation. Note, if your column is typmod based, the creation process would register it correctly, so no need to do
anything. Also views that have no spatial function applied to the geometry will register the same as the underlying table geometry
column.
-- Lets say you have a view created like this
CREATE VIEW public.vwmytablemercator AS
SELECT gid, ST_Transform(geom, 3395) As geom, f_name
FROM public.mytable;
-- If you know the geometry type for sure is a 2D POLYGON then you could do
DROP VIEW public.vwmytablemercator;
CREATE VIEW public.vwmytablemercator AS
SELECT gid, ST_Transform(geom,3395)::geometry(Polygon, 3395) As geom, f_name
FROM public.mytable;
-- If you are using PostGIS 2.0 and for whatever reason, you
-- you need the constraint based definition behavior
-- (such as case of inherited tables where all children do not have the same type and srid)
-- set optional use_typmod argument to false
SELECT populate_geometry_columns('myschema.my_special_pois'::regclass, false);
Although the old-constraint based method is still supported, a constraint-based geometry column used directly in a view, will not
register correctly in geometry_columns, as will a typmod one. In this example we define a column using typmod and another
using constraints.
CREATE TABLE pois_ny(gid SERIAL PRIMARY KEY, poi_name text, cat text, geom geometry(POINT ←-
,4326));
SELECT AddGeometryColumn('pois_ny', 'geom_2160', 2160, 'POINT', 2, false);
If we run in psql
PostGIS 3.3.2 Manual 48 / 902
\d pois_ny;
-----------+-----------------------+------------------------------------------------------
gid | integer | not null default nextval('pois_ny_gid_seq'::regclass)
poi_name | text |
cat | character varying(20) |
geom | geometry(Point,4326) |
geom_2160 | geometry |
Indexes:
"pois_ny_pkey" PRIMARY KEY, btree (gid)
Check constraints:
"enforce_dims_geom_2160" CHECK (st_ndims(geom_2160) = 2)
"enforce_geotype_geom_2160" CHECK (geometrytype(geom_2160) = 'POINT'::text
OR geom_2160 IS NULL)
"enforce_srid_geom_2160" CHECK (st_srid(geom_2160) = 2160)
The typmod based geom view column registers correctly, but the constraint based one does not.
f_table_name | f_geometry_column | srid | type
------------------+-------------------+------+----------
vw_pois_ny_parks | geom | 4326 | POINT
vw_pois_ny_parks | geom_2160 | 0 | GEOMETRY
This may change in future versions of PostGIS, but for now to force the constraint-based view column to register correctly, you
need to do this:
DROP VIEW vw_pois_ny_parks;
CREATE VIEW vw_pois_ny_parks AS
SELECT gid, poi_name, cat,
geom,
geom_2160::geometry(POINT,2160) As geom_2160
FROM pois_ny
WHERE cat = 'park';
SELECT f_table_name, f_geometry_column, srid, type
PostGIS 3.3.2 Manual 49 / 902
FROM geometry_columns
WHERE f_table_name = 'vw_pois_ny_parks';
Once you have created a spatial table, you are ready to upload spatial data to the database. There are two built-in ways to get
spatial data into a PostGIS/PostgreSQL database: using formatted SQL statements or using the Shapefile loader.
If spatial data can be converted to a text representation (as either WKT or WKB), then using SQL might be the easiest way to get
data into PostGIS. Data can be bulk-loaded into PostGIS/PostgreSQL by loading a text file of SQL INSERT statements using
the psql SQL utility.
A SQL load file (roads.sql for example) might look like this:
BEGIN;
INSERT INTO roads (road_id, roads_geom, road_name)
VALUES (1,'LINESTRING(191232 243118,191108 243242)','Jeff Rd');
INSERT INTO roads (road_id, roads_geom, road_name)
VALUES (2,'LINESTRING(189141 244158,189265 244817)','Geordie Rd');
INSERT INTO roads (road_id, roads_geom, road_name)
VALUES (3,'LINESTRING(192783 228138,192612 229814)','Paul St');
INSERT INTO roads (road_id, roads_geom, road_name)
VALUES (4,'LINESTRING(189412 252431,189631 259122)','Graeme Ave');
INSERT INTO roads (road_id, roads_geom, road_name)
VALUES (5,'LINESTRING(190131 224148,190871 228134)','Phil Tce');
INSERT INTO roads (road_id, roads_geom, road_name)
VALUES (6,'LINESTRING(198231 263418,198213 268322)','Dave Cres');
COMMIT;
The shp2pgsql data loader converts Shapefiles into SQL suitable for insertion into a PostGIS/PostgreSQL database either in
geometry or geography format. The loader has several operating modes selected by command line flags.
There is also a shp2pgsql-gui graphical interface with most of the options as the command-line loader. This may be easier
to use for one-off non-scripted loading or if you are new to PostGIS. It can also be configured as a plugin to PgAdminIII.
-c Creates a new table and populates it from the Shapefile. This is the default mode.
-a Appends data from the Shapefile into the database table. Note that to use this option to load multiple files, the files
must have the same attributes and same data types.
-d Drops the database table before creating a new table with the data in the Shapefile.
PostGIS 3.3.2 Manual 50 / 902
-p Only produces the table creation SQL code, without adding any actual data. This can be used if you need to completely
separate the table creation and data loading steps.
-? Display help screen.
-D Use the PostgreSQL "dump" format for the output data. This can be combined with -a, -c and -d. It is much faster to load
than the default "insert" SQL format. Use this for very large data sets.
-s [<FROM_SRID>:]<SRID> Creates and populates the geometry tables with the specified SRID. Optionally specifies that the
input shapefile uses the given FROM_SRID, in which case the geometries will be reprojected to the target SRID.
-k Keep identifiers’ case (column, schema and attributes). Note that attributes in Shapefile are all UPPERCASE.
-i Coerce all integers to standard 32-bit integers, do not create 64-bit bigints, even if the DBF header signature appears to warrant
it.
-I Create a GiST index on the geometry column.
-m -m a_file_name Specify a file containing a set of mappings of (long) column names to 10 character DBF column names.
The content of the file is one or more lines of two names separated by white space and no trailing or leading space. For
example:
COLUMNNAME DBFFIELD1
AVERYLONGCOLUMNNAME DBFFIELD2
-S Generate simple geometries instead of MULTI geometries. Will only succeed if all the geometries are actually single (I.E. a
MULTIPOLYGON with a single shell, or or a MULTIPOINT with a single vertex).
-t <dimensionality> Force the output geometry to have the specified dimensionality. Use the following strings to indicate the
dimensionality: 2D, 3DZ, 3DM, 4D.
If the input has fewer dimensions that specified, the output will have those dimensions filled in with zeroes. If the input
has more dimensions that specified, the unwanted dimensions will be stripped.
-w Output WKT format, instead of WKB. Note that this can introduce coordinate drifts due to loss of precision.
-e Execute each statement on its own, without using a transaction. This allows loading of the majority of good data when there
are some bad geometries that generate errors. Note that this cannot be used with the -D flag as the "dump" format always
uses a transaction.
-W <encoding> Specify encoding of the input data (dbf file). When used, all attributes of the dbf are converted from the
specified encoding to UTF8. The resulting SQL output will contain a SET CLIENT_ENCODING to UTF8 command,
so that the backend will be able to reconvert from UTF8 to whatever encoding the database is configured to use internally.
-N <policy> NULL geometries handling policy (insert*,skip,abort)
-n -n Only import DBF file. If your data has no corresponding shapefile, it will automatically switch to this mode and load just
the dbf. So setting this flag is only needed if you have a full shapefile set, and you only want the attribute data and no
geometry.
-G Use geography type instead of geometry (requires lon/lat data) in WGS84 long lat (SRID=4326)
-T <tablespace> Specify the tablespace for the new table. Indexes will still use the default tablespace unless the -X parameter
is also used. The PostgreSQL documentation has a good description on when to use custom tablespaces.
-X <tablespace> Specify the tablespace for the new table’s indexes. This applies to the primary key index, and the GIST spatial
index if -I is also used.
-Z When used, this flag will prevent the generation of ANALYZE statements. Without the -Z flag (default behavior), the
ANALYZE statements will be generated.
An example session using the loader to create an input file and loading it might look like this:
PostGIS 3.3.2 Manual 51 / 902
A conversion and load can be done in one step using UNIX pipes:
# shp2pgsql shaperoads.shp myschema.roadstable | psql -d roadsdb
Spatial data can be extracted from the database using either SQL or the Shapefile dumper. The section on SQL presents some of
the functions available to do comparisons and queries on spatial tables.
The most straightforward way of extracting spatial data out of the database is to use a SQL SELECT query to define the data set
to be extracted and dump the resulting columns into a parsable text file:
db=# SELECT road_id, ST_AsText(road_geom) AS geom, road_name FROM roads;
There will be times when some kind of restriction is necessary to cut down the number of records returned. In the case of
attribute-based restrictions, use the same SQL syntax as used with a non-spatial table. In the case of spatial restrictions, the
following functions are useful:
ST_Intersects This function tells whether two geometries share any space.
= This tests whether two geometries are geometrically identical. For example, if ’POLYGON((0 0,1 1,1 0,0 0))’ is the same as
’POLYGON((0 0,1 1,1 0,0 0))’ (it is).
Next, you can use these operators in queries. Note that when specifying geometries and boxes on the SQL command line, you
must explicitly turn the string representations into geometries function. The 312 is a fictitious spatial reference system that
matches our data. So, for example:
SELECT road_id, road_name
FROM roads
WHERE roads_geom='SRID=312;LINESTRING(191232 243118,191108 243242)'::geometry;
The above query would return the single record from the "ROADS_GEOM" table in which the geometry was equal to that value.
To check whether some of the roads passes in the area defined by a polygon:
SELECT road_id, road_name
FROM roads
WHERE ST_Intersects(roads_geom, 'SRID=312;POLYGON((...))');
PostGIS 3.3.2 Manual 52 / 902
The most common spatial query will probably be a "frame-based" query, used by client software, like data browsers and web
mappers, to grab a "map frame" worth of data for display.
When using the "&&" operator, you can specify either a BOX3D as the comparison feature or a GEOMETRY. When you specify
a GEOMETRY, however, its bounding box will be used for the comparison.
Using a "BOX3D" object for the frame, such a query looks like this:
SELECT ST_AsText(roads_geom) AS geom
FROM roads
WHERE
roads_geom && ST_MakeEnvelope(191232, 243117,191232, 243119,312);
Note the use of the SRID 312, to specify the projection of the envelope.
The pgsql2shp table dumper connects to the database and converts a table (possibly defined by a query) into a shape file. The
basic syntax is:
pgsql2shp [<options>] <database> [<schema>.]<table>
-r Raw mode. Do not drop the gid field, or escape column names.
-m filename Remap identifiers to ten character names. The content of the file is lines of two symbols separated by a single
white space and no trailing or leading space: VERYLONGSYMBOL SHORTONE ANOTHERVERYLONGSYMBOL
SHORTER etc.
Spatial indexes make using a spatial database for large data sets possible. Without indexing, a search for features requires a
sequential scan of every record in the database. Indexing speeds up searching by organizing the data into a structure which can
be quickly traversed to find matching records.
The B-tree index method commonly used for attribute data is not very useful for spatial data, since it only supports storing and
querying data in a single dimension. Data such as geometry (which has 2 or more dimensions) requires an index method that
supports range query across all the data dimensions. One of the key advantages of PostgreSQL for spatial data handling is that it
offers several kinds of index methods which work well for multi-dimensional data: GiST, BRIN and SP-GiST indexes.
PostGIS 3.3.2 Manual 53 / 902
• GiST (Generalized Search Tree) indexes break up data into "things to one side", "things which overlap", "things which are
inside" and can be used on a wide range of data-types, including GIS data. PostGIS uses an R-Tree index implemented on top
of GiST to index spatial data. GiST is the most commonly-used and versatile spatial index method, and offers very good query
performance.
• BRIN (Block Range Index) indexes operate by summarizing the spatial extent of ranges of table records. Search is done via
a scan of the ranges. BRIN is only appropriate for use for some kinds of data (spatially sorted, with infrequent or no update).
But it provides much faster index create time, and much smaller index size.
• SP-GiST (Space-Partitioned Generalized Search Tree) is a generic index method that supports partitioned search trees such
as quad-trees, k-d trees, and radix trees (tries).
Spatial indexes store only the bounding box of geometries. Spatial queries use the index as a primary filter to quickly deter-
mine a set of geometries potentially matching the query condition. Most spatial queries require a secondary filter that uses a
spatial predicate function to test a more specific spatial condition. For more information on queying with spatial predicates see
Section 5.2.
See also the PostGIS Workshop section on spatial indexes, and the PostgreSQL manual.
GiST stands for "Generalized Search Tree" and is a generic form of indexing for multi-dimensional data. PostGIS uses an R-Tree
index implemented on top of GiST to index spatial data. GiST is the most commonly-used and versatile spatial index method,
and offers very good query performance. Other implementations of GiST are used to speed up searches on all kinds of irregular
data structures (integer arrays, spectral data, etc) which are not amenable to normal B-Tree indexing. For more information see
the PostgreSQL manual.
Once a spatial data table exceeds a few thousand rows, you will want to build an index to speed up spatial searches of the data
(unless all your searches are based on attributes, in which case you’ll want to build a normal index on the attribute fields).
The syntax for building a GiST index on a "geometry" column is as follows:
CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometryfield] );
The above syntax will always build a 2D-index. To get the an n-dimensional index for the geometry type, you can create one
using this syntax:
CREATE INDEX [indexname] ON [tablename] USING GIST ([geometryfield] gist_geometry_ops_nd);
Building a spatial index is a computationally intensive exercise. It also blocks write access to your table for the time it creates,
so on a production system you may want to do in in a slower CONCURRENTLY-aware way:
CREATE INDEX CONCURRENTLY [indexname] ON [tablename] USING GIST ( [geometryfield] );
After building an index, it is sometimes helpful to force PostgreSQL to collect table statistics, which are used to optimize query
plans:
VACUUM ANALYZE [table_name] [(column_name)];
BRIN stands for "Block Range Index". It is a general-purpose index method introduced in PostgreSQL 9.5. BRIN is a lossy
index method, meaning that a secondary check is required to confirm that a record matches a given search condition (which is
the case for all provided spatial indexes). It provides much faster index creation and much smaller index size, with reasonable
read performance. Its primary purpose is to support indexing very large tables on columns which have a correlation with their
physical location within the table. In addition to spatial indexing, BRIN can speed up searches on various kinds of attribute data
structures (integer, arrays etc). For more information see the PostgreSQL manual.
PostGIS 3.3.2 Manual 54 / 902
Once a spatial table exceeds a few thousand rows, you will want to build an index to speed up spatial searches of the data. GiST
indexes are very performant as long as their size doesn’t exceed the amount of RAM available for the database, and as long as
you can afford the index storage size, and the cost of index update on write. Otherwise, for very large tables BRIN index can be
considered as an alternative.
A BRIN index stores the bounding box enclosing all the geometries contained in the rows in a contiguous set of table blocks,
called a block range. When executing a query using the index the block ranges are scanned to find the ones that intersect the
query extent. This is efficient only if the data is physically ordered so that the bounding boxes for block ranges have minimal
overlap (and ideally are mutually exclusive). The resulting index is very small in size, but is typically less performant for read
than a GiST index over the same data.
Building a BRIN index is much less CPU-intensive than building a GiST index. It’s common to find that a BRIN index is ten
times faster to build than a GiST index over the same data. And because a BRIN index stores only one bounding box for each
range of table blocks, it’s common to use up to a thousand times less disk space than a GiST index.
You can choose the number of blocks to summarize in a range. If you decrease this number, the index will be bigger but will
probably provide better performance.
For BRIN to be effective, the table data should be stored in a physical order which minimizes the amount of block extent overlap.
It may be that the data is already sorted appropriately (for instance, if it is loaded from another dataset that is already sorted in
spatial order). Otherwise, this can be accomplished by sorting the data by a one-dimensional spatial key. One way to do this is
to create a new table sorted by the geometry values (which in recent PostGIS versions uses an efficient Hilbert curve ordering):
CREATE TABLE table_sorted AS
SELECT * FROM table ORDER BY geom;
Alternatively, data can be sorted in-place by using a GeoHash as a (temporary) index, and clustering on that index:
CREATE INDEX idx_temp_geohash ON table
USING btree (ST_GeoHash( ST_Transform( geom, 4326 ), 20));
CLUSTER table USING idx_temp_geohash;
The above syntax builds a 2D index. To build a 3D-dimensional index, use this syntax:
CREATE INDEX [indexname] ON [tablename]
USING BRIN ([geome_col] brin_geometry_inclusion_ops_3d);
You can also get a 4D-dimensional index using the 4D operator class:
CREATE INDEX [indexname] ON [tablename]
USING BRIN ([geome_col] brin_geometry_inclusion_ops_4d);
The above commands use the default number of blocks in a range, which is 128. To specify the number of blocks to summarise
in a range, use this syntax
CREATE INDEX [indexname] ON [tablename]
USING BRIN ( [geome_col] ) WITH (pages_per_range = [number]);
Keep in mind that a BRIN index only stores one index entry for a large number of rows. If your table stores geometries with
a mixed number of dimensions, it’s likely that the resulting index will have poor performance. You can avoid this performance
penalty by choosing the operator class with the least number of dimensions of the stored geometries
The geography datatype is supported for BRIN indexing. The syntax for building a BRIN index on a geography column is:
CREATE INDEX [indexname] ON [tablename] USING BRIN ( [geog_col] );
PostGIS 3.3.2 Manual 55 / 902
The above syntax builds a 2D-index for geospatial objects on the spheroid.
Currently, only "inclusion support" is provided, meaning that just the &&, ~ and @ operators can be used for the 2D cases (for both
geometry and geography), and just the &&& operator for 3D geometries. There is currently no support for kNN searches.
An important difference between BRIN and other index types is that the database does not maintain the index dynamically.
Changes to spatial data in the table are simply appended to the end of the index. This will cause index search performance to de-
grade over time. The index can be updated by performing a VACUUM, or by using a special function brin_summarize_new_values
For this reason BRIN may be most appropriate for use with data that is read-only, or only rarely changing. For more information
refer to the manual.
To summarize using BRIN for spatial data:
• Index build time is very fast, and index size is very small.
• Index query time is slower than GiST, but can still be very acceptable.
• Requires table data to be sorted in a spatial ordering.
• Requires manual index maintenance.
• Most appropriate for very large tables, with low or no overlap (e.g. points), which are static or change infrequently.
• More effective for queries which return relatively large numbers of data records.
SP-GiST stands for "Space-Partitioned Generalized Search Tree" and is a generic form of indexing for multi-dimensional data
types that supports partitioned search trees, such as quad-trees, k-d trees, and radix trees (tries). The common feature of these
data structures is that they repeatedly divide the search space into partitions that need not be of equal size. In addition to spatial
indexing, SP-GiST is used to speed up searches on many kinds of data, such as phone routing, ip routing, substring search, etc.
For more information see the PostgreSQL manual.
As it is the case for GiST indexes, SP-GiST indexes are lossy, in the sense that they store the bounding box enclosing spatial
objects. SP-GiST indexes can be considered as an alternative to GiST indexes.
Once a GIS data table exceeds a few thousand rows, an SP-GiST index may be used to speed up spatial searches of the data. The
syntax for building an SP-GiST index on a "geometry" column is as follows:
CREATE INDEX [indexname] ON [tablename] USING SPGIST ( [geometryfield] );
The above syntax will build a 2-dimensional index. A 3-dimensional index for the geometry type can be created using the 3D
operator class:
CREATE INDEX [indexname] ON [tablename] USING SPGIST ([geometryfield] ←-
spgist_geometry_ops_3d);
Building a spatial index is a computationally intensive operation. It also blocks write access to your table for the time it creates,
so on a production system you may want to do in in a slower CONCURRENTLY-aware way:
CREATE INDEX CONCURRENTLY [indexname] ON [tablename] USING SPGIST ( [geometryfield] );
After building an index, it is sometimes helpful to force PostgreSQL to collect table statistics, which are used to optimize query
plans:
VACUUM ANALYZE [table_name] [(column_name)];
• <<, &<, &>, >>, <<|, &<|, |&>, |>>, &&, @>, <@, and ~=, for 2-dimensional indexes,
• &/&, ~==, @>>, and <<@, for 3-dimensional indexes.
Ordinarily, indexes invisibly speed up data access: once an index is built, the PostgreSQL query planner automatically decides
when to use it to improve query performance. But there are some situations where the planner does not choose to use existing
indexes, so queries end up using slow sequential scans instead of a spatial index.
If you find your spatial indexes are not being used, there are a few things you can do:
• Examine the query plan and check your query actually computes the thing you need. An erroneous JOIN, either forgotten or
to the wrong table, can unexpectedly retrieve table records multiple times. To get the query plan, execute with EXPLAIN in
front of the query.
• Make sure statistics are gathered about the number and distributions of values in a table, to provide the query planner with
better information to make decisions around index usage. VACUUM ANALYZE will compute both.
You should regularly vacuum your databases anyways. Many PostgreSQL DBAs run VACUUM as an off-peak cron job on a
regular basis.
• If vacuuming does not help, you can temporarily force the planner to use the index information by using the command SET
ENABLE_SEQSCAN TO OFF;. This way you can check whether the planner is at all able to generate an index-accelerated
query plan for your query. You should only use this command for debugging; generally speaking, the planner knows better
than you do about when to use indexes. Once you have run your query, do not forget to run SET ENABLE_SEQSCAN TO
ON; so that the planner will operate normally for other queries.
• If SET ENABLE_SEQSCAN TO OFF; helps your query to run faster, your Postgres is likely not tuned for your hardware. If
you find the planner wrong about the cost of sequential versus index scans try reducing the value of RANDOM_PAGE_COST in
postgresql.conf, or use SET RANDOM_PAGE_COST TO 1.1;. The default value for RANDOM_PAGE_COST is 4.0.
Try setting it to 1.1 (for SSD) or 2.0 (for fast magnetic disks). Decreasing the value makes the planner more likely to use index
scans.
• If SET ENABLE_SEQSCAN TO OFF; does not help your query, the query may be using a SQL construct that the Postgres
planner is not yet able to optimize. It may be possible to rewrite the query in a way that the planner is able to handle.
For example, a subquery with an inline SELECT may not produce an efficient plan, but could possibly be rewritten using a
LATERAL JOIN.
For more information see the Postgres manual section on Query Planning.
PostGIS 3.3.2 Manual 57 / 902
Chapter 5
Spatial Queries
The raison d’etre of spatial databases is to perform queries inside the database which would ordinarily require desktop GIS
functionality. Using PostGIS effectively requires knowing what spatial functions are available, how to use them in queries, and
ensuring that appropriate indexes are in place to provide good performance.
Spatial relationships indicate how two geometries interact with one another. They are a fundamental capability for querying
geometry.
According to the OpenGIS Simple Features Implementation Specification for SQL, "the basic approach to comparing two ge-
ometries is to make pair-wise tests of the intersections between the Interiors, Boundaries and Exteriors of the two geometries and
to classify the relationship between the two geometries based on the entries in the resulting ’intersection’ matrix."
In the theory of point-set topology, the points in a geometry embedded in 2-dimensional space are categorized into three sets:
Boundary
The boundary of a geometry is the set of geometries of the next lower dimension. For POINTs, which have a dimension
of 0, the boundary is the empty set. The boundary of a LINESTRING is the two endpoints. For POLYGONs, the boundary
is the linework of the exterior and interior rings.
Interior
The interior of a geometry are those points of a geometry that are not in the boundary. For POINTs, the interior is the point
itself. The interior of a LINESTRING is the set of points between the endpoints. For POLYGONs, the interior is the areal
surface inside the polygon.
Exterior
The exterior of a geometry is the rest of the space in which the geometry is embedded; in other words, all points not in the
interior or on the boundary of the geometry. It is a 2-dimensional non-closed surface.
The Dimensionally Extended 9-Intersection Model (DE-9IM) describes the spatial relationship between two geometries by spec-
ifying the dimensions of the 9 intersections between the above sets for each geometry. The intersection dimensions can be
formally represented in a 3x3 intersection matrix.
For a geometry g the Interior, Boundary, and Exterior are denoted using the notation I(g), B(g), and E(g). Also, dim(s) denotes
the dimension of a set s with the domain of {0,1,2,F}:
PostGIS 3.3.2 Manual 58 / 902
• 0 => point
• 1 => line
• 2 => area
• F => empty set
Using this notation, the intersection matrix for two geometries a and b is:
Interior
Boundary
Exterior
Reading from left to right and top to bottom, the intersection matrix is represented as the text string ’212101212’.
For more information, refer to:
• OpenGIS Simple Features Implementation Specification for SQL (version 1.1, section 2.1.13.2)
• Wikipedia: Dimensionally Extended Nine-Intersection Model (DE-9IM)
• GeoTools: Point Set Theory and the DE-9IM Matrix
To make it easy to determine common spatial relationships, the OGC SFS defines a set of named spatial relationship predi-
cates. PostGIS provides these as the functions ST_Contains, ST_Crosses, ST_Disjoint, ST_Equals, ST_Intersects, ST_Overlaps,
ST_Touches, ST_Within. It also defines the non-standard relationship predicates ST_Covers, ST_CoveredBy, and ST_ContainsProperly.
PostGIS 3.3.2 Manual 60 / 902
Spatial predicates are usually used as conditions in SQL WHERE or JOIN clauses. The named spatial predicates automatically
use a spatial index if one is available, so there is no need to use the bounding box operator && as well. For example:
SELECT city.name, state.name, city.geom
FROM city JOIN state ON ST_Intersects(city.geom, state.geom);
In some cases the named spatial relationships are insufficient to provide a desired spatial filter condition.
For example, consider a linear dataset representing a road network. It may be required to identify all road segments that
cross each other, not at a point, but in a line (perhaps to validate some business rule). In this case ST_Crosses does not
provide the necessary spatial filter, since for linear features it returns true only where they cross at a point.
A two-step solution would be to first compute the actual intersection (ST_Intersection) of pairs of road lines that spatially
intersect (ST_Intersects), and then check if the intersection’s ST_GeometryType is ’LINESTRING’ (properly dealing
with cases that return GEOMETRYCOLLECTIONs of [MULTI]POINTs, [MULTI]LINESTRINGs, etc.).
Clearly, a simpler and faster solution is desirable.
PostGIS 3.3.2 Manual 61 / 902
A second example is locating wharves that intersect a lake’s boundary on a line and where one end of the wharf is up on
shore. In other words, where a wharf is within but not completely contained by a lake, intersects the boundary of a lake on
a line, and where exactly one of the wharf’s endpoints is within or on the boundary of the lake. It is possible to use a
combination of spatial predicates to find the required features:
• ST_Contains(lake, wharf) = TRUE
• ST_ContainsProperly(lake, wharf) = FALSE
These requirements can be met by computing the full DE-9IM intersection matrix. PostGIS provides the ST_Relate function to
do this:
SELECT ST_Relate( 'LINESTRING (1 1, 5 5)',
'POLYGON ((3 3, 3 7, 7 7, 7 3, 3 3))' );
st_relate
-----------
1010F0212
To test a particular spatial relationship, an intersection matrix pattern is used. This is the matrix representation augmented with
the additional symbols {T,*}:
Using intersection matrix patterns, specific spatial relationships can be evaluated in a more succinct way. The ST_Relate and the
ST_RelateMatch functions can be used to test intersection matrix patterns. For the first example above, the intersection matrix
pattern specifying two lines intersecting in a line is ’1*1***1**’:
-- Find road segments that intersect in a line
SELECT a.id
FROM roads a, roads b
WHERE a.id != b.id
AND a.geom && b.geom
AND ST_Relate(a.geom, b.geom, '1*1***1**');
PostGIS 3.3.2 Manual 62 / 902
For the second example, the intersection matrix pattern specifying a line partly inside and partly outside a polygon is ’102101FF2’:
-- Find wharves partly on a lake's shoreline
SELECT a.lake_id, b.wharf_id
FROM lakes a, wharfs b
WHERE a.geom && b.geom
AND ST_Relate(a.geom, b.geom, '102101FF2');
When constructing queries using spatial conditions, for best performance it is important to ensure that a spatial index is used, if
one exists (see Section 4.9). To do this, a spatial operator or index-aware function must be used in a WHERE or ON clause of the
query.
Spatial operators include the bounding box operators (of which the most commonly used is &&; see Section 8.10.1 for the full
list) and the distance operators used in nearest-neighbor queries (the most common being <->; see Section 8.10.2 for the full list.)
Index-aware functions automatically add a bounding box operator to the spatial condition. Index-aware functions include the
named spatial relationship predicates ST_Contains, ST_ContainsProperly, ST_CoveredBy, ST_Covers, ST_Crosses, ST_Intersects,
ST_Overlaps, ST_Touches, ST_Within, ST_Within, and ST_3DIntersects, and the distance predicates ST_DWithin, ST_DFullyWithin,
ST_3DDFullyWithin, and ST_3DDWithin .)
Functions such as ST_Distance do not use indexes to optimize their operation. For example, the following query would be quite
slow on a large table:
SELECT geom
FROM geom_table
WHERE ST_Distance( geom, 'SRID=312;POINT(100000 200000)' ) < 100
This query selects all the geometries in geom_table which are within 100 units of the point (100000, 200000). It will be
slow because it is calculating the distance between each point in the table and the specified point, ie. one ST_Distance()
calculation is computed for every row in the table.
The number of rows processed can be reduced substantially by using the index-aware function ST_DWithin:
SELECT geom
FROM geom_table
WHERE ST_DWithin( geom, 'SRID=312;POINT(100000 200000)', 100 )
This query selects the same geometries, but it does it in a more efficient way. This is enabled by ST_DWithin() using the &&
operator internally on an expanded bounding box of the query geometry. If there is a spatial index on geom, the query planner
will recognize that it can use the index to reduce the number of rows scanned before calculating the distance. The spatial index
allows retrieving only records with geometries whose bounding boxes overlap the expanded extent and hence which might be
within the required distance. The actual distance is then computed to confirm whether to include the record in the result set.
For more information and examples see the PostGIS Workshop.
The examples in this section make use of a table of linear roads, and a table of polygonal municipality boundaries. The definition
of the bc_roads table is:
Column | Type | Description
----------+-------------------+-------------------
gid | integer | Unique ID
name | character varying | Road Name
geom | geometry | Location Geometry (Linestring)
PostGIS 3.3.2 Manual 63 / 902
km_roads
------------------
70842.1243039643
hectares
------------------
32657.9103824927
name | hectares
---------------+-----------------
TUMBLER RIDGE | 155020.02556131
Note that in order to answer this query we have to calculate the area of every polygon. If we were doing this a lot it
would make sense to add an area column to the table that could be indexed for performance. By ordering the results in
a descending direction, and them using the PostgreSQL "LIMIT" command we can easily select just the largest value
without using an aggregate function like MAX().
4. What is the length of roads fully contained within each municipality?
This is an example of a "spatial join", which brings together data from two tables (with a join) using a spatial interaction
("contained") as the join condition (rather than the usual relational approach of joining on a common key):
SELECT
m.name,
sum(ST_Length(r.geom))/1000 as roads_km
FROM bc_roads AS r
JOIN bc_municipality AS m
PostGIS 3.3.2 Manual 64 / 902
ON ST_Contains(m.geom, r.geom)
GROUP BY m.name
ORDER BY roads_km;
name | roads_km
----------------------------+------------------
SURREY | 1539.47553551242
VANCOUVER | 1450.33093486576
LANGLEY DISTRICT | 833.793392535662
BURNABY | 773.769091404338
PRINCE GEORGE | 694.37554369147
...
This query takes a while, because every road in the table is summarized into the final result (about 250K roads for the
example table). For smaller datsets (several thousand records on several hundred) the response can be very fast.
5. Create a new table with all the roads within the city of Prince George.
This is an example of an "overlay", which takes in two tables and outputs a new table that consists of spatially clipped
or cut resultants. Unlike the "spatial join" demonstrated above, this query creates new geometries. An overlay is like a
turbo-charged spatial join, and is useful for more exact analysis work:
CREATE TABLE pg_roads as
SELECT
ST_Intersection(r.geom, m.geom) AS intersection_geom,
ST_Length(r.geom) AS rd_orig_length,
r.*
FROM bc_roads AS r
JOIN bc_municipality AS m
ON ST_Intersects(r.geom, m.geom)
WHERE
m.name = 'PRINCE GEORGE';
kilometers
------------------
4.89151904172838
Chapter 6
Performance Tips
Current PostgreSQL versions (including 9.6) suffer from a query optimizer weakness regarding TOAST tables. TOAST tables
are a kind of "extension room" used to store large (in the sense of data size) values that do not fit into normal data pages (like long
texts, images or complex geometries with lots of vertices), see the PostgreSQL Documentation for TOAST for more information).
The problem appears if you happen to have a table with rather large geometries, but not too many rows of them (like a table
containing the boundaries of all European countries in high resolution). Then the table itself is small, but it uses lots of TOAST
space. In our example case, the table itself had about 80 rows and used only 3 data pages, but the TOAST table used 8225 pages.
Now issue a query where you use the geometry operator && to search for a bounding box that matches only very few of those
rows. Now the query optimizer sees that the table has only 3 pages and 80 rows. It estimates that a sequential scan on such a
small table is much faster than using an index. And so it decides to ignore the GIST index. Usually, this estimation is correct.
But in our case, the && operator has to fetch every geometry from disk to compare the bounding boxes, thus reading all TOAST
pages, too.
To see whether your suffer from this issue, use the "EXPLAIN ANALYZE" postgresql command. For more information and
the technical details, you can read the thread on the PostgreSQL performance mailing list: http://archives.postgresql.org/pgsql-
performance/2005-02/msg00030.php
and newer thread on PostGIS https://lists.osgeo.org/pipermail/postgis-devel/2017-June/026209.html
6.1.2 Workarounds
The PostgreSQL people are trying to solve this issue by making the query estimation TOAST-aware. For now, here are two
workarounds:
The first workaround is to force the query planner to use the index. Send "SET enable_seqscan TO off;" to the server before
issuing the query. This basically forces the query planner to avoid sequential scans whenever possible. So it uses the GIST index
as usual. But this flag has to be set on every connection, and it causes the query planner to make misestimations in other cases,
so you should "SET enable_seqscan TO on;" after the query.
The second workaround is to make the sequential scan as fast as the query planner thinks. This can be achieved by creating an
additional column that "caches" the bbox, and matching against this. In our example, the commands are like:
SELECT AddGeometryColumn('myschema','mytable','bbox','4326','GEOMETRY','2');
UPDATE mytable SET bbox = ST_Envelope(ST_Force2D(geom));
Now change your query to use the && operator against bbox instead of geom_column, like:
PostGIS 3.3.2 Manual 66 / 902
SELECT geom_column
FROM mytable
WHERE bbox && ST_SetSRID('BOX3D(0 0,1 1)'::box3d,4326);
Of course, if you change or add rows to mytable, you have to keep the bbox "in sync". The most transparent way to do this would
be triggers, but you also can modify your application to keep the bbox column current or run the UPDATE query above after
every modification.
For tables that are mostly read-only, and where a single index is used for the majority of queries, PostgreSQL offers the CLUS-
TER command. This command physically reorders all the data rows in the same order as the index criteria, yielding two
performance advantages: First, for index range scans, the number of seeks on the data table is drastically reduced. Second, if
your working set concentrates to some small intervals on the indices, you have a more efficient caching because the data rows
are spread along fewer data pages. (Feel invited to read the CLUSTER command documentation from the PostgreSQL manual
at this point.)
However, currently PostgreSQL does not allow clustering on PostGIS GIST indices because GIST indices simply ignores NULL
values, you get an error message like:
lwgeom=# CLUSTER my_geom_index ON my_table;
ERROR: cannot cluster when index access method does not handle null values
HINT: You may be able to work around this by marking column "geom" NOT NULL.
As the HINT message tells you, one can work around this deficiency by adding a "not null" constraint to the table:
lwgeom=# ALTER TABLE my_table ALTER COLUMN geom SET not null;
ALTER TABLE
Of course, this will not work if you in fact need NULL values in your geometry column. Additionally, you must use the above
method to add the constraint, using a CHECK constraint like "ALTER TABLE blubb ADD CHECK (geometry is not null);" will
not work.
Sometimes, you happen to have 3D or 4D data in your table, but always access it using OpenGIS compliant ST_AsText() or
ST_AsBinary() functions that only output 2D geometries. They do this by internally calling the ST_Force2D() function, which
introduces a significant overhead for large geometries. To avoid this overhead, it may be feasible to pre-drop those additional
dimensions once and forever:
UPDATE mytable SET geom = ST_Force2D(geom);
VACUUM FULL ANALYZE mytable;
Note that if you added your geometry column using AddGeometryColumn() there’ll be a constraint on geometry dimension. To
bypass it you will need to drop the constraint. Remember to update the entry in the geometry_columns table and recreate the
constraint afterwards.
In case of large tables, it may be wise to divide this UPDATE into smaller portions by constraining the UPDATE to a part of the
table via a WHERE clause and your primary key or another feasible criteria, and running a simple "VACUUM;" between your
UPDATEs. This drastically reduces the need for temporary disk space. Additionally, if you have mixed dimension geometries,
restricting the UPDATE by "WHERE dimension(geom)>2" skips re-writing of geometries that already are in 2D.
PostGIS 3.3.2 Manual 67 / 902
Chapter 7
Building Applications
The Minnesota MapServer is an internet web-mapping server which conforms to the OpenGIS Web Map Service specification.
To use PostGIS with MapServer, you need to know how to configure MapServer, which is beyond the scope of this documentation.
This section covers specific PostGIS issues and configuration details.
To use PostGIS with MapServer, you will need:
MapServer accesses PostGIS/PostgreSQL data like any other PostgreSQL client, using the libpq interface. This means that
MapServer can be installed on any machine with network access to the PostGIS server, and use PostGIS as a source of data. The
faster the connection between the systems, the better.
1. Compile and install MapServer, with whatever options you desire, including the "--with-postgis" configuration option.
2. In your MapServer map file, add a PostGIS layer. For example:
LAYER
CONNECTIONTYPE postgis
NAME "widehighways"
# Connect to a remote spatial database
CONNECTION "user=dbuser dbname=gisdatabase host=bigserver"
PROCESSING "CLOSE_CONNECTION=DEFER"
# Get the lines from the 'geom' column of the 'roads' table
DATA "geom from roads using srid=4326 using unique gid"
STATUS ON
TYPE LINE
# Of the lines in the extents, only render the wide highways
FILTER "type = 'highway' and numlanes >= 4"
CLASS
# Make the superhighways brighter and 2 pixels wide
PostGIS 3.3.2 Manual 68 / 902
4. If you will be querying your layers using MapServer you will also need to use the "using unique" clause in your DATA
statement.
MapServer requires unique identifiers for each spatial record when doing queries, and the PostGIS module of MapServer
uses the unique value you specify in order to provide these unique identifiers. Using the table primary key is the best
practice.
1. When I use an EXPRESSION in my map file, the condition never returns as true, even though I know the values exist in
my table.
Unlike shape files, PostGIS field names have to be referenced in EXPRESSIONS using lower case.
EXPRESSION ([numlanes] >= 6)
2. The FILTER I use for my Shapefiles is not working for my PostGIS table of the same data.
Unlike shape files, filters for PostGIS layers use SQL syntax (they are appended to the SQL statement the PostGIS con-
nector generates for drawing layers in MapServer).
PostGIS 3.3.2 Manual 69 / 902
3. My PostGIS layer draws much slower than my Shapefile layer, is this normal?
In general, the more features you are drawing into a given map, the more likely it is that PostGIS will be slower than
Shapefiles. For maps with relatively few features (100s), PostGIS will often be faster. For maps with high feature density
(1000s), PostGIS will always be slower. If you are finding substantial draw performance problems, it is possible that you
have not built a spatial index on your table.
postgis# CREATE INDEX geotable_gix ON geotable USING GIST ( geocolumn );
postgis# VACUUM ANALYZE;
4. My PostGIS layer draws fine, but queries are really slow. What is wrong?
For queries to be fast, you must have a unique key for your spatial table and you must have an index on that unique key.You
can specify what unique key for mapserver to use with the USING UNIQUE clause in your DATA line:
DATA "geom FROM geotable USING UNIQUE gid"
5. Can I use "geography" columns (new in PostGIS 1.5) as a source for MapServer layers?
Yes! MapServer understands geography columns as being the same as geometry columns, but always using an SRID of
4326. Just make sure to include a "using srid=4326" clause in your DATA statement. Everything else works exactly the
same as with geometry.
DATA "geog FROM geogtable USING SRID=4326 USING UNIQUE gid"
The USING pseudo-SQL clause is used to add some information to help mapserver understand the results of more complex
queries. More specifically, when either a view or a subselect is used as the source table (the thing to the right of "FROM" in a
DATA definition) it is more difficult for mapserver to automatically determine a unique identifier for each row and also the SRID
for the table. The USING clause can provide mapserver with these two pieces of information as follows:
DATA "geom FROM (
SELECT
table1.geom AS geom,
table1.gid AS gid,
table2.data AS data
FROM table1
LEFT JOIN table2
ON table1.id = table2.id
) AS new_table USING UNIQUE gid USING SRID=4326"
USING UNIQUE <uniqueid> MapServer requires a unique id for each row in order to identify the row when doing map
queries. Normally it identifies the primary key from the system tables. However, views and subselects don’t automatically
have an known unique column. If you want to use MapServer’s query functionality, you need to ensure your view or
subselect includes a uniquely valued column, and declare it with USING UNIQUE. For example, you could explicitly
select nee of the table’s primary key values for this purpose, or any other column which is guaranteed to be unique for the
result set.
Note
"Querying a Map" is the action of clicking on a map to ask for information about the map features in that location.
Don’t confuse "map queries" with the SQL query in a DATA definition.
USING SRID=<srid> PostGIS needs to know which spatial referencing system is being used by the geometries in order to
return the correct data back to MapServer. Normally it is possible to find this information in the "geometry_columns" table
in the PostGIS database, however, this is not possible for tables which are created on the fly such as subselects and views.
So the USING SRID= option allows the correct SRID to be specified in the DATA definition.
PostGIS 3.3.2 Manual 70 / 902
7.1.4 Examples
Lets start with a simple example and work our way up. Consider the following MapServer layer definition:
LAYER
CONNECTIONTYPE postgis
NAME "roads"
CONNECTION "user=theuser password=thepass dbname=thedb host=theserver"
DATA "geom from roads"
STATUS ON
TYPE LINE
CLASS
STYLE
COLOR 0 0 0
END
END
END
This layer will display all the road geometries in the roads table as black lines.
Now lets say we want to show only the highways until we get zoomed in to at least a 1:100000 scale - the next two layers will
achieve this effect:
LAYER
CONNECTIONTYPE postgis
CONNECTION "user=theuser password=thepass dbname=thedb host=theserver"
PROCESSING "CLOSE_CONNECTION=DEFER"
DATA "geom from roads"
MINSCALE 100000
STATUS ON
TYPE LINE
FILTER "road_type = 'highway'"
CLASS
COLOR 0 0 0
END
END
LAYER
CONNECTIONTYPE postgis
CONNECTION "user=theuser password=thepass dbname=thedb host=theserver"
PROCESSING "CLOSE_CONNECTION=DEFER"
DATA "geom from roads"
MAXSCALE 100000
STATUS ON
TYPE LINE
CLASSITEM road_type
CLASS
EXPRESSION "highway"
STYLE
WIDTH 2
COLOR 255 0 0
END
END
CLASS
STYLE
COLOR 0 0 0
END
END
END
The first layer is used when the scale is greater than 1:100000, and displays only the roads of type "highway" as black lines. The
FILTER option causes only roads of type "highway" to be displayed.
PostGIS 3.3.2 Manual 71 / 902
The second layer is used when the scale is less than 1:100000, and will display highways as double-thick red lines, and other
roads as regular black lines.
So, we have done a couple of interesting things using only MapServer functionality, but our DATA SQL statement has remained
simple. Suppose that the name of the road is stored in another table (for whatever reason) and we need to do a join to get it and
label our roads.
LAYER
CONNECTIONTYPE postgis
CONNECTION "user=theuser password=thepass dbname=thedb host=theserver"
DATA "geom FROM (SELECT roads.gid AS gid, roads.geom AS geom,
road_names.name as name FROM roads LEFT JOIN road_names ON
roads.road_name_id = road_names.road_name_id)
AS named_roads USING UNIQUE gid USING SRID=4326"
MAXSCALE 20000
STATUS ON
TYPE ANNOTATION
LABELITEM name
CLASS
LABEL
ANGLE auto
SIZE 8
COLOR 0 192 0
TYPE truetype
FONT arial
END
END
END
This annotation layer adds green labels to all the roads when the scale gets down to 1:20000 or less. It also demonstrates how to
use an SQL join in a DATA definition.
Java clients can access PostGIS "geometry" objects in the PostgreSQL database either directly as text representations or using
the JDBC extension objects bundled with PostGIS. In order to use the extension objects, the "postgis.jar" file must be in your
CLASSPATH along with the "postgresql.jar" JDBC driver package.
import java.sql.*;
import java.util.*;
import java.lang.*;
import org.postgis.*;
java.sql.Connection conn;
try {
/*
* Load the JDBC driver and establish a connection.
*/
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost:5432/database";
conn = DriverManager.getConnection(url, "postgres", "");
/*
* Add the geometry types to the connection. Note that you
* must cast the connection to the pgsql-specific connection
* implementation before calling the addDataType() method.
PostGIS 3.3.2 Manual 72 / 902
*/
((org.postgresql.PGConnection)conn).addDataType("geometry",Class.forName("org.postgis. ←-
PGgeometry"));
((org.postgresql.PGConnection)conn).addDataType("box3d",Class.forName("org.postgis. ←-
PGbox3d"));
/*
* Create a statement and execute a select query.
*/
Statement s = conn.createStatement();
ResultSet r = s.executeQuery("select geom,id from geomtable");
while( r.next() ) {
/*
* Retrieve the geometry as an object then cast it to the geometry type.
* Print things out.
*/
PGgeometry geom = (PGgeometry)r.getObject(1);
int id = r.getInt(2);
System.out.println("Row " + id + ":");
System.out.println(geom.toString());
}
s.close();
conn.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
The "PGgeometry" object is a wrapper object which contains a specific topological geometry object (subclasses of the abstract
class "Geometry") depending on the type: Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon.
PGgeometry geom = (PGgeometry)r.getObject(1);
if( geom.getType() == Geometry.POLYGON ) {
Polygon pl = (Polygon)geom.getGeometry();
for( int r = 0; r < pl.numRings(); r++) {
LinearRing rng = pl.getRing(r);
System.out.println("Ring: " + r);
for( int p = 0; p < rng.numPoints(); p++ ) {
Point pt = rng.getPoint(p);
System.out.println("Point: " + p);
System.out.println(pt.toString());
}
}
}
The JavaDoc for the extension objects provides a reference for the various data accessor functions in the geometric objects.
...
...
...
PostGIS 3.3.2 Manual 73 / 902
Chapter 8
PostGIS Reference
The functions given below are the ones which a user of PostGIS is likely to need. There are other functions which are required
support functions to the PostGIS objects which are not of use to a general user.
Note
PostGIS has begun a transition from the existing naming convention to an SQL-MM-centric convention. As a result,
most of the functions that you know and love have been renamed using the standard spatial type (ST) prefix. Previous
functions are still available, though are not listed in this document where updated functions are equivalent. The non
ST_ functions not listed in this documentation are deprecated and will be removed in a future release so STOP USING
THEM.
8.1.1 box2d
Description
box2d is a spatial data type used to represent the two-dimensional bounding box enclosing a geometry or collection of geome-
tries. For example, the ST_Extent aggregate function returns a box2d object.
The representation contains the values xmin, ymin, xmax, ymax. These are the minimum and maximum values of the X
and Y extents.
box2d objects have a text representation which looks like BOX(1 2,5 6).
Casting Behavior
This table lists the automatic and explicit casts allowed for this data type:
Cast To Behavior
box3d automatic
geometry automatic
PostGIS 3.3.2 Manual 74 / 902
See Also
Section 15.7
8.1.2 box3d
Description
box3d is a PostGIS spatial data type used to represent the three-dimensional bounding box enclosing a geometry or collection
of geometries. For example, the ST_3DExtent aggregate function returns a box3d object.
The representation contains the values xmin, ymin, zmin, xmax, ymax, zmax. These are the minimum and maxium
values of the X, Y and Z extents.
box3d objects have a text representation which looks like BOX3D(1 2 3,5 6 5).
Casting Behavior
This table lists the automatic and explicit casts allowed for this data type:
Cast To Behavior
box automatic
box2d automatic
geometry automatic
See Also
Section 15.7
8.1.3 geometry
geometry — The type representing spatial features with planar coordinate systems.
Description
geometry is a fundamental PostGIS spatial data type used to represent a feature in planar (Euclidean) coordinate systems.
All spatial operations on geometry use the units of the Spatial Reference System the geometry is in.
Casting Behavior
This table lists the automatic and explicit casts allowed for this data type:
Cast To Behavior
box automatic
box2d automatic
box3d automatic
bytea automatic
geography automatic
text automatic
PostGIS 3.3.2 Manual 75 / 902
See Also
8.1.4 geometry_dump
Description
• geom - a geometry representing a component of the dumped geometry. The geometry type depends on the originating function.
• path[] - an integer array that defines the navigation path within the dumped geometry to the geom component. The path
array is 1-based (i.e. path[1] is the first element.)
It is used by the ST_Dump* family of functions as an output type to explode a complex geometry into its constituent parts.
See Also
Section 15.6
8.1.5 geography
geography — The type representing spatial features with geodetic (ellipsoidal) coordinate systems.
Description
geography is a spatial data type used to represent a feature in geodetic coordinate systems. Geodetic coordinate systems model
the earth using an ellipsoid.
Spatial operations on the geography type provide more accurate results by taking the ellipsoidal model into account.
Casting Behavior
This table lists the automatic and explicit casts allowed for this data type:
Cast To Behavior
geometry explicit
See Also
8.2.1 AddGeometryColumn
Synopsis
text AddGeometryColumn(varchar table_name, varchar column_name, integer srid, varchar type, integer dimension, boolean
use_typmod=true);
text AddGeometryColumn(varchar schema_name, varchar table_name, varchar column_name, integer srid, varchar type, inte-
ger dimension, boolean use_typmod=true);
text AddGeometryColumn(varchar catalog_name, varchar schema_name, varchar table_name, varchar column_name, integer
srid, varchar type, integer dimension, boolean use_typmod=true);
Description
Adds a geometry column to an existing table of attributes. The schema_name is the name of the table schema. The srid
must be an integer value reference to an entry in the SPATIAL_REF_SYS table. The type must be a string corresponding to the
geometry type, eg, ’POLYGON’ or ’MULTILINESTRING’ . An error is thrown if the schemaname doesn’t exist (or not visible
in the current search_path) or the specified SRID, geometry type, or dimension is invalid.
Note
Changed: 2.0.0 This function no longer updates geometry_columns since geometry_columns is a view that reads from
system catalogs. It by default also does not create constraints, but instead uses the built in type modifier behavior of
PostgreSQL. So for example building a wgs84 POINT column with this function is now equivalent to: ALTER TABLE
some_table ADD COLUMN geom geometry(Point,4326);
Changed: 2.0.0 If you require the old behavior of constraints use the default use_typmod, but set it to false.
Note
Changed: 2.0.0 Views can no longer be manually registered in geometry_columns, however views built against geome-
try typmod tables geometries and used without wrapper functions will register themselves correctly because they inherit
the typmod behavior of their parent table column. Views that use geometry functions that output other geometries will
need to be cast to typmod geometries for these view geometry columns to be registered correctly in geometry_columns.
Refer to Section 4.6.3.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
Examples
-- Describing the table shows a simple table with a single "id" column.
postgis=# \d my_schema.my_spatial_table
Table "my_schema.my_spatial_table"
Column | Type | Modifiers
--------+---------+------------------------------------------------------------------------- ←-
-- Describe the table again reveals the addition of a new geometry columns.
\d my_schema.my_spatial_table
addgeometrycolumn
-------------------------------------------------------------------------
my_schema.my_spatial_table.geomcp_c SRID:4326 TYPE:CURVEPOLYGON DIMS:2
(1 row)
Table "my_schema.my_spatial_table"
Column | Type | Modifiers
----------+----------------------+-------------------------------------------------------------------
See Also
8.2.2 DropGeometryColumn
Synopsis
Description
Removes a geometry column from a spatial table. Note that schema_name will need to match the f_table_schema field of the
table’s row in the geometry_columns table.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
Note
Changed: 2.0.0 This function is provided for backward compatibility. Now that since geometry_columns is now a view
against the system catalogs, you can drop a geometry column like any other table column using ALTER TABLE
Examples
See Also
8.2.3 DropGeometryTable
Synopsis
Description
Drops a table and all its references in geometry_columns. Note: uses current_schema() on schema-aware pgsql installations if
schema is not provided.
Note
Changed: 2.0.0 This function is provided for backward compatibility. Now that since geometry_columns is now a view
against the system catalogs, you can drop a table with geometry columns like any other table using DROP TABLE
PostGIS 3.3.2 Manual 79 / 902
Examples
See Also
8.2.4 Find_SRID
Synopsis
Description
Returns the integer SRID of the specified geometry column by searching through the GEOMETRY_COLUMNS table. If the
geometry column has not been properly added (e.g. with the AddGeometryColumn function), this function will not work.
Examples
See Also
ST_SRID
8.2.5 Populate_Geometry_Columns
Populate_Geometry_Columns — Ensures geometry columns are defined with type modifiers or have appropriate spatial con-
straints.
Synopsis
Description
Ensures geometry columns have appropriate type modifiers or spatial constraints to ensure they are registered correctly in the
geometry_columns view. By default will convert all geometry columns with no type modifier to ones with type modifiers.
For backwards compatibility and for spatial needs such as table inheritance where each child table may have different geometry
type, the old check constraint behavior is still supported. If you need the old behavior, you need to pass in the new optional
argument as false use_typmod=false. When this is done geometry columns will be created with no type modifiers but will
have 3 constraints defined. In particular, this means that every geometry column belonging to a table has at least three constraints:
• enforce_dims_geom - ensures every geometry has the same dimension (see ST_NDims)
• enforce_geotype_geom - ensures every geometry is of the same type (see GeometryType)
• enforce_srid_geom - ensures every geometry is in the same projection (see ST_SRID)
If a table oid is provided, this function tries to determine the srid, dimension, and geometry type of all geometry columns in the
table, adding constraints as necessary. If successful, an appropriate row is inserted into the geometry_columns table, otherwise,
the exception is caught and an error notice is raised describing the problem.
If the oid of a view is provided, as with a table oid, this function tries to determine the srid, dimension, and type of all
the geometries in the view, inserting appropriate entries into the geometry_columns table, but nothing is done to enforce
constraints.
The parameterless variant is a simple wrapper for the parameterized variant that first truncates and repopulates the geome-
try_columns table for every spatial table and view in the database, adding spatial constraints to tables where appropriate. It
returns a summary of the number of geometry columns detected in the database and the number that were inserted into the
geometry_columns table. The parameterized version simply returns the number of rows inserted into the geometry_columns
table.
Availability: 1.4.0
Changed: 2.0.0 By default, now uses type modifiers instead of check constraints to constrain geometry types. You can still use
check constraint behavior instead by using the new use_typmod and setting it to false.
Enhanced: 2.0.0 use_typmod optional argument was introduced that allows controlling if columns are created with typmodi-
fiers or with check constraints.
Examples
populate_geometry_columns
--------------------------
1
\d myspatial_table
Table "public.myspatial_table"
Column | Type | Modifiers
--------+---------------------------+---------------------------------------------------------------
-- This will change the geometry columns to use constraints if they are not typmod or have ←-
constraints already.
--For this to work, there must exist data
CREATE TABLE public.myspatial_table_cs(gid serial, geom geometry);
INSERT INTO myspatial_table_cs(geom) VALUES(ST_GeomFromText('LINESTRING(1 2, 3 4)',4326) );
SELECT Populate_Geometry_Columns('public.myspatial_table_cs'::regclass, false);
populate_geometry_columns
--------------------------
1
\d myspatial_table_cs
Table "public.myspatial_table_cs"
Column | Type | Modifiers
--------+----------+------------------------------------------------------------------
gid | integer | not null default nextval('myspatial_table_cs_gid_seq'::regclass)
geom | geometry |
Check constraints:
"enforce_dims_geom" CHECK (st_ndims(geom) = 2)
"enforce_geotype_geom" CHECK (geometrytype(geom) = 'LINESTRING'::text OR geom IS NULL)
"enforce_srid_geom" CHECK (st_srid(geom) = 4326)
8.2.6 UpdateGeometrySRID
UpdateGeometrySRID — Updates the SRID of all features in a geometry column, and the table metadata.
Synopsis
Description
Updates the SRID of all features in a geometry column, updating constraints and reference in geometry_columns. If the column
was enforced by a type definition, the type definition will be changed. Note: uses current_schema() on schema-aware pgsql
installations if schema is not provided.
Examples
Insert geometries into roads table with a SRID set already using EWKT format:
COPY roads (geom) FROM STDIN;
SRID=4326;LINESTRING(0 0, 10 10)
SRID=4326;LINESTRING(10 10, 15 0)
\.
This will change the srid of the roads table to 4326 from whatever it was before:
SELECT UpdateGeometrySRID('roads','geom',4326);
PostGIS 3.3.2 Manual 82 / 902
If you got the projection wrong (or brought it in as unknown) in load and you wanted to transform to web mercator all in one
shot you can do this with DDL but there is no equivalent PostGIS management function to do so in one go.
ALTER TABLE roads
ALTER COLUMN geom TYPE geometry(MULTILINESTRING, 3857) USING ST_Transform(ST_SetSRID(geom ←-
,4326),3857) ;
See Also
8.3.1 ST_Collect
Synopsis
Description
Collects geometries into a geometry collection. The result is either a Multi* or a GeometryCollection, depending on whether
the input geometries have the same or different types (homogeneous or heterogeneous). The input geometries are left unchanged
within the collection.
Variant 1: accepts two input geometries
Variant 2: accepts an array of geometries
Variant 3: aggregate function accepting a rowset of geometries.
Note
If any of the input geometries are collections (Multi* or GeometryCollection) ST_Collect returns a GeometryCollection
(since that is the only type which can contain nested collections). To prevent this, use ST_Dump in a subquery to
expand the input collections to their atomic elements (see example below).
Note
ST_Collect and ST_Union appear similar, but in fact operate quite differently. ST_Collect aggregates geometries into
a collection without changing them in any way. ST_Union geometrically merges geometries where they overlap, and
splits linestrings at intersections. It may return single geometries when it dissolves boundaries.
Availability: 1.4.0 - ST_Collect(geomarray) was introduced. ST_Collect was enhanced to handle more geometries faster.
Collect 2D points.
SELECT ST_AsText( ST_Collect( ST_GeomFromText('POINT(1 2)'),
ST_GeomFromText('POINT(-2 3)') ));
st_astext
----------
MULTIPOINT((1 2),(-2 3))
Collect 3D points.
SELECT ST_AsEWKT( ST_Collect( ST_GeomFromEWKT('POINT(1 2 3)'),
ST_GeomFromEWKT('POINT(1 2 4)') ) );
st_asewkt
-------------------------
MULTIPOINT(1 2 3,1 2 4)
Collect curves.
SELECT ST_AsText( ST_Collect( 'CIRCULARSTRING(220268 150415,220227 150505,220227 150406)',
'CIRCULARSTRING(220227 150406,2220227 150407,220227 150406)'));
st_astext
------------------------------------------------------------------------------------
MULTICURVE(CIRCULARSTRING(220268 150415,220227 150505,220227 150406),
CIRCULARSTRING(220227 150406,2220227 150407,220227 150406))
--wkt collect --
MULTILINESTRING((1 2,3 4),(3 4,4 5))
See Also
ST_Dump, ST_Union
PostGIS 3.3.2 Manual 84 / 902
8.3.2 ST_LineFromMultiPoint
Synopsis
Description
Examples
--result--
LINESTRING(1 2 3,4 5 6,7 8 9)
See Also
ST_AsEWKT, ST_MakeLine
8.3.3 ST_MakeEnvelope
Synopsis
geometry ST_MakeEnvelope(float xmin, float ymin, float xmax, float ymax, integer srid=unknown);
Description
Creates a rectangular Polygon from the minimum and maximum values for X and Y. Input values must be in the spatial reference
system specified by the SRID. If no SRID is specified the unknown spatial reference system (SRID 0) is used.
Availability: 1.5
Enhanced: 2.0: Ability to specify an envelope without specifying an SRID was introduced.
st_asewkt
-----------
POLYGON((10 10, 10 11, 11 11, 11 10, 10 10))
PostGIS 3.3.2 Manual 85 / 902
See Also
8.3.4 ST_MakeLine
Synopsis
Description
Creates a LineString containing the points of Point, MultiPoint, or LineString geometries. Other geometry types cause an error.
Variant 1: accepts two input geometries
Variant 2: accepts an array of geometries
Variant 3: aggregate function accepting a rowset of geometries. To ensure the order of the input geometries use ORDER BY in
the function call, or a subquery with an ORDER BY clause.
Repeated nodes at the beginning of input LineStrings are collapsed to a single point. Repeated points in Point and MultiPoint
inputs are not collapsed. ST_RemoveRepeatedPoints can be used to collapse repeated points from the output LineString.
st_astext
---------------------
LINESTRING(1 2,3 4)
st_asewkt
-------------------------
LINESTRING(1 2 3,3 4 5)
st_astext
-----------------------------
LINESTRING(0 0,1 1,2 2,3 3)
PostGIS 3.3.2 Manual 86 / 902
st_asewkt
-------------------------
LINESTRING(1 2 3,3 4 5,6 6 6)
This example queries time-based sequences of GPS points from a set of tracks and creates one record for each track. The result
geometries are LineStrings composed of the GPS track points in the order of travel.
Using aggregate ORDER BY provides a correctly-ordered LineString.
SELECT gps.track_id, ST_MakeLine(gps.geom ORDER BY gps_time) As geom
FROM gps_points As gps
GROUP BY track_id;
Prior to PostgreSQL 9, ordering in a subquery can be used. However, sometimes the query plan may not respect the order of the
subquery.
SELECT gps.track_id, ST_MakeLine(gps.geom) As geom
FROM ( SELECT track_id, gps_time, geom
FROM gps_points ORDER BY track_id, gps_time ) As gps
GROUP BY track_id;
See Also
8.3.5 ST_MakePoint
Synopsis
Description
Note
For geodetic coordinates, X is longitude and Y is latitude
Examples
--Get z of point
SELECT ST_Z(ST_MakePoint(1, 2,1.5));
result
-------
1.5
See Also
8.3.6 ST_MakePointM
Synopsis
Description
Note
For geodetic coordinates, X is longitude and Y is latitude
PostGIS 3.3.2 Manual 88 / 902
Examples
Note
ST_AsEWKT is used for text output because ST_AsText does not support M values.
st_asewkt
-----------------------------------------------
POINTM(-71.1043443253471 42.3150676015829 10)
st_asewkt
---------------------------------------------------------
SRID=4326;POINTM(-71.104 42.315 10)
result
-------
10
See Also
8.3.7 ST_MakePolygon
Synopsis
Description
Creates a Polygon formed by the given shell and optional array of holes. Input geometries must be closed LineStrings (rings).
Variant 1: Accepts one shell LineString.
Variant 2: Accepts a shell LineString and an array of inner (hole) LineStrings. A geometry array can be constructed using the
PostgreSQL array_agg(), ARRAY[] or ARRAY() constructs.
PostGIS 3.3.2 Manual 89 / 902
Note
This function does not accept MultiLineStrings. Use ST_LineMerge to generate a LineString, or ST_Dump to extract
LineStrings.
Create a Polygon from an open LineString, using ST_StartPoint and ST_AddPoint to close it.
SELECT ST_MakePolygon( ST_AddPoint(foo.open_line, ST_StartPoint(foo.open_line)) )
FROM (
SELECT ST_GeomFromText('LINESTRING(75 29,77 29,77 29, 75 29)') As open_line) As foo;
st_asewkt
-----------
POLYGON((75.15 29.53 1,77 29 1,77.6 29.5 1,75.15 29.53 1))
st_asewkt
----------
POLYGONM((75.15 29.53 1,77 29 1,77.6 29.5 2,75.15 29.53 2))
Create a set of province boundaries with holes representing lakes. The input is a table of province Polygons/MultiPolygons and a
table of water linestrings. Lines forming lakes are determined by using ST_IsClosed. The province linework is extracted by using
ST_Boundary. As required by ST_MakePolygon, the boundary is forced to be a single LineString by using ST_LineMerge.
(However, note that if a province has more than one region or has islands this will produce an invalid polygon.) Using a LEFT
JOIN ensures all provinces are included even if they have no lakes.
Note
The CASE construct is used because passing a null array into ST_MakePolygon results in a NULL return value.
PostGIS 3.3.2 Manual 90 / 902
Another technique is to utilize a correlated subquery and the ARRAY() constructor that converts a row set to an array.
SELECT p.gid, p.province_name,
CASE WHEN EXISTS( SELECT w.geom
FROM waterlines w
WHERE ST_Within(w.geom, p.geom)
AND ST_IsClosed(w.geom))
THEN ST_MakePolygon(
ST_LineMerge(ST_Boundary(p.geom)),
ARRAY( SELECT w.geom
FROM waterlines w
WHERE ST_Within(w.geom, p.geom)
AND ST_IsClosed(w.geom)))
ELSE p.geom
END AS geom
FROM provinces p;
See Also
ST_BuildArea ST_Polygon
8.3.8 ST_Point
Synopsis
Description
Returns a Point with the given X and Y coordinate values. This is the SQL-MM equivalent for ST_MakePoint that takes just X
and Y.
Note
For geodetic coordinates, X is longitude and Y is latitude
Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the
srid on the geometry.
Examples: Geometry
Examples: Geography
If the point coordinates are not in a geodetic coordinate system (such as WGS84), then they must be reprojected before casting
to a geography. In this example a point in Pennsylvania State Plane feet (SRID 2273) is projected to WGS84 (SRID 4326).
SELECT ST_Transform(ST_SetSRID( ST_Point( 3637510, 3014852 ), 2273), 4326)::geography;
See Also
8.3.9 ST_PointZ
Synopsis
Description
Returns an Point with the given X, Y and Z coordinate values, and optionally an SRID number.
Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the
srid on the geometry.
Examples
See Also
8.3.10 ST_PointM
Synopsis
Description
Returns an Point with the given X, Y and M coordinate values, and optionally an SRID number.
Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the
srid on the geometry.
Examples
See Also
8.3.11 ST_PointZM
Synopsis
Description
Returns an Point with the given X, Y, Z and M coordinate values, and optionally an SRID number.
Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the
srid on the geometry.
Examples
See Also
8.3.12 ST_Polygon
Synopsis
Description
Returns a polygon built from the given LineString and sets the spatial reference system from the srid.
ST_Polygon is similar to ST_MakePolygon Variant 1 with the addition of setting the SRID.
To create polygons with holes use ST_MakePolygon Variant 2 and then ST_SetSRID.
Note
This function does not accept MultiLineStrings. Use ST_LineMerge to generate a LineString, or ST_Dump to extract
LineStrings.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
Examples
Create a 2D polygon.
SELECT ST_AsText( ST_Polygon('LINESTRING(75 29, 77 29, 77 29, 75 29)'::geometry, 4326) );
-- result --
POLYGON((75 29, 77 29, 77 29, 75 29))
Create a 3D polygon.
SELECT ST_AsEWKT( ST_Polygon( ST_GeomFromEWKT('LINESTRING(75 29 1, 77 29 2, 77 29 3, 75 29 ←-
1)'), 4326) );
-- result --
SRID=4326;POLYGON((75 29 1, 77 29 2, 77 29 3, 75 29 1))
See Also
8.3.13 ST_TileEnvelope
ST_TileEnvelope — Creates a rectangular Polygon in Web Mercator (SRID:3857) using the XYZ tile system.
Synopsis
Description
Creates a rectangular Polygon giving the extent of a tile in the XYZ tile system. The tile is specifed by the zoom level Z and
the XY index of the tile in the grid at that level. Can be used to define the tile bounds required by ST_AsMVTGeom to convert
geometry into the MVT tile coordinate space.
By default, the tile envelope is in the Web Mercator coordinate system (SRID:3857) using the standard range of the Web Mercator
system (-20037508.342789, 20037508.342789). This is the most common coordinate system used for MVT tiles. The optional
bounds parameter can be used to generate tiles in any coordinate system. It is a geometry that has the SRID and extent of the
"Zoom Level zero" square within which the XYZ tile system is inscribed.
The optional margin parameter can be used to expand a tile by the given percentage. E.g. margin=0.125 expands the tile by
12.5%, which is equivalent to buffer=512 when the tile extent size is 4096, as used in ST_AsMVTGeom. This is useful to create
a tile buffer to include data lying outside of the tile’s visible area, but whose existence affects the tile rendering. For example, a
city name (a point) could be near an edge of a tile, so its label should be rendered on two tiles, even though the point is located
in the visible area of just one tile. Using expanded tiles in a query will include the city point in both tiles. Use a negative value
to shrink the tile instead. Values less than -0.5 are prohibited because that would eliminate the tile completely. Do not specify a
margin when using with ST_AsMVTGeom. See the example for ST_AsMVT.
Enhanced: 3.1.0 Added margin parameter.
Availability: 3.0.0
st_astext
------------------------------
POLYGON((-10018754.1713945 0,-10018754.1713945 10018754.1713945,0 10018754.1713945,0 ←-
0,-10018754.1713945 0))
st_astext
------------------------------------------------------
POLYGON((-135 45,-135 67.5,-90 67.5,-90 45,-135 45))
See Also
ST_MakeEnvelope
8.3.14 ST_HexagonGrid
ST_HexagonGrid — Returns a set of hexagons and cell indices that completely cover the bounds of the geometry argument.
PostGIS 3.3.2 Manual 95 / 902
Synopsis
Description
Starts with the concept of a hexagon tiling of the plane. (Not a hexagon tiling of the globe, this is not the H3 tiling scheme.) For
a given planar SRS, and a given edge size, starting at the origin of the SRS, there is one unique hexagonal tiling of the plane,
Tiling(SRS, Size). This function answers the question: what hexagons in a given Tiling(SRS, Size) overlap with a given bounds.
The SRS for the output hexagons is the SRS provided by the bounds geometry.
Doubling or tripling the edge size of the hexagon generates a new parent tiling that fits with the origin tiling. Unfortunately, it is
not possible to generate parent hexagon tilings that the child tiles perfectly fit inside.
PostGIS 3.3.2 Manual 96 / 902
Availability: 3.1.0
To do a point summary against a hexagonal tiling, generate a hexagon grid using the extent of the points as the bounds, then
spatially join to that grid.
SELECT COUNT(*), hexes.geom
FROM
ST_HexagonGrid(
10000,
ST_SetSRID(ST_EstimatedExtent('pointtable', 'geom'), 3857)
) AS hexes
INNER JOIN
pointtable AS pts
ON ST_Intersects(pts.geom, hexes.geom)
GROUP BY hexes.geom;
If we generate a set of hexagons for each polygon boundary and filter out those that do not intersect their hexagons, we end up
with a tiling for each polygon.
PostGIS 3.3.2 Manual 97 / 902
Tiling states results in a hexagon coverage of each state, and multiple hexagons overlapping at the borders between states.
Note
The LATERAL keyword is implied for set-returning functions when referring to a prior table in the FROM list. So CROSS
JOIN LATERAL, CROSS JOIN, or just plain , are equivalent constructs for this example.
See Also
8.3.15 ST_Hexagon
ST_Hexagon — Returns a single hexagon, using the provided edge size and cell coordinate within the hexagon grid space.
Synopsis
Description
Uses the same hexagon tiling concept as ST_HexagonGrid, but generates just one hexagon at the desired cell coordinate. Op-
tionally, can adjust origin coordinate of the tiling, the default origin is at 0,0.
Hexagons are generated with no SRID set, so use ST_SetSRID to set the SRID to the one you expect.
Availability: 3.1.0
POLYGON((-1 0,-0.5
-0.866025403784439,0.5
-0.866025403784439,1
0,0.5
0.866025403784439,-0.5
0.866025403784439,-1 0))
See Also
8.3.16 ST_SquareGrid
ST_SquareGrid — Returns a set of grid squares and cell indices that completely cover the bounds of the geometry argument.
Synopsis
Description
Starts with the concept of a square tiling of the plane. For a given planar SRS, and a given edge size, starting at the origin of the
SRS, there is one unique square tiling of the plane, Tiling(SRS, Size). This function answers the question: what grids in a given
Tiling(SRS, Size) overlap with a given bounds.
The SRS for the output squares is the SRS provided by the bounds geometry.
Doubling or edge size of the square generates a new parent tiling that perfectly fits with the original tiling. Standard web map
tilings in mercator are just powers-of-two square grids in the mercator plane.
Availability: 3.1.0
The grid will fill the whole bounds of the country, so if you want just squares that touch the country you will have to filter
afterwards with ST_Intersects.
WITH grid AS (
SELECT (ST_SquareGrid(1, ST_Transform(geom,4326))).*
FROM admin0 WHERE name = 'Canada'
)
SELEcT ST_AsText(geom)
FROM grid
PostGIS 3.3.2 Manual 99 / 902
To do a point summary against a square tiling, generate a square grid using the extent of the points as the bounds, then spatially
join to that grid. Note the estimated extent might be off from actual extent, so be cautious and at very least make sure you’ve
analyzed your table.
SELECT COUNT(*), squares.geom
FROM
pointtable AS pts
INNER JOIN
ST_SquareGrid(
1000,
ST_SetSRID(ST_EstimatedExtent('pointtable', 'geom'), 3857)
) AS squares
ON ST_Intersects(pts.geom, squares.geom)
GROUP BY squares.geom
This yields the same result as the first example but will be slower for a large number of points
SELECT COUNT(*), squares.geom
FROM
pointtable AS pts
INNER JOIN
ST_SquareGrid(
1000,
pts.geom
) AS squares
ON ST_Intersects(pts.geom, squares.geom)
GROUP BY squares.geom
See Also
8.3.17 ST_Square
ST_Square — Returns a single square, using the provided edge size and cell coordinate within the square grid space.
Synopsis
Description
Uses the same square tiling concept as ST_SquareGrid, but generates just one square at the desired cell coordinate. Optionally,
can adjust origin coordinate of the tiling, the default origin is at 0,0.
Squares are generated with no SRID set, so use ST_SetSRID to set the SRID to the one you expect.
Availability: 3.1.0
PostGIS 3.3.2 Manual 100 / 902
See Also
8.3.18 ST_Letters
ST_Letters — Returns the input letters rendered as geometry with a default start position at the origin and default text height of
100.
Synopsis
Description
Uses a built-in font to render out a string as a multipolygon geometry. The default text height is 100.0, the distance from the
bottom of a descender to the top of a capital. The default start position places the start of the baseline at the origin. Over-riding
the font involves passing in a json map, with a character as the key, and base64 encoded TWKB for the font shape, with the fonts
having a height of 1000 units from the bottom of the descenders to the tops of the capitals.
The text is generated at the origin by default, so to reposition and resize the text, first apply the ST_Scale function and then
apply the ST_Translate function.
Availability: 3.3.0
See Also
8.4.1 GeometryType
Synopsis
Description
Returns the type of the geometry as a string. Eg: ’LINESTRING’, ’POLYGON’, ’MULTIPOINT’, etc.
OGC SPEC s2.1.1.1 - Returns the name of the instantiable subtype of Geometry of which this Geometry instance is a member.
The name of the instantiable subtype of Geometry is returned as a string.
Note
This function also indicates if the geometry is measured, by returning a string of the form ’POINTM’.
Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
See Also
ST_GeometryType
8.4.2 ST_Boundary
Synopsis
Description
Returns the closure of the combinatorial boundary of this Geometry. The combinatorial boundary is defined as described in
section 3.12.3.2 of the OGC SPEC. Because the result of this function is a closure, and hence topologically closed, the resulting
boundary can be represented using representational geometry primitives as discussed in the OGC SPEC, section 3.12.2.
Performed by the GEOS module
Note
Prior to 2.0.0, this function throws an exception if used with GEOMETRYCOLLECTION. From 2.0.0 up it will return
NULL instead (unsupported input).
PostGIS 3.3.2 Manual 103 / 902
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. OGC SPEC s2.1.1.1
This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1.17
Examples
--Using a 3d polygon
SELECT ST_AsEWKT(ST_Boundary(ST_GeomFromEWKT('POLYGON((1 1 1,0 0 1, -1 1 1, 1 1 1))')));
PostGIS 3.3.2 Manual 104 / 902
st_asewkt
-----------------------------------
LINESTRING(1 1 1,0 0 1,-1 1 1,1 1 1)
--Using a 3d multilinestring
SELECT ST_AsEWKT(ST_Boundary(ST_GeomFromEWKT('MULTILINESTRING((1 1 1,0 0 0.5, -1 1 1),(1 1 ←-
0.5,0 0 0.5, -1 1 0.5, 1 1 0.5) )')));
st_asewkt
----------
MULTIPOINT((-1 1 1),(1 1 0.75))
See Also
8.4.3 ST_BoundingDiagonal
Synopsis
Description
Returns the diagonal of the supplied geometry’s bounding box as a LineString. The diagonal is a 2-point LineString with the
minimum values of each dimension in its start point and the maximum values in its end point. If the input geometry is empty, the
diagonal line is a LINESTRING EMPTY.
The optional fits parameter specifies if the best fit is needed. If false, the diagonal of a somewhat larger bounding box can
be accepted (which is faster to compute for geometries with many vertices). In either case, the bounding box of the returned
diagonal line always covers the input geometry.
The returned geometry retains the SRID and dimensionality (Z and M presence) of the input geometry.
Note
In degenerate cases (i.e. a single vertex in input) the returned linestring will be formally invalid (no interior). The result
is still topologically valid.
Availability: 2.2.0
Examples
See Also
8.4.4 ST_CoordDim
Synopsis
Description
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
SELECT ST_CoordDim(ST_Point(1,2));
--result--
2
See Also
ST_NDims
PostGIS 3.3.2 Manual 106 / 902
8.4.5 ST_Dimension
Synopsis
Description
Return the topological dimension of this Geometry object, which must be less than or equal to the coordinate dimension. OGC
SPEC s2.1.1.1 - returns 0 for POINT, 1 for LINESTRING, 2 for POLYGON, and the largest dimension of the components of a
GEOMETRYCOLLECTION. If the dimension is unknown (e.g. for an empty GEOMETRYCOLLECTION) 0 is returned.
Note
Prior to 2.0.0, this function throws an exception if used with empty geometry.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
See Also
ST_NDims
8.4.6 ST_Dump
Synopsis
Description
A set-returning function (SRF) that extracts the components of a geometry. It returns a set of geometry_dump rows, each
containing a geometry (geom field) and an array of integers (path field).
For an atomic geometry type (POINT,LINESTRING,POLYGON) a single record is returned with an empty path array and the
input geometry as geom. For a collection or multi-geometry a record is returned for each of the collection components, and the
path denotes the position of the component inside the collection.
ST_Dump is useful for expanding geometries. It is the inverse of a ST_Collect / GROUP BY, in that it creates new rows. For
example it can be use to expand MULTIPOLYGONS into POLYGONS.
Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
Availability: PostGIS 1.0.0RC1. Requires PostgreSQL 7.3 or higher.
Note
Prior to 1.3.4, this function crashes if used with geometries that contain CURVES. This is fixed in 1.3.4+
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Standard Examples
)') ) AS p_geom ) AS a;
path | geom_ewkt
------+------------------------------------------
1 | POLYGON((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0))
2 | POLYGON((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0))
3 | POLYGON((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0))
4 | POLYGON((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0))
5 | POLYGON((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0))
6 | POLYGON((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1))
-- TIN --
SELECT (g.gdump).path, ST_AsEWKT((g.gdump).geom) as wkt
FROM
(SELECT
ST_Dump( ST_GeomFromEWKT('TIN (((
0 0 0,
0 0 1,
0 1 0,
0 0 0
)), ((
0 0 0,
0 1 0,
1 1 0,
0 0 0
))
)') ) AS gdump
) AS g;
-- result --
path | wkt
------+-------------------------------------
{1} | TRIANGLE((0 0 0,0 0 1,0 1 0,0 0 0))
{2} | TRIANGLE((0 0 0,0 1 0,1 1 0,0 0 0))
See Also
8.4.7 ST_DumpPoints
Synopsis
Description
A set-returning function (SRF) that extracts the coordinates (vertices) of a geometry. It returns a set of geometry_dump rows,
each containing a geometry (geom field) and an array of integers (path field).
• the geom field POINTs represent the coordinates of the supplied geometry.
• the path field (an integer[]) is an index enumerating the coordinate positions in the elements of the supplied geometry. The
indices are 1-based. For example, for a LINESTRING the paths are {i} where i is the nth coordinate in the LINESTRING.
For a POLYGON the paths are {i,j} where i is the ring number (1 is outer; inner rings follow) and j is the coordinate position
in the ring.
PostGIS 3.3.2 Manual 109 / 902
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
(SELECT
'GEOMETRYCOLLECTION(
POINT ( 0 1 ),
LINESTRING ( 0 3, 3 4 ),
POLYGON (( 2 0, 2 3, 0 2, 2 0 )),
POLYGON (( 3 0, 3 3, 6 3, 6 0, 3 0 ),
( 5 1, 4 2, 5 2, 5 1 )),
MULTIPOLYGON (
(( 0 5, 0 8, 4 8, 4 5, 0 5 ),
( 1 6, 3 6, 2 7, 1 6 )),
(( 5 4, 5 8, 6 7, 5 4 ))
)
)'::geometry AS geom
) AS g
) j;
path | st_astext
-----------+------------
{1,1} | POINT(0 1)
{2,1} | POINT(0 3)
{2,2} | POINT(3 4)
{3,1,1} | POINT(2 0)
{3,1,2} | POINT(2 3)
{3,1,3} | POINT(0 2)
{3,1,4} | POINT(2 0)
{4,1,1} | POINT(3 0)
{4,1,2} | POINT(3 3)
{4,1,3} | POINT(6 3)
{4,1,4} | POINT(6 0)
{4,1,5} | POINT(3 0)
{4,2,1} | POINT(5 1)
{4,2,2} | POINT(4 2)
{4,2,3} | POINT(5 2)
{4,2,4} | POINT(5 1)
{5,1,1,1} | POINT(0 5)
{5,1,1,2} | POINT(0 8)
{5,1,1,3} | POINT(4 8)
{5,1,1,4} | POINT(4 5)
{5,1,1,5} | POINT(0 5)
{5,1,2,1} | POINT(1 6)
{5,1,2,2} | POINT(3 6)
{5,1,2,3} | POINT(2 7)
{5,1,2,4} | POINT(1 6)
{5,2,1,1} | POINT(5 4)
{5,2,1,2} | POINT(5 8)
{5,2,1,3} | POINT(6 7)
{5,2,1,4} | POINT(5 4)
(29 rows)
) AS g;
-- result --
path | wkt
---------+--------------
{1,1,1} | POINT(0 0 0)
{1,1,2} | POINT(0 0 1)
{1,1,3} | POINT(0 1 1)
{1,1,4} | POINT(0 1 0)
{1,1,5} | POINT(0 0 0)
{2,1,1} | POINT(0 0 0)
{2,1,2} | POINT(0 1 0)
{2,1,3} | POINT(1 1 0)
{2,1,4} | POINT(1 0 0)
{2,1,5} | POINT(0 0 0)
{3,1,1} | POINT(0 0 0)
{3,1,2} | POINT(1 0 0)
{3,1,3} | POINT(1 0 1)
{3,1,4} | POINT(0 0 1)
{3,1,5} | POINT(0 0 0)
{4,1,1} | POINT(1 1 0)
{4,1,2} | POINT(1 1 1)
{4,1,3} | POINT(1 0 1)
{4,1,4} | POINT(1 0 0)
{4,1,5} | POINT(1 1 0)
{5,1,1} | POINT(0 1 0)
{5,1,2} | POINT(0 1 1)
{5,1,3} | POINT(1 1 1)
{5,1,4} | POINT(1 1 0)
{5,1,5} | POINT(0 1 0)
{6,1,1} | POINT(0 0 1)
{6,1,2} | POINT(1 0 1)
{6,1,3} | POINT(1 1 1)
{6,1,4} | POINT(0 1 1)
{6,1,5} | POINT(0 0 1)
(30 rows)
-- Triangle --
SELECT (g.gdump).path, ST_AsText((g.gdump).geom) as wkt
FROM
(SELECT
ST_DumpPoints( ST_GeomFromEWKT('TRIANGLE ((
0 0,
0 9,
9 0,
0 0
))') ) AS gdump
) AS g;
-- result --
path | wkt
------+------------
{1} | POINT(0 0)
{2} | POINT(0 9)
{3} | POINT(9 0)
{4} | POINT(0 0)
-- TIN --
SELECT (g.gdump).path, ST_AsEWKT((g.gdump).geom) as wkt
FROM
(SELECT
ST_DumpPoints( ST_GeomFromEWKT('TIN (((
0 0 0,
PostGIS 3.3.2 Manual 112 / 902
0 0 1,
0 1 0,
0 0 0
)), ((
0 0 0,
0 1 0,
1 1 0,
0 0 0
))
)') ) AS gdump
) AS g;
-- result --
path | wkt
---------+--------------
{1,1,1} | POINT(0 0 0)
{1,1,2} | POINT(0 0 1)
{1,1,3} | POINT(0 1 0)
{1,1,4} | POINT(0 0 0)
{2,1,1} | POINT(0 0 0)
{2,1,2} | POINT(0 1 0)
{2,1,3} | POINT(1 1 0)
{2,1,4} | POINT(0 0 0)
(8 rows)
See Also
8.4.8 ST_DumpSegments
Synopsis
Description
A set-returning function (SRF) that extracts the segments of a geometry. It returns a set of geometry_dump rows, each containing
a geometry (geom field) and an array of integers (path field).
• the geom field LINESTRINGs represent the segments of the supplied geometry.
• the path field (an integer[]) is an index enumerating the segment start point positions in the elements of the supplied
geometry. The indices are 1-based. For example, for a LINESTRING the paths are {i} where i is the nth segment start
point in the LINESTRING. For a POLYGON the paths are {i,j} where i is the ring number (1 is outer; inner rings follow)
and j is the segment start point position in the ring.
Availability: 3.2.0
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
-- Triangle --
SELECT path, ST_AsText(geom)
FROM (
SELECT (ST_DumpSegments(g.geom)).*
FROM (SELECT 'TRIANGLE((
0 0,
0 9,
9 0,
0 0
))'::geometry AS geom
) AS g
) j;
-- TIN --
SELECT path, ST_AsEWKT(geom)
FROM (
SELECT (ST_DumpSegments(g.geom)).*
FROM (SELECT 'TIN(((
0 0 0,
0 0 1,
0 1 0,
0 0 0
)), ((
0 0 0,
0 1 0,
1 1 0,
0 0 0
))
)'::geometry AS geom
PostGIS 3.3.2 Manual 114 / 902
) AS g
) j;
See Also
8.4.9 ST_DumpRings
ST_DumpRings — Returns a set of geometry_dump rows for the exterior and interior rings of a Polygon.
Synopsis
Description
A set-returning function (SRF) that extracts the rings of a polygon. It returns a set of geometry_dump rows, each containing a
geometry (geom field) and an array of integers (path field).
The geom field contains each ring as a POLYGON. The path field is an integer array of length 1 containing the polygon ring
index. The exterior ring (shell) has index 0. The interior rings (holes) have indices of 1 and higher.
Note
This only works for POLYGON geometries. It does not work for MULTIPOLYGONS
Examples
See Also
8.4.10 ST_EndPoint
Synopsis
Description
Returns the last point of a LINESTRING or CIRCULARLINESTRING geometry as a POINT. Returns NULL if the input is not
a LINESTRING or CIRCULARLINESTRING.
Note
Changed: 2.0.0 no longer works with single geometry MultiLineStrings. In older versions of PostGIS a single-line Multi-
LineString would work with this function and return the end point. In 2.0.0 it returns NULL like any other MultiLineString.
The old behavior was an undocumented feature, but people who assumed they had their data stored as LINESTRING
may experience these returning NULL in 2.0.0.
PostGIS 3.3.2 Manual 116 / 902
Examples
See Also
ST_PointN, ST_StartPoint
8.4.11 ST_Envelope
Synopsis
Description
Returns the double-precision (float8) minimum bounding box for the supplied geometry, as a geometry. The polygon is defined
by the corner points of the bounding box ((MINX, MINY), (MINX, MAXY), (MAXX, MAXY), (MAXX, MINY), (MINX, MINY)).
(PostGIS will add a ZMIN/ZMAX coordinate as well).
Degenerate cases (vertical lines, points) will return a geometry of lower dimension than POLYGON, ie. POINT or LINESTRING.
Availability: 1.5.0 behavior changed to output double precision instead of float4
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.1
Examples
SELECT ST_AsText(ST_Envelope(
ST_Collect(
ST_GeomFromText('LINESTRING(55 75,125 150)'),
ST_Point(20, 80))
PostGIS 3.3.2 Manual 118 / 902
)) As wktenv;
wktenv
-----------
POLYGON((20 75,20 150,125 150,125 75,20 75))
See Also
8.4.12 ST_ExteriorRing
Synopsis
Description
Returns a LINESTRING representing the exterior ring (shell) of a POLYGON. Returns NULL if the geometry is not a polygon.
Note
This function does not support MULTIPOLYGONs. For MULTIPOLYGONs use in conjunction with ST_GeometryN or
ST_Dump
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. 2.1.5.1
Examples
--3d Example
SELECT ST_AsEWKT(
ST_ExteriorRing(
ST_GeomFromEWKT('POLYGON((0 0 1, 1 1 1, 1 2 1, 1 1 1, 0 0 1))')
)
);
st_asewkt
---------
LINESTRING(0 0 1,1 1 1,1 2 1,1 1 1,0 0 1)
PostGIS 3.3.2 Manual 119 / 902
See Also
8.4.13 ST_GeometryN
Synopsis
Description
Return the 1-based Nth element geometry of an input geometry which is a GEOMETRYCOLLECTION, MULTIPOINT, MUL-
TILINESTRING, MULTICURVE, MULTI)POLYGON, or POLYHEDRALSURFACE. Otherwise, returns NULL.
Note
Index is 1-based as for OGC specs since version 0.8.0. Previous versions implemented this as 0-based instead.
Note
To extract all elements of a geometry, ST_Dump is more efficient and works for atomic geometries.
Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
Changed: 2.0.0 Prior versions would return NULL for singular geometries. This was changed to return the geometry for
ST_GeometryN(..,1) case.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Standard Examples
n | geomewkt
---+-----------------------------------------
1 | POINT(1 2 7)
2 | POINT(3 4 7)
3 | POINT(5 6 7)
4 | POINT(8 9 10)
1 | CIRCULARSTRING(2.5 2.5,4.5 2.5,3.5 3.5)
2 | LINESTRING(10 11,12 11)
geom_ewkt
------------------------------------------
POLYGON((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0))
-- TIN --
SELECT ST_AsEWKT(ST_GeometryN(geom,2)) as wkt
FROM
(SELECT
ST_GeomFromEWKT('TIN (((
0 0 0,
0 0 1,
0 1 0,
0 0 0
)), ((
0 0 0,
0 1 0,
1 1 0,
0 0 0
))
)') AS geom
) AS g;
-- result --
wkt
-------------------------------------
TRIANGLE((0 0 0,0 1 0,1 1 0,0 0 0))
PostGIS 3.3.2 Manual 121 / 902
See Also
ST_Dump, ST_NumGeometries
8.4.14 ST_GeometryType
Synopsis
Description
Returns the type of the geometry as a string. EG: ’ST_LineString’, ’ST_Polygon’,’ST_MultiPolygon’ etc. This function differs
from GeometryType(geometry) in the case of the string and ST in front that is returned, as well as the fact that it will not indicate
whether the geometry is measured.
Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.
Examples
0 1 0,
0 0 0
)), ((
0 0 0,
0 1 0,
1 1 0,
0 0 0
))
)') AS geom
) AS g;
result
--------
ST_Tin
See Also
GeometryType
8.4.15 ST_HasArc
Synopsis
Description
Examples
See Also
ST_CurveToLine, ST_LineToCurve
8.4.16 ST_InteriorRingN
Synopsis
Description
Returns the Nth interior ring (hole) of a POLYGON geometry as a LINESTRING. The index starts at 1. Returns NULL if the
geometry is not a polygon or the index is out of range.
Note
This function does not support MULTIPOLYGONs. For MULTIPOLYGONs use in conjunction with ST_GeometryN or
ST_Dump
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
Examples
See Also
8.4.17 ST_IsClosed
ST_IsClosed — Tests if a LineStrings’s start and end points are coincident. For a PolyhedralSurface tests if it is closed (volu-
metric).
Synopsis
Description
Returns TRUE if the LINESTRING’s start and end points are coincident. For Polyhedral Surfaces, reports if the surface is areal
(open) or volumetric (closed).
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
Note
SQL-MM defines the result of ST_IsClosed(NULL) to be 0, while PostGIS returns NULL.
-- A cube --
SELECT ST_IsClosed(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 ←-
0 0)),
((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)),
((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)),
((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )'));
st_isclosed
-------------
t
PostGIS 3.3.2 Manual 125 / 902
st_isclosed
-------------
f
See Also
ST_IsRing
8.4.18 ST_IsCollection
Synopsis
Description
Returns TRUE if the geometry type of the argument a geometry collection type. Collection types are the following:
• GEOMETRYCOLLECTION
• MULTI{POINT,POLYGON,LINESTRING,CURVE,SURFACE}
• COMPOUNDCURVE
Note
This function analyzes the type of the geometry. This means that it will return TRUE on collections that are empty or
that contain a single element.
Examples
See Also
ST_NumGeometries
8.4.19 ST_IsEmpty
Synopsis
Description
Returns true if this Geometry is an empty geometry. If true, then this Geometry represents an empty geometry collection,
polygon, point etc.
Note
SQL-MM defines the result of ST_IsEmpty(NULL) to be 0, while PostGIS returns NULL.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.1
Warning
Changed: 2.0.0 In prior versions of PostGIS ST_GeomFromText(’GEOMETRYCOLLECTION(EMPTY)’) was allowed.
This is now illegal in PostGIS 2.0.0 to better conform with SQL/MM standards
Examples
st_isempty
------------
f
(1 row)
8.4.20 ST_IsPolygonCCW
ST_IsPolygonCCW — Tests if Polygons have exterior rings oriented counter-clockwise and interior rings oriented clockwise.
Synopsis
Description
Returns true if all polygonal components of the input geometry use a counter-clockwise orientation for their exterior ring, and a
clockwise direction for all interior rings.
Returns true if the geometry has no polygonal components.
PostGIS 3.3.2 Manual 128 / 902
Note
Closed linestrings are not considered polygonal components, so you would still get a true return by passing a single
closed linestring no matter its orientation.
Note
If a polygonal geometry does not use reversed orientation for interior rings (i.e., if one or more interior rings are oriented
in the same direction as an exterior ring) then both ST_IsPolygonCW and ST_IsPolygonCCW will return false.
Availability: 2.4.0
See Also
8.4.21 ST_IsPolygonCW
ST_IsPolygonCW — Tests if Polygons have exterior rings oriented clockwise and interior rings oriented counter-clockwise.
Synopsis
Description
Returns true if all polygonal components of the input geometry use a clockwise orientation for their exterior ring, and a counter-
clockwise direction for all interior rings.
Returns true if the geometry has no polygonal components.
Note
Closed linestrings are not considered polygonal components, so you would still get a true return by passing a single
closed linestring no matter its orientation.
Note
If a polygonal geometry does not use reversed orientation for interior rings (i.e., if one or more interior rings are oriented
in the same direction as an exterior ring) then both ST_IsPolygonCW and ST_IsPolygonCCW will return false.
Availability: 2.4.0
See Also
8.4.22 ST_IsRing
Synopsis
Description
Returns TRUE if this LINESTRING is both ST_IsClosed (ST_StartPoint((g )) ~= ST_Endpoint((g ))) and ST_IsSimple
(does not self intersect).
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. 2.1.5.1
Note
SQL-MM defines the result of ST_IsRing(NULL) to be 0, while PostGIS returns NULL.
Examples
See Also
8.4.23 ST_IsSimple
Synopsis
Description
Returns true if this Geometry has no anomalous geometric points, such as self-intersection or self-tangency. For more information
on the OGC’s definition of geometry simplicity and validity, refer to "Ensuring OpenGIS compliancy of geometries"
Note
SQL-MM defines the result of ST_IsSimple(NULL) to be 0, while PostGIS returns NULL.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.1
Examples
See Also
ST_IsValid
8.4.24 ST_M
Synopsis
Description
Return the M coordinate of a Point, or NULL if not available. Input must be a Point.
Note
This is not (yet) part of the OGC spec, but is listed here to complete the point coordinate extractor function list.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
Examples
See Also
8.4.25 ST_MemSize
Synopsis
Description
Returns the amount of memory space (in bytes) the geometry takes.
This complements the PostgreSQL built-in database object functions pg_column_size, pg_size_pretty, pg_relation_size, pg_total_relation
Note
pg_relation_size which gives the byte size of a table may return byte size lower than ST_MemSize. This is because
pg_relation_size does not add toasted table contribution and large geometries are stored in TOAST tables.
pg_total_relation_size - includes, the table, the toasted tables, and the indexes.
pg_column_size returns how much space a geometry would take in a column considering compression, so may be
lower than ST_MemSize
PostGIS 3.3.2 Manual 132 / 902
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Changed: 2.2.0 name changed to ST_MemSize to follow naming convention.
Examples
--Return how much byte space Boston takes up in our Mass data set
SELECT pg_size_pretty(SUM(ST_MemSize(geom))) as totgeomsum,
pg_size_pretty(SUM(CASE WHEN town = 'BOSTON' THEN ST_MemSize(geom) ELSE 0 END)) As bossum,
CAST(SUM(CASE WHEN town = 'BOSTON' THEN ST_MemSize(geom) ELSE 0 END)*1.00 /
SUM(ST_MemSize(geom))*100 As numeric(10,2)) As perbos
FROM towns;
---
73
8.4.26 ST_NDims
Synopsis
Description
Returns the coordinate dimension of the geometry. PostGIS supports 2 - (x,y) , 3 - (x,y,z) or 2D with measure - x,y,m, and 4 - 3D
with measure space x,y,z,m
Examples
See Also
8.4.27 ST_NPoints
Synopsis
Description
Note
Prior to 1.3.4, this function crashes if used with geometries that contain CURVES. This is fixed in 1.3.4+
Examples
--Polygon in 3D space
SELECT ST_NPoints(ST_GeomFromEWKT('LINESTRING(77.29 29.07 1,77.42 29.26 0,77.27 29.31 ←-
-1,77.29 29.07 3)'))
--result
4
PostGIS 3.3.2 Manual 134 / 902
See Also
ST_NumPoints
8.4.28 ST_NRings
Synopsis
Description
If the geometry is a polygon or multi-polygon returns the number of rings. Unlike NumInteriorRings, it counts the outer rings as
well.
Examples
See Also
ST_NumInteriorRings
8.4.29 ST_NumGeometries
Synopsis
Description
Returns the number of Geometries. If geometry is a GEOMETRYCOLLECTION (or MULTI*) return the number of geometries,
for single geometries will return 1, otherwise return NULL.
Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
Changed: 2.0.0 In prior versions this would return NULL if the geometry was not a collection/MULTI type. 2.0.0+ now returns
1 for single geometries e.g POLYGON, LINESTRING, POINT.
PostGIS 3.3.2 Manual 135 / 902
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
--Prior versions would have returned NULL for this -- in 2.0.0 this returns 1
SELECT ST_NumGeometries(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 ←-
29.31,77.29 29.07)'));
--result
1
See Also
ST_GeometryN, ST_Multi
8.4.30 ST_NumInteriorRings
Synopsis
Description
Return the number of interior rings of a polygon geometry. Return NULL if the geometry is not a polygon.
Examples
See Also
ST_NumInteriorRing, ST_InteriorRingN
8.4.31 ST_NumInteriorRing
ST_NumInteriorRing — Returns the number of interior rings (holes) of a Polygon. Aias for ST_NumInteriorRings
Synopsis
See Also
ST_NumInteriorRings, ST_InteriorRingN
8.4.32 ST_NumPatches
ST_NumPatches — Return the number of faces on a Polyhedral Surface. Will return null for non-polyhedral geometries.
Synopsis
Description
Return the number of faces on a Polyhedral Surface. Will return null for non-polyhedral geometries. This is an alias for
ST_NumGeometries to support MM naming. Faster to use ST_NumGeometries if you don’t care about MM convention.
Availability: 2.0.0
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM ISO/IEC 13249-3: 8.5
Examples
See Also
ST_GeomFromEWKT, ST_NumGeometries
8.4.33 ST_NumPoints
Synopsis
Description
Return the number of points in an ST_LineString or ST_CircularString value. Prior to 1.4 only works with linestrings as the
specs state. From 1.4 forward this is an alias for ST_NPoints which returns number of vertexes for not just linestrings. Consider
using ST_NPoints instead which is multi-purpose and works with many geometry types.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
Examples
See Also
ST_NPoints
8.4.34 ST_PatchN
Synopsis
Description
Returns the 1-based Nth geometry (face) if the geometry is a POLYHEDRALSURFACE or POLYHEDRALSURFACEM. Oth-
erwise, returns NULL. This returns the same answer as ST_GeometryN for PolyhedralSurfaces. Using ST_GeometryN is faster.
Note
Index is 1-based.
PostGIS 3.3.2 Manual 138 / 902
Note
If you want to extract all elements of a geometry ST_Dump is more efficient.
Availability: 2.0.0
This method implements the SQL/MM specification. SQL-MM ISO/IEC 13249-3: 8.5
Examples
geomewkt
---+-----------------------------------------
POLYGON((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0))
See Also
8.4.35 ST_PointN
ST_PointN — Returns the Nth point in the first LineString or circular LineString in a geometry.
Synopsis
Description
Return the Nth point in a single linestring or circular linestring in the geometry. Negative values are counted backwards from the
end of the LineString, so that -1 is the last point. Returns NULL if there is no linestring in the geometry.
Note
Index is 1-based as for OGC specs since version 0.8.0. Backward indexing (negative index) is not in OGC Previous
versions implemented this as 0-based instead.
PostGIS 3.3.2 Manual 139 / 902
Note
If you want to get the Nth point of each LineString in a MultiLineString, use in conjunction with ST_Dump
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
Note
Changed: 2.0.0 no longer works with single geometry multilinestrings. In older versions of PostGIS -- a single line
multilinestring would work happily with this function and return the start point. In 2.0.0 it just returns NULL like any other
multilinestring.
Changed: 2.3.0 : negative indexing available (-1 is last point)
Examples
st_astext
------------
POINT(0 0)
POINT(1 1)
POINT(2 2)
(3 rows)
st_astext
------------
POINT(3 2)
(1 row)
SELECT ST_AsText(f)
FROM ST_GeomFromText('LINESTRING(0 0 0, 1 1 1, 2 2 2)') AS g
,ST_PointN(g, -2) AS f; -- 1 based index
st_astext
-----------------
POINT Z (1 1 1)
(1 row)
PostGIS 3.3.2 Manual 140 / 902
See Also
ST_NPoints
8.4.36 ST_Points
Synopsis
Description
Returns a MultiPoint containing all the coordinates of a geometry. Duplicate points are preserved, including the start and end
points of ring geometries. (If desired, duplicate points can be removed by calling ST_RemoveRepeatedPoints on the result).
To obtain information about the position of each coordinate in the parent geometry use ST_DumpPoints.
M and Z coordinates are preserved if present.
Examples
--result
MULTIPOINT Z ((30 10 4),(10 30 5),(40 40 6),(30 10 4))
See Also
ST_RemoveRepeatedPoints, ST_DumpPoints
8.4.37 ST_StartPoint
Synopsis
Description
Returns the first point of a LINESTRING or CIRCULARLINESTRING geometry as a POINT. Returns NULL if the input is not
a LINESTRING or CIRCULARLINESTRING.
Note
Enhanced: 3.2.0 returns a point for all geometries. Prior behavior returns NULLs if input was not a LineString.
Changed: 2.0.0 no longer works with single geometry MultiLineStrings. In older versions of PostGIS a single-line
MultiLineString would work happily with this function and return the start point. In 2.0.0 it just returns NULL like any
other MultiLineString. The old behavior was an undocumented feature, but people who assumed they had their data
stored as LINESTRING may experience these returning NULL in 2.0.0.
Examples
See Also
ST_EndPoint, ST_PointN
8.4.38 ST_Summary
Synopsis
Description
• M: has M coordinate
• Z: has Z coordinate
• B: has a cached bounding box
• G: is geodetic (geography)
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Availability: 1.2.2
Enhanced: 2.0.0 added support for geography
Enhanced: 2.1.0 S flag to denote if has a known spatial reference system
Enhanced: 2.2.0 Added support for TIN and Curves
Examples
See Also
8.4.39 ST_X
Synopsis
Description
Return the X coordinate of the point, or NULL if not available. Input must be a point.
Note
To get the minimum and maximum X value of geometry coordinates use the functions ST_XMin and ST_XMax.
Examples
See Also
8.4.40 ST_Y
Synopsis
Description
Return the Y coordinate of the point, or NULL if not available. Input must be a point.
Note
To get the minimum and maximum Y value of geometry coordinates use the functions ST_YMin and ST_YMax.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
Examples
See Also
8.4.41 ST_Z
Synopsis
Description
Return the Z coordinate of the point, or NULL if not available. Input must be a point.
Note
To get the minimum and maximum Z value of geometry coordinates use the functions ST_ZMin and ST_ZMax.
Examples
See Also
8.4.42 ST_Zmflag
Synopsis
Description
Examples
st_zmflag
-----------
1
See Also
8.5.1 ST_AddPoint
Synopsis
Description
Adds a point to a LineString before the index position (using a 0-based index). If the position parameter is omitted or is -1
the point is appended to the end of the LineString.
Availability: 1.1.0
Examples
st_asewkt
----------
LINESTRING(0 0 1,1 1 1,1 2 3)
Guarantee all lines in a table are closed by adding the start point of each line to the end of the line only for those that are not
closed.
UPDATE sometable
SET geom = ST_AddPoint(geom, ST_StartPoint(geom))
FROM sometable
WHERE ST_IsClosed(geom) = false;
PostGIS 3.3.2 Manual 147 / 902
See Also
ST_RemovePoint, ST_SetPoint
8.5.2 ST_CollectionExtract
ST_CollectionExtract — Given a geometry collection, returns a multi-geometry containing only elements of a specified type.
Synopsis
Description
• 1 == POINT
• 2 == LINESTRING
• 3 == POLYGON
For atomic geometry inputs, the geometry is retured unchanged if the input type matches the requested type. Otherwise, the
result is an EMPTY geometry of the specified type. If required, these can be converted to multi-geometries using ST_Multi.
Warning
MultiPolygon results are not checked for validity. If the polygon components are adjacent or overlapping the result will
be invalid. (For example, this can occur when applying this function to an ST_Split result.) This situation can be checked
with ST_IsValid and repaired with ST_MakeValid.
Availability: 1.5.0
Note
Prior to 1.5.3 this function returned atomic inputs unchanged, no matter type. In 1.5.3 non-matching single geometries
returned a NULL result. In 2.0.0 non-matching single geometries return an EMPTY result of the requested type.
Examples
See Also
8.5.3 ST_CollectionHomogenize
Synopsis
Description
• Atomic geometries are returned unchanged. If required, these can be converted to a multi-geometry using ST_Multi.
Warning
This function does not ensure that the result is valid. In particular, a collection containing adjacent or overlapping Poly-
gons will create an invalid MultiPolygon. This situation can be checked with ST_IsValid and repaired with ST_MakeValid.
Availability: 2.0.0
PostGIS 3.3.2 Manual 149 / 902
Examples
st_astext
------------
POINT(0 0)
st_astext
------------
POINT(0 0)
st_astext
---------------------
MULTIPOINT((0 0),(1 1))
st_astext
---------------------
GEOMETRYCOLLECTION(POINT(0 0),LINESTRING(1 1,2 2))
st_astext
---------------------
MULTIPOLYGON(((10 50,50 50,50 10,10 10,10 50)),((90 50,90 10,50 10,50 50,90 50)))
See Also
8.5.4 ST_CurveToLine
Synopsis
Description
Availability: 1.3.0
Enhanced: 2.4.0 added support for max-deviation and max-angle tolerance, and for symmetric output.
Enhanced: 3.0.0 implemented a minimum number of segments per linearized arc to prevent topological collapse.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
Examples
--Result --
LINESTRING(220268 150415,220269.95064912 150416.539364228,220271.823415575 ←-
150418.17258804,220273.613787707 150419.895736857,
220275.317452352 150421.704659462,220276.930305234 150423.594998003,220278.448460847 ←-
150425.562198489,
220279.868261823 150427.60152176,220281.186287736 150429.708054909,220282.399363347 ←-
150431.876723113,
220283.50456625 150434.10230186,220284.499233914 150436.379429536,220285.380970099 ←-
150438.702620341,220286.147650624 150441.066277505,
220286.797428488 150443.464706771,220287.328738321 150445.892130112,220287.740300149 ←-
150448.342699654,
220288.031122486 150450.810511759,220288.200504713 150453.289621251,220288.248038775 ←-
150455.77405574,
220288.173610157 150458.257830005,220287.977398166 150460.734960415,220287.659875492 ←-
150463.199479347,
220287.221807076 150465.64544956,220286.664248262 150468.066978495,220285.988542259 ←-
150470.458232479,220285.196316903 150472.81345077,
220284.289480732 150475.126959442,220283.270218395 150477.39318505,220282.140985384 ←-
150479.606668057,
PostGIS 3.3.2 Manual 151 / 902
--3d example
SELECT ST_AsEWKT(ST_CurveToLine(ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 ←-
150505 2,220227 150406 3)')));
Output
------
LINESTRING(220268 150415 1,220269.95064912 150416.539364228 1.0181172856673,
220271.823415575 150418.17258804 1.03623457133459,220273.613787707 150419.895736857 ←-
1.05435185700189,....AD INFINITUM ....
220225.586657991 150406.324522731 1.32611114201132,220227 150406 3)
See Also
ST_LineToCurve
8.5.5 ST_Scroll
Synopsis
Description
Changes the start/end point of a closed LineString to the given vertex point.
Availability: 3.2.0
Examples
st_asewkt
----------
SRID=4326;LINESTRING(5 5 4 2,0 0 0 1,10 0 2 0,5 5 4 2)
PostGIS 3.3.2 Manual 153 / 902
See Also
ST_Normalize
8.5.6 ST_FlipCoordinates
Synopsis
Description
Returns a version of the given geometry with X and Y axis flipped. Useful for fixing geometries which contain coordinates
expressed as latitude/longitude (Y,X).
Availability: 2.0.0
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Example
See Also
ST_SwapOrdinates
8.5.7 ST_Force2D
Synopsis
Description
Forces the geometries into a "2-dimensional mode" so that all output representations will only have the X and Y coordinates.
This is useful for force OGC-compliant output (since OGC only specifies 2-D geometries).
Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.
Changed: 2.1.0. Up to 2.0.x this was called ST_Force_2D.
Examples
SELECT ST_AsEWKT(ST_Force2D(ST_GeomFromEWKT('CIRCULARSTRING(1 1 2, 2 3 2, 4 5 2, 6 7 2, 5 6 ←-
2)')));
st_asewkt
-------------------------------------
CIRCULARSTRING(1 1,2 3,4 5,6 7,5 6)
SELECT ST_AsEWKT(ST_Force2D('POLYGON((0 0 2,0 5 2,5 0 2,0 0 2),(1 1 2,3 1 2,1 3 2,1 1 2)) ←-
'));
st_asewkt
----------------------------------------------
POLYGON((0 0,0 5,5 0,0 0),(1 1,3 1,1 3,1 1))
See Also
ST_Force3D
8.5.8 ST_Force3D
ST_Force3D — Force the geometries into XYZ mode. This is an alias for ST_Force3DZ.
Synopsis
Description
Forces the geometries into XYZ mode. This is an alias for ST_Force3DZ. If a geometry has no Z component, then a Zvalue Z
coordinate is tacked on.
Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.
Changed: 2.1.0. Up to 2.0.x this was called ST_Force_3D.
Changed: 3.1.0. Added support for supplying a non-zero Z value.
Examples
SELECT ST_AsEWKT(ST_Force3D('POLYGON((0 0,0 5,5 0,0 0),(1 1,3 1,1 3,1 1))'));
st_asewkt
--------------------------------------------------------------
POLYGON((0 0 0,0 5 0,5 0 0,0 0 0),(1 1 0,3 1 0,1 3 0,1 1 0))
See Also
8.5.9 ST_Force3DZ
Synopsis
Description
Forces the geometries into XYZ mode. If a geometry has no Z component, then a Zvalue Z coordinate is tacked on.
Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.
Changed: 2.1.0. Up to 2.0.x this was called ST_Force_3DZ.
Changed: 3.1.0. Added support for supplying a non-zero Z value.
Examples
SELECT ST_AsEWKT(ST_Force3DZ('POLYGON((0 0,0 5,5 0,0 0),(1 1,3 1,1 3,1 1))'));
PostGIS 3.3.2 Manual 156 / 902
st_asewkt
--------------------------------------------------------------
POLYGON((0 0 0,0 5 0,5 0 0,0 0 0),(1 1 0,3 1 0,1 3 0,1 1 0))
See Also
8.5.10 ST_Force3DM
Synopsis
Description
Forces the geometries into XYM mode. If a geometry has no M component, then a Mvalue M coordinate is tacked on. If it has
a Z component, then Z is removed
Changed: 2.1.0. Up to 2.0.x this was called ST_Force_3DM.
Changed: 3.1.0. Added support for supplying a non-zero M value.
Examples
SELECT ST_AsEWKT(ST_Force3DM('POLYGON((0 0 1,0 5 1,5 0 1,0 0 1),(1 1 1,3 1 1,1 3 1,1 1 1)) ←-
'));
st_asewkt
---------------------------------------------------------------
POLYGONM((0 0 0,0 5 0,5 0 0,0 0 0),(1 1 0,3 1 0,1 3 0,1 1 0))
See Also
8.5.11 ST_Force4D
Synopsis
Description
Forces the geometries into XYZM mode. Zvalue and Mvalue is tacked on for missing Z and M dimensions, respectively.
Changed: 2.1.0. Up to 2.0.x this was called ST_Force_4D.
Changed: 3.1.0. Added support for supplying non-zero Z and M values.
Examples
st_asewkt
--------------------------------------------------------------------------------------
MULTILINESTRING((0 0 0 1,0 5 0 2,5 0 0 3,0 0 0 4),(1 1 0 1,3 1 0 1,1 3 0 1,1 1 0 1))
See Also
8.5.12 ST_ForcePolygonCCW
ST_ForcePolygonCCW — Orients all exterior rings counter-clockwise and all interior rings clockwise.
Synopsis
Description
Forces (Multi)Polygons to use a counter-clockwise orientation for their exterior ring, and a clockwise orientation for their interior
rings. Non-polygonal geometries are returned unchanged.
Availability: 2.4.0
See Also
8.5.13 ST_ForceCollection
Synopsis
Description
Converts the geometry into a GEOMETRYCOLLECTION. This is useful for simplifying the WKB representation.
Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.
Availability: 1.2.2, prior to 1.3.4 this function will crash with Curves. This is fixed in 1.3.4+
Changed: 2.1.0. Up to 2.0.x this was called ST_Force_Collection.
Examples
st_asewkt
----------------------------------------------------------------------------------
GEOMETRYCOLLECTION(POLYGON((0 0 1,0 5 1,5 0 1,0 0 1),(1 1 1,3 1 1,1 3 1,1 1 1)))
-- POLYHEDRAL example --
SELECT ST_AsEWKT(ST_ForceCollection('POLYHEDRALSURFACE(((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),
((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),
((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)))'))
st_asewkt
----------------------------------------------------------------------------------
PostGIS 3.3.2 Manual 159 / 902
GEOMETRYCOLLECTION(
POLYGON((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
POLYGON((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),
POLYGON((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
POLYGON((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
POLYGON((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),
POLYGON((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1))
)
See Also
8.5.14 ST_ForcePolygonCW
ST_ForcePolygonCW — Orients all exterior rings clockwise and all interior rings counter-clockwise.
Synopsis
Description
Forces (Multi)Polygons to use a clockwise orientation for their exterior ring, and a counter-clockwise orientation for their interior
rings. Non-polygonal geometries are returned unchanged.
Availability: 2.4.0
See Also
8.5.15 ST_ForceSFS
ST_ForceSFS — Force the geometries to use SFS 1.1 geometry types only.
Synopsis
Description
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
8.5.16 ST_ForceRHR
ST_ForceRHR — Force the orientation of the vertices in a polygon to follow the Right-Hand-Rule.
Synopsis
Description
Forces the orientation of the vertices in a polygon to follow a Right-Hand-Rule, in which the area that is bounded by the polygon
is to the right of the boundary. In particular, the exterior ring is orientated in a clockwise direction and the interior rings in a
counter-clockwise direction. This function is a synonym for ST_ForcePolygonCW
Note
The above definition of the Right-Hand-Rule conflicts with definitions used in other contexts. To avoid confusion, it is
recommended to use ST_ForcePolygonCW.
Examples
SELECT ST_AsEWKT(
ST_ForceRHR(
'POLYGON((0 0 2, 5 0 2, 0 5 2, 0 0 2),(1 1 2, 1 3 2, 3 1 2, 1 1 2))'
)
);
st_asewkt
--------------------------------------------------------------
POLYGON((0 0 2,0 5 2,5 0 2,0 0 2),(1 1 2,3 1 2,1 3 2,1 1 2))
(1 row)
See Also
8.5.17 ST_ForceCurve
Synopsis
Description
Turns a geometry into its curved representation, if applicable: lines become compoundcurves, multilines become multicurves
polygons become curvepolygons multipolygons become multisurfaces. If the geometry input is already a curved representation
returns back same as input.
Availability: 2.2.0
Examples
SELECT ST_AsText(
ST_ForceCurve(
'POLYGON((0 0 2, 5 0 2, 0 5 2, 0 0 2),(1 1 2, 1 3 2, 3 1 2, 1 1 2))'::geometry
)
);
st_astext
----------------------------------------------------------------------
CURVEPOLYGON Z ((0 0 2,5 0 2,0 5 2,0 0 2),(1 1 2,1 3 2,3 1 2,1 1 2))
(1 row)
See Also
ST_LineToCurve
8.5.18 ST_LineToCurve
Synopsis
Description
Converts plain LINESTRING/POLYGON to CIRCULAR STRINGs and Curved Polygons. Note much fewer points are needed
to describe the curved equivalent.
Note
If the input LINESTRING/POLYGON is not curved enough to clearly represent a curve, the function will return the same
input geometry.
Availability: 1.3.0
Examples
-- 2D Example
SELECT ST_AsText(ST_LineToCurve(foo.geom)) As curvedastext,ST_AsText(foo.geom) As ←-
non_curvedastext
FROM (SELECT ST_Buffer('POINT(1 3)'::geometry, 3) As geom) As foo;
curvedatext non_curvedastext
--------------------------------------------------------------------|--------------------------------
--3D example
SELECT ST_AsText(ST_LineToCurve(geom)) As curved, ST_AsText(geom) AS not_curved
FROM (SELECT ST_Translate(ST_Force3D(ST_Boundary(ST_Buffer(ST_Point(1,3), 2,2))),0,0,3) AS ←-
geom) AS foo;
curved | not_curved
------------------------------------------------------+----------------------------------------------
See Also
ST_CurveToLine
PostGIS 3.3.2 Manual 163 / 902
8.5.19 ST_Multi
Synopsis
Description
Returns the geometry as a MULTI* geometry collection. If the geometry is already a collection, it is returned unchanged.
Examples
See Also
ST_AsText
8.5.20 ST_Normalize
Synopsis
Description
Returns the geometry in its normalized/canonical form. May reorder vertices in polygon rings, rings in a polygon, elements in a
multi-geometry complex.
Mostly only useful for testing purposes (comparing expected and obtained results).
Availability: 2.3.0
Examples
SELECT ST_AsText(ST_Normalize(ST_GeomFromText(
'GEOMETRYCOLLECTION(
POINT(2 3),
MULTILINESTRING((0 0, 1 1),(2 2, 3 3)),
POLYGON(
(0 10,0 0,10 0,10 10,0 10),
(4 2,2 2,2 4,4 4,4 2),
(6 8,8 8,8 6,6 6,6 8)
)
)'
)));
PostGIS 3.3.2 Manual 164 / 902
st_astext
-----------------------------------------------------------------------------------------------------
GEOMETRYCOLLECTION(POLYGON((0 0,0 10,10 10,10 0,0 0),(6 6,8 6,8 8,6 8,6 6),(2 2,4 2,4 4,2 ←-
4,2 2)),MULTILINESTRING((2 2,3 3),(0 0,1 1)),POINT(2 3))
(1 row)
See Also
ST_Equals,
8.5.21 ST_QuantizeCoordinates
Synopsis
geometry ST_QuantizeCoordinates ( geometry g , int prec_x , int prec_y , int prec_z , int prec_m );
Description
ST_QuantizeCoordinates determines the number of bits (N) required to represent a coordinate value with a specified
number of digits after the decimal point, and then sets all but the N most significant bits to zero. The resulting coordinate value
will still round to the original value, but will have improved compressiblity. This can result in a significant disk usage reduction
provided that the geometry column is using a compressible storage type. The function allows specification of a different number
of digits after the decimal point in each dimension; unspecified dimensions are assumed to have the precision of the x dimension.
Negative digits are interpreted to refer digits to the left of the decimal point, (i.e., prec_x=-2 will preserve coordinate values
to the nearest 100.
The coordinates produced by ST_QuantizeCoordinates are independent of the geometry that contains those coordinates
and the relative position of those coordinates within the geometry. As a result, existing topological relationships between geome-
tries are unaffected by use of this function. The function may produce invalid geometry when it is called with a number of digits
lower than the intrinsic precision of the geometry.
Availability: 2.5.0
Technical Background
PostGIS stores all coordinate values as double-precision floating point integers, which can reliably represent 15 significant digits.
However, PostGIS may be used to manage data that intrinsically has fewer than 15 significant digits. An example is TIGER
data, which is provided as geographic coordinates with six digits of precision after the decimal point (thus requiring only nine
significant digits of longitude and eight significant digits of latitude.)
When 15 significant digits are available, there are many possible representations of a number with 9 significant digits. A double
precision floating point number uses 52 explicit bits to represent the significand (mantissa) of the coordinate. Only 30 bits are
needed to represent a mantissa with 9 significant digits, leaving 22 insignificant bits; we can set their value to anything we
like and still end up with a number that rounds to our input value. For example, the value 100.123456 can be represented by
the floating point numbers closest to 100.123456000000, 100.123456000001, and 100.123456432199. All are equally valid,
in that ST_AsText(geom, 6) will return the same result with any of these inputs. As we can set these bits to any value,
ST_QuantizeCoordinates sets the 22 insignificant bits to zero. For a long coordinate sequence this creates a pattern of
blocks of consecutive zeros that is compressed by PostgreSQL more effeciently.
Note
Only the on-disk size of the geometry is potentially affected by ST_QuantizeCoordinates. ST_MemSize, which
reports the in-memory usage of the geometry, will return the the same value regardless of the disk space used by a
geometry.
PostGIS 3.3.2 Manual 165 / 902
Examples
15 | 01010000005f9a72083cdd5e405f9a72083cdd5e40 | POINT(123.456789123456 ←-
123.456789123456)
14 | 01010000005f9a72083cdd5e405f9a72083cdd5e40 | POINT(123.456789123456 ←-
123.456789123456)
13 | 01010000005f9a72083cdd5e405f9a72083cdd5e40 | POINT(123.456789123456 ←-
123.456789123456)
12 | 01010000005c9a72083cdd5e405c9a72083cdd5e40 | POINT(123.456789123456 ←-
123.456789123456)
11 | 0101000000409a72083cdd5e40409a72083cdd5e40 | POINT(123.456789123456 ←-
123.456789123456)
10 | 0101000000009a72083cdd5e40009a72083cdd5e40 | POINT(123.456789123455 ←-
123.456789123455)
9 | 0101000000009072083cdd5e40009072083cdd5e40 | POINT(123.456789123418 ←-
123.456789123418)
8 | 0101000000008072083cdd5e40008072083cdd5e40 | POINT(123.45678912336 ←-
123.45678912336)
7 | 0101000000000070083cdd5e40000070083cdd5e40 | POINT(123.456789121032 ←-
123.456789121032)
6 | 0101000000000040083cdd5e40000040083cdd5e40 | POINT(123.456789076328 ←-
123.456789076328)
5 | 0101000000000000083cdd5e40000000083cdd5e40 | POINT(123.456789016724 ←-
123.456789016724)
4 | 0101000000000000003cdd5e40000000003cdd5e40 | POINT(123.456787109375 ←-
123.456787109375)
3 | 0101000000000000003cdd5e40000000003cdd5e40 | POINT(123.456787109375 ←-
123.456787109375)
2 | 01010000000000000038dd5e400000000038dd5e40 | POINT(123.45654296875 ←-
123.45654296875)
1 | 01010000000000000000dd5e400000000000dd5e40 | POINT(123.453125 123.453125)
0 | 01010000000000000000dc5e400000000000dc5e40 | POINT(123.4375 123.4375)
-1 | 01010000000000000000c05e400000000000c05e40 | POINT(123 123)
-2 | 01010000000000000000005e400000000000005e40 | POINT(120 120)
-3 | 010100000000000000000058400000000000005840 | POINT(96 96)
-4 | 010100000000000000000058400000000000005840 | POINT(96 96)
-5 | 010100000000000000000058400000000000005840 | POINT(96 96)
-6 | 010100000000000000000058400000000000005840 | POINT(96 96)
-7 | 010100000000000000000058400000000000005840 | POINT(96 96)
-8 | 010100000000000000000058400000000000005840 | POINT(96 96)
-9 | 010100000000000000000058400000000000005840 | POINT(96 96)
-10 | 010100000000000000000058400000000000005840 | POINT(96 96)
-11 | 010100000000000000000058400000000000005840 | POINT(96 96)
-12 | 010100000000000000000058400000000000005840 | POINT(96 96)
-13 | 010100000000000000000058400000000000005840 | POINT(96 96)
-14 | 010100000000000000000058400000000000005840 | POINT(96 96)
PostGIS 3.3.2 Manual 166 / 902
See Also
ST_SnapToGrid
8.5.22 ST_RemovePoint
Synopsis
Description
Removes a point from a LineString, given its index (0-based). Useful for turning a closed line (ring) into an open linestring.
Enhanced: 3.2.0
Availability: 1.1.0
Examples
Guarantees no lines are closed by removing the end point of closed lines (rings). Assumes geom is of type LINESTRING
UPDATE sometable
SET geom = ST_RemovePoint(geom, ST_NPoints(geom) - 1)
FROM sometable
WHERE ST_IsClosed(geom);
See Also
8.5.23 ST_RemoveRepeatedPoints
Synopsis
Description
Returns a version of the given geometry with duplicate consecutive points removed. The function processes only (Multi)LineStrings,
(Multi)Polygons and MultiPoints but it can be called with any kind of geometry. Elements of GeometryCollections are processed
individually. The endpoints of LineStrings are preserved.
If the tolerance parameter is provided, vertices within the tolerance distance of one another are considered to be duplicates.
Enhanced: 3.2.0
Availability: 2.2.0
Examples
See Also
ST_Simplify
8.5.24 ST_Reverse
Synopsis
Description
Can be used on any geometry and reverses the order of the vertexes.
Enhanced: 2.4.0 support for curves was introduced.
Examples
8.5.25 ST_Segmentize
ST_Segmentize — Return a modified geometry/geography having no segment longer than the given distance.
Synopsis
Description
Returns a modified geometry having no segment longer than the given max_segment_length. Distance computation is
performed in 2d only. For geometry, length units are in units of spatial reference. For geography, units are in meters.
Availability: 1.2.2
Enhanced: 3.0.0 Segmentize geometry now uses equal length segments
Enhanced: 2.3.0 Segmentize geography now uses equal length segments
Enhanced: 2.1.0 support for geography was introduced.
Changed: 2.1.0 As a result of the introduction of geography support: The construct SELECT ST_Segmentize(’LINESTRING(1
2, 3 4)’,0.5); will result in ambiguous function error. You need to have properly typed object e.g. a geometry/-
geography column, use ST_GeomFromText, ST_GeogFromText or SELECT ST_Segmentize(’LINESTRING(1 2, 3
4)’::geometry,0.5);
Note
This will only increase segments. It will not lengthen segments shorter than max length
PostGIS 3.3.2 Manual 169 / 902
Examples
SELECT ST_AsText(ST_Segmentize(
ST_GeomFromText('MULTILINESTRING((-29 -27,-30 -29.7,-36 -31,-45 -33),(-45 -33,-46 -32))')
,5)
);
st_astext
-------------------------------------------------------------------------------------------------- ←
See Also
ST_LineSubstring
8.5.26 ST_SetPoint
Synopsis
Description
Replace point N of linestring with given point. Index is 0-based.Negative index are counted backwards, so that -1 is last point.
This is especially useful in triggers when trying to maintain relationship of joints when one vertex moves.
Availability: 1.1.0
Updated 2.3.0 : negative indexing
Examples
---Change last point in a line string (lets play with 3d linestring this time)
SELECT ST_AsEWKT(ST_SetPoint(foo.geom, ST_NumPoints(foo.geom) - 1, ST_GeomFromEWKT('POINT ←-
(-1 1 3)')))
PostGIS 3.3.2 Manual 170 / 902
See Also
8.5.27 ST_ShiftLongitude
ST_ShiftLongitude — Shifts the longitude coordinates of a geometry between -180..180 and 0..360.
Synopsis
Description
Reads every point/vertex in a geometry, and shifts its longitude coordinate from -180..0 to 180..360 and vice versa if between
these ranges. This function is symmetrical so the result is a 0..360 representation of a -180..180 data and a -180..180 representa-
tion of a 0..360 data.
Note
This is only useful for data with coordinates in longitude/latitude; e.g. SRID 4326 (WGS 84 geographic)
Warning
Pre-1.3.4 bug prevented this from working for MULTIPOINT. 1.3.4+ works with MULTIPOINT as well.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
PostGIS 3.3.2 Manual 171 / 902
Examples
st_astext
----------
POINT(-90 0)
st_astext
----------
POINT(270 0)
st_astext
----------
LINESTRING(174 12,-178 13)
See Also
ST_WrapX
8.5.28 ST_WrapX
Synopsis
Description
This function splits the input geometries and then moves every resulting component falling on the right (for negative ’move’) or
on the left (for positive ’move’) of given ’wrap’ line in the direction specified by the ’move’ parameter, finally re-unioning the
pieces together.
Note
This is useful to "recenter" long-lat input to have features of interest not spawned from one side to the other.
Examples
See Also
ST_ShiftLongitude
8.5.29 ST_SnapToGrid
Synopsis
geometry ST_SnapToGrid(geometry geomA, float originX, float originY, float sizeX, float sizeY);
geometry ST_SnapToGrid(geometry geomA, float sizeX, float sizeY);
geometry ST_SnapToGrid(geometry geomA, float size);
geometry ST_SnapToGrid(geometry geomA, geometry pointOrigin, float sizeX, float sizeY, float sizeZ, float sizeM);
Description
Variant 1,2,3: Snap all points of the input geometry to the grid defined by its origin and cell size. Remove consecutive points
falling on the same cell, eventually returning NULL if output points are not enough to define a geometry of the given type.
Collapsed geometries in a collection are stripped from it. Useful for reducing precision.
Variant 4: Introduced 1.1.0 - Snap all points of the input geometry to the grid defined by its origin (the second argument, must
be a point) and cell sizes. Specify 0 as size for any dimension you don’t want to snap to a grid.
Note
The returned geometry might lose its simplicity (see ST_IsSimple).
Note
Before release 1.1.0 this function always returned a 2d geometry. Starting at 1.1.0 the returned geometry will have same
dimensionality as the input one with higher dimension values untouched. Use the version taking a second geometry
argument to define all grid dimensions.
Availability: 1.0.0RC1
Availability: 1.1.0 - Z and M support
Examples
SELECT ST_AsText(ST_SnapToGrid(
ST_GeomFromText('LINESTRING(1.1115678 2.123, 4.111111 3.2374897, 4.11112 3.23748667) ←-
'),
0.001)
);
st_astext
-------------------------------------
LINESTRING(1.112 2.123,4.111 3.237)
--Snap a 4d geometry
SELECT ST_AsEWKT(ST_SnapToGrid(
ST_GeomFromEWKT('LINESTRING(-1.1115678 2.123 2.3456 1.11111,
4.111111 3.2374897 3.1234 1.1111, -1.11111112 2.123 2.3456 1.1111112)'),
ST_GeomFromEWKT('POINT(1.12 2.22 3.2 4.4444)'),
0.1, 0.1, 0.1, 0.01) );
st_asewkt
------------------------------------------------------------------------------
LINESTRING(-1.08 2.12 2.3 1.1144,4.12 3.22 3.1 1.1144,-1.08 2.12 2.3 1.1144)
--With a 4d geometry - the ST_SnapToGrid(geom,size) only touches x and y coords but keeps m ←-
and z the same
SELECT ST_AsEWKT(ST_SnapToGrid(ST_GeomFromEWKT('LINESTRING(-1.1115678 2.123 3 2.3456,
4.111111 3.2374897 3.1234 1.1111)'),
0.01) );
st_asewkt
---------------------------------------------------------
LINESTRING(-1.11 2.12 3 2.3456,4.11 3.24 3.1234 1.1111)
See Also
8.5.30 ST_Snap
ST_Snap — Snap segments and vertices of input geometry to vertices of a reference geometry.
Synopsis
Description
Snaps the vertices and segments of a geometry to another Geometry’s vertices. A snap distance tolerance is used to control where
snapping is performed. The result geometry is the input geometry with the vertices snapped. If no snapping occurs then the input
geometry is returned unchanged.
Snapping one geometry to another can improve robustness for overlay operations by eliminating nearly-coincident edges (which
cause problems during noding and intersection calculation).
Too much snapping can result in invalid topology being created, so the number and location of snapped vertices is decided using
heuristics to determine when it is safe to snap. This can result in some potential snaps being omitted, however.
PostGIS 3.3.2 Manual 174 / 902
Note
The returned geometry might lose its simplicity (see ST_IsSimple) and validity (see ST_IsValid).
Examples
See Also
ST_SnapToGrid
8.5.31 ST_SwapOrdinates
ST_SwapOrdinates — Returns a version of the given geometry with given ordinate values swapped.
Synopsis
Description
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Example
-- Scale M value by 2
SELECT ST_AsText(
ST_SwapOrdinates(
ST_Scale(
ST_SwapOrdinates(g,'xm'),
2, 1
),
'xm')
) FROM ( SELECT 'POINT ZM (0 0 0 2)'::geometry g ) foo;
st_astext
--------------------
POINT ZM (0 0 0 4)
See Also
ST_FlipCoordinates
8.6.1 ST_IsValid
Synopsis
Description
Tests if an ST_Geometry value is well-formed and valid in 2D according to the OGC rules. For geometries with 3 and 4
dimensions, the validity is still only tested in 2 dimensions. For geometries that are invalid, a PostgreSQL NOTICE is emitted
providing details of why it is not valid.
For the version with the flags parameter, supported values are documented in ST_IsValidDetail This version does not print a
NOTICE explaining invalidity.
For more information on the definition of geometry validity, refer to Section 4.4
Note
SQL-MM defines the result of ST_IsValid(NULL) to be 0, while PostGIS returns NULL.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
Note
Neither OGC-SFS nor SQL-MM specifications include a flag argument for ST_IsValid. The flag is a PostGIS extension.
Examples
See Also
8.6.2 ST_IsValidDetail
ST_IsValidDetail — Returns a valid_detail row stating if a geometry is valid or if not a reason and a location.
Synopsis
Description
Returns a valid_detail row, containing a boolean (valid) stating if a geometry is valid, a varchar (reason) stating a
reason why it is invalid and a geometry (location) pointing out where it is invalid.
Useful to improve on the combination of ST_IsValid and ST_IsValidReason to generate a detailed report of invalid geometries.
The optional flags parameter is a bitfield. It can have the following values:
Examples
--simple example
SELECT * FROM ST_IsValidDetail('LINESTRING(220227 150406,2220227 150407,222020 150410)');
See Also
ST_IsValid, ST_IsValidReason
PostGIS 3.3.2 Manual 180 / 902
8.6.3 ST_IsValidReason
Synopsis
Description
Examples
gid | validity_info
------+--------------------------
5330 | Self-intersection [32 5]
5340 | Self-intersection [42 5]
5350 | Self-intersection [52 5]
PostGIS 3.3.2 Manual 181 / 902
--simple example
SELECT ST_IsValidReason('LINESTRING(220227 150406,2220227 150407,222020 150410)');
st_isvalidreason
------------------
Valid Geometry
See Also
ST_IsValid, ST_Summary
8.6.4 ST_MakeValid
Synopsis
Description
The function attempts to create a valid representation of a given invalid geometry without losing any of the input vertices. Valid
geometries are returned unchanged.
Supported inputs are: POINTS, MULTIPOINTS, LINESTRINGS, MULTILINESTRINGS, POLYGONS, MULTIPOLYGONS
and GEOMETRYCOLLECTIONS containing any mix of them.
In case of full or partial dimensional collapses, the output geometry may be a collection of lower-to-equal dimension geometries,
or a geometry of lower dimension.
Single polygons may become multi-geometries in case of self-intersections.
The params argument can be used to supply an options string to select the method to use for building valid geometry. The
options string is in the format "method=linework|structure keepcollapsed=true|false".
The "method" key has two values.
• "linework" is the original algorithm, and builds valid geometries by first extracting all lines, noding that linework together, then
building a value output from the linework.
• "structure" is an algorithm that distinguishes between interior and exterior rings, building new geometry by unioning exterior
rings, and then differencing all interior rings.
The "keepcollapsed" key is only valid for the "structure" algorithm, and takes a value of "true" or "false". When set to "false",
geometry components that collapse to a lower dimensionality, for example a one-point linestring would be dropped.
Performed by the GEOS module.
Availability: 2.0.0
Enhanced: 2.0.1, speed improvements
Enhanced: 2.1.0, added support for GEOMETRYCOLLECTION and MULTIPOINT.
Enhanced: 3.1.0, added removal of Coordinates with NaN values.
Enhanced: 3.2.0, added algorithm options, ’linework’ and ’structure’ which requires GEOS >= 3.10.0.
Examples
PostGIS 3.3.2 Manual 183 / 902
Examples
SELECT ST_AsText(ST_MakeValid(
'LINESTRING(0 0, 0 0)',
'method=structure keepcollapsed=true'
));
st_astext
------------
POINT(0 0)
SELECT ST_AsText(ST_MakeValid(
'LINESTRING(0 0, 0 0)',
'method=structure keepcollapsed=false'
));
st_astext
------------------
LINESTRING EMPTY
See Also
8.7.1 ST_SetSRID
Synopsis
Description
Sets the SRID on a geometry to a particular integer value. Useful in constructing bounding boxes for queries.
Note
This function does not transform the geometry coordinates in any way - it simply sets the meta data defining the spatial
reference system the geometry is assumed to be in. Use ST_Transform if you want to transform the geometry into a
new projection.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
Examples
-- Mark a point as WGS 84 long lat and then transform to web mercator (Spherical Mercator) --
SELECT ST_Transform(ST_SetSRID(ST_Point(-123.365556, 48.428611),4326),3785) As spere_merc;
-- the ewkt representation (wrap with ST_AsEWKT) -
SRID=3785;POINT(-13732990.8753491 6178458.96425423)
See Also
8.7.2 ST_SRID
Synopsis
Description
Returns the spatial reference identifier for the ST_Geometry as defined in spatial_ref_sys table. Section 4.5
Note
spatial_ref_sys table is a table that catalogs all spatial reference systems known to PostGIS and is used for transforma-
tions from one spatial reference system to another. So verifying you have the right spatial reference system identifier is
important if you plan to ever transform your geometries.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.1
Examples
See Also
8.7.3 ST_Transform
ST_Transform — Return a new geometry with coordinates transformed to a different spatial reference system.
Synopsis
Description
Returns a new geometry with its coordinates transformed to a different spatial reference system. The destination spatial reference
to_srid may be identified by a valid SRID integer parameter (i.e. it must exist in the spatial_ref_sys table). Alterna-
tively, a spatial reference defined as a PROJ.4 string can be used for to_proj and/or from_proj, however these methods are
not optimized. If the destination spatial reference system is expressed with a PROJ.4 string instead of an SRID, the SRID of the
output geometry will be set to zero. With the exception of functions with from_proj, input geometries must have a defined
SRID.
ST_Transform is often confused with ST_SetSRID. ST_Transform actually changes the coordinates of a geometry from one
spatial reference system to another, while ST_SetSRID() simply changes the SRID identifier of the geometry.
Note
Requires PostGIS be compiled with PROJ support. Use PostGIS_Full_Version to confirm you have PROJ support
compiled in.
Note
If using more than one transformation, it is useful to have a functional index on the commonly used transformations to
take advantage of index usage.
Note
Prior to 1.3.4, this function crashes if used with geometries that contain CURVES. This is fixed in 1.3.4+
Examples
wgs_geom
---------------------------
POLYGON((-71.1776848522251 42.3902896512902,-71.1776843766326 42.3903829478009,
-71.1775844305465 42.3903826677917,-71.1775825927231 42.3902893647987,-71.177684
8522251 42.3902896512902));
(1 row)
st_asewkt
--------------------------------------------------------------------------------------
SRID=4326;CIRCULARSTRING(-71.1776848522251 42.3902896512902 1,-71.1776843766326 ←-
42.3903829478009 2,
-71.1775844305465 42.3903826677917 3,
-71.1775825927231 42.3902893647987 3,-71.1776848522251 42.3902896512902 4)
Example of creating a partial functional index. For tables where you are not sure all the geometries will be filled in, its best to use
a partial index that leaves out null geometries which will both conserve space and make your index smaller and more efficient.
CREATE INDEX idx_geom_26986_parcels
ON parcels
USING gist
(ST_Transform(geom, 26986))
WHERE geom IS NOT NULL;
Sometimes coordinate transformation involving a grid-shift can fail, for example if PROJ.4 has not been built with grid-shift files
or the coordinate does not lie within the range for which the grid shift is defined. By default, PostGIS will throw an error if a
grid shift file is not present, but this behavior can be configured on a per-SRID basis either by testing different to_proj values
of PROJ.4 text, or altering the proj4text value within the spatial_ref_sys table.
For example, the proj4text parameter +datum=NAD87 is a shorthand form for the following +nadgrids parameter:
PostGIS 3.3.2 Manual 190 / 902
+nadgrids=@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat
The @ prefix means no error is reported if the files are not present, but if the end of the list is reached with no file having been
appropriate (ie. found and overlapping) then an error is issued.
If, conversely, you wanted to ensure that at least the standard files were present, but that if all files were scanned without a hit a
null transformation is applied you could use:
+nadgrids=@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat,null
The null grid shift file is a valid grid shift file covering the whole world and applying no shift. So for a complete example, if you
wanted to alter PostGIS so that transformations to SRID 4267 that didn’t lie within the correct range did not throw an ERROR,
you would use the following:
UPDATE spatial_ref_sys SET proj4text = '+proj=longlat +ellps=clrk66 +nadgrids=@conus, ←-
@alaska,@ntv2_0.gsb,@ntv1_can.dat,null +no_defs' WHERE srid = 4267;
See Also
8.8.1.1 ST_BdPolyFromText
ST_BdPolyFromText — Construct a Polygon given an arbitrary collection of closed linestrings as a MultiLineString Well-Known
text representation.
Synopsis
Description
Construct a Polygon given an arbitrary collection of closed linestrings as a MultiLineString Well-Known text representation.
Note
Throws an error if WKT is not a MULTILINESTRING. Throws an error if output is a MULTIPOLYGON; use
ST_BdMPolyFromText in that case, or see ST_BuildArea() for a postgis-specific approach.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2
Performed by the GEOS module.
Availability: 1.1.0
See Also
ST_BuildArea, ST_BdMPolyFromText
PostGIS 3.3.2 Manual 191 / 902
8.8.1.2 ST_BdMPolyFromText
ST_BdMPolyFromText — Construct a MultiPolygon given an arbitrary collection of closed linestrings as a MultiLineString text
representation Well-Known text representation.
Synopsis
Description
Construct a Polygon given an arbitrary collection of closed linestrings, polygons, MultiLineStrings as Well-Known text repre-
sentation.
Note
Throws an error if WKT is not a MULTILINESTRING. Forces MULTIPOLYGON output even when result is really only
composed by a single POLYGON; use ST_BdPolyFromText if you’re sure a single POLYGON will result from operation,
or see ST_BuildArea() for a postgis-specific approach.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2
Performed by the GEOS module.
Availability: 1.1.0
See Also
ST_BuildArea, ST_BdPolyFromText
8.8.1.3 ST_GeogFromText
ST_GeogFromText — Return a specified geography value from Well-Known Text representation or extended (WKT).
Synopsis
Description
Returns a geography object from the well-known text or extended well-known representation. SRID 4326 is assumed if unspec-
ified. This is an alias for ST_GeographyFromText. Points are always expressed in long lat form.
Examples
See Also
ST_AsText, ST_GeographyFromText
8.8.1.4 ST_GeographyFromText
ST_GeographyFromText — Return a specified geography value from Well-Known Text representation or extended (WKT).
Synopsis
Description
Returns a geography object from the well-known text representation. SRID 4326 is assumed if unspecified.
See Also
ST_GeogFromText, ST_AsText
8.8.1.5 ST_GeomCollFromText
ST_GeomCollFromText — Makes a collection Geometry from collection WKT with the given SRID. If SRID is not given, it
defaults to 0.
Synopsis
Description
Makes a collection Geometry from the Well-Known-Text (WKT) representation with the given SRID. If SRID is not given, it
defaults to 0.
OGC SPEC 3.2.6.2 - option SRID is from the conformance suite
Returns null if the WKT is not a GEOMETRYCOLLECTION
Note
If you are absolutely sure all your WKT geometries are collections, don’t use this function. It is slower than
ST_GeomFromText since it adds an additional validation step.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2
Examples
See Also
ST_GeomFromText, ST_SRID
8.8.1.6 ST_GeomFromEWKT
ST_GeomFromEWKT — Return a specified ST_Geometry value from Extended Well-Known Text representation (EWKT).
Synopsis
Description
Constructs a PostGIS ST_Geometry object from the OGC Extended Well-Known text (EWKT) representation.
Note
The EWKT format is not an OGC standard, but an PostGIS specific format that includes the spatial reference system
(SRID) identifier
Enhanced: 2.0.0 support for Polyhedral surfaces and TIN was introduced.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
SELECT ST_GeomFromEWKT('SRID=4269;POLYGON((-71.1776585052917 ←-
42.3902909739571,-71.1776820268866 42.3903701743239,
-71.1776063012595 42.3903825660754,-71.1775826583081 42.3903033653531,-71.1776585052917 ←-
42.3902909739571))');
See Also
8.8.1.7 ST_GeomFromMARC21
ST_GeomFromMARC21 — Takes MARC21/XML geographic data as input and returns a PostGIS geometry object.
Synopsis
Description
This function creates a PostGIS geometry from a MARC21/XML record, which can contain a POINT or a POLYGON. In case of
multiple geographic data entries in the same MARC21/XML record, a MULTIPOINT or MULTIPOLYGON will be returned. If
the record contains mixed geometry types, a GEOMETRYCOLLECTION will be returned. It returns NULL if the MARC21/XML
record does not contain any geographic data (datafield:034).
LOC MARC21/XML versions supported:
• MARC21/XML 1.1
Note
The MARC21/XML Coded Cartographic Mathematical Data currently does not provide any means to describe the
Spatial Reference System of the encoded coordinates, so this function will always return a geometry with SRID 0.
PostGIS 3.3.2 Manual 195 / 902
Note
Returned POLYGON geometries will always be clockwise oriented.
Examples
st_astext
-------------------
POINT(-4.5 54.25)
(1 row)
SELECT
ST_AsText(
ST_GeomFromMARC21('
<record xmlns="http://www.loc.gov/MARC21/slim">
<leader>01062cem a2200241 a 4500</leader>
<controlfield tag="001"> 84696781 </controlfield>
<datafield tag="034" ind1="1" ind2=" ">
<subfield code="a">a</subfield>
<subfield code="b">50000</subfield>
<subfield code="d">E0130600</subfield>
<subfield code="e">E0133100</subfield>
<subfield code="f">N0523900</subfield>
<subfield code="g">N0522300</subfield>
</datafield>
</record>'));
st_astext
-------------------------------------------------------------------------------------
SELECT
PostGIS 3.3.2 Manual 196 / 902
ST_AsText(
ST_GeomFromMARC21('
<record xmlns="http://www.loc.gov/MARC21/slim">
<datafield tag="034" ind1="1" ind2=" ">
<subfield code="a">a</subfield>
<subfield code="b">50000</subfield>
<subfield code="d">E0130600</subfield>
<subfield code="e">E0133100</subfield>
<subfield code="f">N0523900</subfield>
<subfield code="g">N0522300</subfield>
</datafield>
<datafield tag="034" ind1=" " ind2=" ">
<subfield code="d">W004.500000</subfield>
<subfield code="e">W004.500000</subfield>
<subfield code="f">N054.250000</subfield>
<subfield code="g">N054.250000</subfield>
</datafield>
</record>'));
st_astext ←-
-------------------------------------------------------------------------------------
GEOMETRYCOLLECTION(POLYGON((13.1 52.65,13.516666666666667 ←-
52.65,13.516666666666667 52.38333333333333,13.1 52.38333333333333,13.1 ←-
52.65)),POINT(-4.5 54.25))
(1 row)
See Also
ST_AsMARC21
8.8.1.8 ST_GeometryFromText
ST_GeometryFromText — Return a specified ST_Geometry value from Well-Known Text representation (WKT). This is an alias
name for ST_GeomFromText
Synopsis
Description
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
See Also
ST_GeomFromText
8.8.1.9 ST_GeomFromText
ST_GeomFromText — Return a specified ST_Geometry value from Well-Known Text representation (WKT).
PostGIS 3.3.2 Manual 197 / 902
Synopsis
Description
Constructs a PostGIS ST_Geometry object from the OGC Well-Known text representation.
Note
There are two variants of ST_GeomFromText function. The first takes no SRID and returns a geometry with no defined
spatial reference system (SRID=0). The second takes a SRID as the second argument and returns a geometry that
includes this SRID as part of its metadata.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2 - option SRID is
from the conformance suite.
Note
While not OGC-compliant, ST_MakePoint is faster than ST_GeomFromText and ST_PointFromText. It is also easier to
use for numeric coordinate values. ST_Point is another option similar in speed to ST_MakePoint and is OGC-compliant,
but doesn’t support anything but 2D points.
Warning
Changed: 2.0.0 In prior versions of PostGIS ST_GeomFromText(’GEOMETRYCOLLECTION(EMPTY)’) was allowed.
This is now illegal in PostGIS 2.0.0 to better conform with SQL/MM standards. This should now be written as
ST_GeomFromText(’GEOMETRYCOLLECTION EMPTY’)
Examples
See Also
8.8.1.10 ST_LineFromText
ST_LineFromText — Makes a Geometry from WKT representation with the given SRID. If SRID is not given, it defaults to 0.
Synopsis
Description
Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0. If WKT passed in is not a
LINESTRING, then null is returned.
Note
OGC SPEC 3.2.6.2 - option SRID is from the conformance suite.
Note
If you know all your geometries are LINESTRINGS, its more efficient to just use ST_GeomFromText. This just calls
ST_GeomFromText and adds additional validation that it returns a linestring.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2
Examples
See Also
ST_GeomFromText
8.8.1.11 ST_MLineFromText
Synopsis
Description
Makes a Geometry from Well-Known-Text (WKT) with the given SRID. If SRID is not given, it defaults to 0.
OGC SPEC 3.2.6.2 - option SRID is from the conformance suite
Returns null if the WKT is not a MULTILINESTRING
Note
If you are absolutely sure all your WKT geometries are points, don’t use this function. It is slower than
ST_GeomFromText since it adds an additional validation step.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2
Examples
See Also
ST_GeomFromText
8.8.1.12 ST_MPointFromText
ST_MPointFromText — Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
PostGIS 3.3.2 Manual 200 / 902
Synopsis
Description
Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
OGC SPEC 3.2.6.2 - option SRID is from the conformance suite
Returns null if the WKT is not a MULTIPOINT
Note
If you are absolutely sure all your WKT geometries are points, don’t use this function. It is slower than
ST_GeomFromText since it adds an additional validation step.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. 3.2.6.2
Examples
See Also
ST_GeomFromText
8.8.1.13 ST_MPolyFromText
ST_MPolyFromText — Makes a MultiPolygon Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
Synopsis
Description
Makes a MultiPolygon from WKT with the given SRID. If SRID is not given, it defaults to 0.
OGC SPEC 3.2.6.2 - option SRID is from the conformance suite
Throws an error if the WKT is not a MULTIPOLYGON
Note
If you are absolutely sure all your WKT geometries are multipolygons, don’t use this function. It is slower than
ST_GeomFromText since it adds an additional validation step.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2
Examples
See Also
ST_GeomFromText, ST_SRID
8.8.1.14 ST_PointFromText
ST_PointFromText — Makes a point Geometry from WKT with the given SRID. If SRID is not given, it defaults to unknown.
Synopsis
Description
Constructs a PostGIS ST_Geometry point object from the OGC Well-Known text representation. If SRID is not given, it defaults
to unknown (currently 0). If geometry is not a WKT point representation, returns null. If completely invalid WKT, then throws
an error.
Note
There are 2 variants of ST_PointFromText function, the first takes no SRID and returns a geometry with no defined
spatial reference system. The second takes a spatial reference id as the second argument and returns an ST_Geometry
that includes this srid as part of its meta-data. The srid must be defined in the spatial_ref_sys table.
Note
If you are absolutely sure all your WKT geometries are points, don’t use this function. It is slower than
ST_GeomFromText since it adds an additional validation step. If you are building points from long lat coordinates
and care more about performance and accuracy than OGC compliance, use ST_MakePoint or OGC compliant alias
ST_Point.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2 - option SRID is
from the conformance suite.
Examples
See Also
8.8.1.15 ST_PolygonFromText
ST_PolygonFromText — Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
Synopsis
Description
Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0. Returns null if WKT is not a polygon.
OGC SPEC 3.2.6.2 - option SRID is from the conformance suite
Note
If you are absolutely sure all your WKT geometries are polygons, don’t use this function. It is slower than
ST_GeomFromText since it adds an additional validation step.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2
Examples
point_is_not_poly
----------
t
See Also
ST_GeomFromText
PostGIS 3.3.2 Manual 203 / 902
8.8.1.16 ST_WKTToSQL
ST_WKTToSQL — Return a specified ST_Geometry value from Well-Known Text representation (WKT). This is an alias name
for ST_GeomFromText
Synopsis
Description
See Also
ST_GeomFromText
8.8.2.1 ST_GeogFromWKB
ST_GeogFromWKB — Creates a geography instance from a Well-Known Binary geometry representation (WKB) or extended
Well Known Binary (EWKB).
Synopsis
Description
The ST_GeogFromWKB function, takes a well-known binary representation (WKB) of a geometry or PostGIS Extended WKB
and creates an instance of the appropriate geography type. This function plays the role of the Geometry Factory in SQL.
If SRID is not specified, it defaults to 4326 (WGS 84 long lat).
Examples
--Although bytea rep contains single \, these need to be escaped when inserting into a ←-
table
SELECT ST_AsText(
ST_GeogFromWKB(E'\\001\\002\\000\\000\\000\\002\\000\\000\\000\\037\\205\\353Q ←-
\\270~\\\\\\300\\323Mb\\020X\\231C@\\020X9\\264\\310~\\\\\\300)\\\\\\217\\302\\365\\230 ←-
C@')
);
st_astext
------------------------------------------------------
LINESTRING(-113.98 39.198,-113.981 39.195)
(1 row)
PostGIS 3.3.2 Manual 204 / 902
See Also
ST_GeogFromText, ST_AsBinary
8.8.2.2 ST_GeomFromEWKB
ST_GeomFromEWKB — Return a specified ST_Geometry value from Extended Well-Known Binary representation (EWKB).
Synopsis
Description
Constructs a PostGIS ST_Geometry object from the OGC Extended Well-Known binary (EWKT) representation.
Note
The EWKB format is not an OGC standard, but a PostGIS specific format that includes the spatial reference system
(SRID) identifier
Enhanced: 2.0.0 support for Polyhedral surfaces and TIN was introduced.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
line string binary rep 0f LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932) in NAD 83 long lat
(4269).
Note
NOTE: Even though byte arrays are delimited with \ and may have ’, we need to escape both out with \ and ” if
standard_conforming_strings is off. So it does not look exactly like its AsEWKB representation.
Note
In PostgreSQL 9.1+ - standard_conforming_strings is set to on by default, where as in past versions it was set to off.
You can change defaults as needed for a single query or at the database or server level. Below is how you would do it
with standard_conforming_strings = on. In this case we escape the ’ with standard ansi ’, but slashes are not escaped
PostGIS 3.3.2 Manual 205 / 902
See Also
8.8.2.3 ST_GeomFromWKB
ST_GeomFromWKB — Creates a geometry instance from a Well-Known Binary geometry representation (WKB) and optional
SRID.
Synopsis
Description
The ST_GeomFromWKB function, takes a well-known binary representation of a geometry and a Spatial Reference System ID
(SRID) and creates an instance of the appropriate geometry type. This function plays the role of the Geometry Factory in SQL.
This is an alternate name for ST_WKBToSQL.
If SRID is not specified, it defaults to 0 (Unknown).
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.7.2 - the optional SRID
is from the conformance suite
Examples
--Although bytea rep contains single \, these need to be escaped when inserting into a ←-
table
-- unless standard_conforming_strings is set to on.
SELECT ST_AsEWKT(
ST_GeomFromWKB(E'\\001\\002\\000\\000\\000\\002\\000\\000\\000\\037\\205\\353Q ←-
\\270~\\\\\\300\\323Mb\\020X\\231C@\\020X9\\264\\310~\\\\\\300)\\\\\\217\\302\\365\\230 ←-
C@',4326)
);
st_asewkt
------------------------------------------------------
SRID=4326;LINESTRING(-113.98 39.198,-113.981 39.195)
(1 row)
SELECT
ST_AsText(
ST_GeomFromWKB(
ST_AsEWKB('POINT(2 5)'::geometry)
)
);
PostGIS 3.3.2 Manual 206 / 902
st_astext
------------
POINT(2 5)
(1 row)
See Also
8.8.2.4 ST_LineFromWKB
Synopsis
Description
The ST_LineFromWKB function, takes a well-known binary representation of geometry and a Spatial Reference System ID
(SRID) and creates an instance of the appropriate geometry type - in this case, a LINESTRING geometry. This function plays
the role of the Geometry Factory in SQL.
If an SRID is not specified, it defaults to 0. NULL is returned if the input bytea does not represent a LINESTRING.
Note
OGC SPEC 3.2.6.2 - option SRID is from the conformance suite.
Note
If you know all your geometries are LINESTRINGs, its more efficient to just use ST_GeomFromWKB. This function
just calls ST_GeomFromWKB and adds additional validation that it returns a linestring.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2
Examples
See Also
ST_GeomFromWKB, ST_LinestringFromWKB
PostGIS 3.3.2 Manual 207 / 902
8.8.2.5 ST_LinestringFromWKB
Synopsis
Description
The ST_LinestringFromWKB function, takes a well-known binary representation of geometry and a Spatial Reference Sys-
tem ID (SRID) and creates an instance of the appropriate geometry type - in this case, a LINESTRING geometry. This function
plays the role of the Geometry Factory in SQL.
If an SRID is not specified, it defaults to 0. NULL is returned if the input bytea does not represent a LINESTRING geometry.
This an alias for ST_LineFromWKB.
Note
OGC SPEC 3.2.6.2 - optional SRID is from the conformance suite.
Note
If you know all your geometries are LINESTRINGs, it’s more efficient to just use ST_GeomFromWKB. This function
just calls ST_GeomFromWKB and adds additional validation that it returns a LINESTRING.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2
Examples
SELECT
ST_LineStringFromWKB(
ST_AsBinary(ST_GeomFromText('LINESTRING(1 2, 3 4)'))
) AS aline,
ST_LinestringFromWKB(
ST_AsBinary(ST_GeomFromText('POINT(1 2)'))
) IS NULL AS null_return;
aline | null_return
------------------------------------------------
010200000002000000000000000000F ... | t
See Also
ST_GeomFromWKB, ST_LineFromWKB
8.8.2.6 ST_PointFromWKB
Synopsis
Description
The ST_PointFromWKB function, takes a well-known binary representation of geometry and a Spatial Reference System ID
(SRID) and creates an instance of the appropriate geometry type - in this case, a POINT geometry. This function plays the role
of the Geometry Factory in SQL.
If an SRID is not specified, it defaults to 0. NULL is returned if the input bytea does not represent a POINT geometry.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.7.2
Examples
SELECT
ST_AsText(
ST_PointFromWKB(
ST_AsEWKB('POINT(2 5)'::geometry)
)
);
st_astext
------------
POINT(2 5)
(1 row)
SELECT
ST_AsText(
ST_PointFromWKB(
ST_AsEWKB('LINESTRING(2 5, 2 6)'::geometry)
)
);
st_astext
-----------
(1 row)
See Also
ST_GeomFromWKB, ST_LineFromWKB
8.8.2.7 ST_WKBToSQL
ST_WKBToSQL — Return a specified ST_Geometry value from Well-Known Binary representation (WKB). This is an alias
name for ST_GeomFromWKB that takes no srid
Synopsis
Description
See Also
ST_GeomFromWKB
8.8.3.1 ST_Box2dFromGeoHash
Synopsis
Description
Examples
SELECT ST_Box2dFromGeoHash('9qqj7nmxncgyy4d0dbxqz0');
st_geomfromgeohash
--------------------------------------------------
BOX(-115.172816 36.114646,-115.172816 36.114646)
st_box2dfromgeohash
----------------------
BOX(-180 -90,180 90)
See Also
8.8.3.2 ST_GeomFromGeoHash
Synopsis
Description
Return a geometry from a GeoHash string. The geometry will be a polygon representing the GeoHash bounds.
If no precision is specified ST_GeomFromGeoHash returns a polygon based on full precision of the input GeoHash string.
If precision is specified ST_GeomFromGeoHash will use that many characters from the GeoHash to create the polygon.
Availability: 2.1.0
Examples
SELECT ST_AsText(ST_GeomFromGeoHash('9qqj7nmxncgyy4d0dbxqz0'));
st_astext
-----------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------
POLYGON((-115.17282128334 36.1146408319473,-115.17282128334 ←-
36.1146461963654,-115.172810554504 36.1146461963654,-115.172810554504 ←-
36.1146408319473,-115.17282128334 36.1146408319473))
See Also
ST_GeoHash,ST_Box2dFromGeoHash, ST_PointFromGeoHash
8.8.3.3 ST_GeomFromGML
ST_GeomFromGML — Takes as input GML representation of geometry and outputs a PostGIS geometry object
Synopsis
Description
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
GML allow mixed dimensions (2D and 3D inside the same MultiGeometry for instance). As PostGIS geometries don’t,
ST_GeomFromGML convert the whole geometry to 2D if a missing Z dimension is found once.
GML support mixed SRS inside the same MultiGeometry. As PostGIS geometries don’t, ST_GeomFromGML, in this case,
reproject all subgeometries to the SRS root node. If no srsName attribute available for the GML root node, the function throw an
error.
ST_GeomFromGML function is not pedantic about an explicit GML namespace. You could avoid to mention it explicitly for
common usages. But you need it if you want to use XLink feature inside GML.
Note
ST_GeomFromGML function not support SQL/MM curves geometries.
SELECT ST_GeomFromGML('
<gml:LineString srsName="EPSG:4269">
<gml:coordinates>
-71.16028,42.258729 -71.160837,42.259112 -71.161143,42.25932
</gml:coordinates>
</gml:LineString>');
SELECT ST_GeomFromGML('
<gml:LineString xmlns:gml="http://www.opengis.net/gml"
xmlns:xlink="http://www.w3.org/1999/xlink"
srsName="urn:ogc:def:crs:EPSG::4269">
<gml:pointProperty>
<gml:Point gml:id="p1"><gml:pos>42.258729 -71.16028</gml:pos></gml:Point>
PostGIS 3.3.2 Manual 212 / 902
</gml:pointProperty>
<gml:pos>42.259112 -71.160837</gml:pos>
<gml:pointProperty>
<gml:Point xlink:type="simple" xlink:href="#p1"/>
</gml:pointProperty>
</gml:LineString>'););
SELECT ST_AsEWKT(ST_GeomFromGML('
<gml:PolyhedralSurface>
<gml:polygonPatches>
<gml:PolygonPatch>
<gml:exterior>
<gml:LinearRing><gml:posList srsDimension="3">0 0 0 0 0 1 0 1 1 0 1 0 0 0 0</gml: ←-
posList></gml:LinearRing>
</gml:exterior>
</gml:PolygonPatch>
<gml:PolygonPatch>
<gml:exterior>
<gml:LinearRing><gml:posList srsDimension="3">0 0 0 0 1 0 1 1 0 1 0 0 0 0 0</gml:posList ←-
></gml:LinearRing>
</gml:exterior>
</gml:PolygonPatch>
<gml:PolygonPatch>
<gml:exterior>
<gml:LinearRing><gml:posList srsDimension="3">0 0 0 1 0 0 1 0 1 0 0 1 0 0 0</gml:posList ←-
></gml:LinearRing>
</gml:exterior>
</gml:PolygonPatch>
<gml:PolygonPatch>
<gml:exterior>
<gml:LinearRing><gml:posList srsDimension="3">1 1 0 1 1 1 1 0 1 1 0 0 1 1 0</gml:posList ←-
></gml:LinearRing>
</gml:exterior>
</gml:PolygonPatch>
<gml:PolygonPatch>
<gml:exterior>
<gml:LinearRing><gml:posList srsDimension="3">0 1 0 0 1 1 1 1 1 1 1 0 0 1 0</gml:posList ←-
></gml:LinearRing>
</gml:exterior>
</gml:PolygonPatch>
<gml:PolygonPatch>
<gml:exterior>
<gml:LinearRing><gml:posList srsDimension="3">0 0 1 1 0 1 1 1 1 0 1 1 0 0 1</gml:posList ←-
></gml:LinearRing>
</gml:exterior>
</gml:PolygonPatch>
</gml:polygonPatches>
</gml:PolyhedralSurface>'));
-- result --
POLYHEDRALSURFACE(((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),
((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),
((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)))
PostGIS 3.3.2 Manual 213 / 902
See Also
8.8.3.4 ST_GeomFromGeoJSON
ST_GeomFromGeoJSON — Takes as input a geojson representation of a geometry and outputs a PostGIS geometry object
Synopsis
Description
Note
If you do not have JSON-C enabled, support you will get an error notice instead of seeing an output. To enable JSON-C,
run configure --with-jsondir=/path/to/json-c. See Section 2.2.3 for details.
Examples
SELECT ST_AsText(ST_GeomFromGeoJSON('{"type":"Point","coordinates":[-48.23456,20.12345]}')) ←-
As wkt;
wkt
------
POINT(-48.23456 20.12345)
-- a 3D linestring
SELECT ST_AsText(ST_GeomFromGeoJSON('{"type":"LineString","coordinates ←-
":[[1,2,3],[4,5,6],[7,8,9]]}')) As wkt;
wkt
-------------------
LINESTRING(1 2,4 5,7 8)
See Also
8.8.3.5 ST_GeomFromKML
ST_GeomFromKML — Takes as input KML representation of geometry and outputs a PostGIS geometry object
Synopsis
Description
Note
ST_GeomFromKML function not support SQL/MM curves geometries.
SELECT ST_GeomFromKML('
<LineString>
<coordinates>-71.1663,42.2614
-71.1667,42.2616</coordinates>
</LineString>');
See Also
8.8.3.6 ST_GeomFromTWKB
ST_GeomFromTWKB — Creates a geometry instance from a TWKB ("Tiny Well-Known Binary") geometry representation.
Synopsis
Description
The ST_GeomFromTWKB function, takes a a TWKB ("Tiny Well-Known Binary") geometry representation (WKB) and creates
an instance of the appropriate geometry type.
PostGIS 3.3.2 Manual 215 / 902
Examples
st_astext
-----------------------------
LINESTRING(126 34, 127 35)
(1 row)
SELECT ST_AsEWKT(
ST_GeomFromTWKB(E'\\x620002f7f40dbce4040105')
);
st_asewkt
------------------------------------------------------
LINESTRING(-113.98 39.198,-113.981 39.195)
(1 row)
See Also
ST_AsTWKB
8.8.3.7 ST_GMLToSQL
ST_GMLToSQL — Return a specified ST_Geometry value from GML representation. This is an alias name for ST_GeomFromGML
Synopsis
Description
This method implements the SQL/MM specification. SQL-MM 3: 5.1.50 (except for curves support).
Availability: 1.5, requires libxml2 1.6+
Enhanced: 2.0.0 support for Polyhedral surfaces and TIN was introduced.
Enhanced: 2.0.0 default srid optional parameter added.
See Also
8.8.3.8 ST_LineFromEncodedPolyline
Synopsis
Description
Examples
See Also
ST_AsEncodedPolyline
8.8.3.9 ST_PointFromGeoHash
Synopsis
Description
Return a point from a GeoHash string. The point represents the center point of the GeoHash.
If no precision is specified ST_PointFromGeoHash returns a point based on full precision of the input GeoHash string.
If precision is specified ST_PointFromGeoHash will use that many characters from the GeoHash to create the point.
Availability: 2.1.0
Examples
SELECT ST_AsText(ST_PointFromGeoHash('9qqj7nmxncgyy4d0dbxqz0'));
st_astext
------------------------------
POINT(-115.172816 36.114646)
See Also
8.8.3.10 ST_FromFlatGeobufToTable
Synopsis
Description
8.8.3.11 ST_FromFlatGeobuf
Synopsis
Description
Reads FlatGeobuf data (http://flatgeobuf.org). NOTE: PostgreSQL bytea cannot exceed 1GB.
tabletype reference to a table type.
data input FlatGeobuf data.
Availability: 3.2.0
8.9.1.1 ST_AsEWKT
ST_AsEWKT — Return the Well-Known Text (WKT) representation of the geometry with SRID meta data.
PostGIS 3.3.2 Manual 218 / 902
Synopsis
Description
Returns the Well-Known Text representation of the geometry prefixed with the SRID. The optional maxdecimaldigits argu-
ment may be used to reduce the maximum number of decimal digits after floating point used in output (defaults to 15).
To perform the inverse conversion of EWKT representation to PostGIS geometry use ST_GeomFromEWKT.
Warning
Using the maxdecimaldigits parameter can cause output geometry to become invalid. To avoid this use
ST_ReducePrecision with a suitable gridsize first.
Note
The WKT spec does not include the SRID. To get the OGC WKT format use ST_AsText.
Warning
WKT format does not maintain precision so to prevent floating truncation, use ST_AsBinary or ST_AsEWKB format for
transport.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
SELECT ST_AsEWKT('0103000020E61000000100000005000000000000
000000000000000000000000000000000000000000000000000000
F03F000000000000F03F000000000000F03F000000000000F03
F000000000000000000000000000000000000000000000000'::geometry);
st_asewkt
--------------------------------
SRID=4326;POLYGON((0 0,0 1,1 1,1 0,0 0))
(1 row)
PostGIS 3.3.2 Manual 219 / 902
SELECT ST_AsEWKT('0108000080030000000000000060 ←-
E30A4100000000785C0241000000000000F03F0000000018
E20A4100000000485F024100000000000000400000000018
E20A4100000000305C02410000000000000840')
--st_asewkt---
CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)
See Also
8.9.1.2 ST_AsText
ST_AsText — Return the Well-Known Text (WKT) representation of the geometry/geography without SRID metadata.
Synopsis
Description
Returns the OGC Well-Known Text (WKT) representation of the geometry/geography. The optional maxdecimaldigits argu-
ment may be used to limit the number of digits after the decimal point in output ordinates (defaults to 15).
To perform the inverse conversion of WKT representation to PostGIS geometry use ST_GeomFromText.
Note
The standard OGC WKT representation does not include the SRID. To include the SRID as part of the output represen-
tation, use the non-standard PostGIS function ST_AsEWKT
Warning
The textual representation of numbers in WKT may not maintain full floating-point precision. To ensure full ac-
curacy for data storage or transport it is best to use Well-Known Binary (WKB) format (see ST_AsBinary and
maxdecimaldigits).
Warning
Using the maxdecimaldigits parameter can cause output geometry to become invalid. To avoid this use
ST_ReducePrecision with a suitable gridsize first.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.1
Examples
SELECT ST_AsText('01030000000100000005000000000000000000
000000000000000000000000000000000000000000000000
F03F000000000000F03F000000000000F03F000000000000F03
F000000000000000000000000000000000000000000000000');
st_astext
--------------------------------
POLYGON((0 0,0 1,1 1,1 0,0 0))
See Also
8.9.2.1 ST_AsBinary
ST_AsBinary — Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID
meta data.
Synopsis
Description
Returns the OGC/ISO Well-Known Binary (WKB) representation of the geometry. The first function variant defaults to encoding
using server machine endian. The second function variant takes a text argument specifying the endian encoding, either little-
endian (’NDR’) or big-endian (’XDR’).
WKB format is useful to read geometry data from the database and maintaining full numeric precision. This avoids the precision
rounding that can happen with text formats such as WKT.
To perform the inverse conversion of WKB to PostGIS geometry use ST_GeomFromWKB.
Note
The OGC/ISO WKB format does not include the SRID. To get the EWKB format which does include the SRID use
ST_AsEWKB
PostGIS 3.3.2 Manual 221 / 902
Note
The default behavior in PostgreSQL 9.0 has been changed to output bytea in hex encoding. If your GUI tools require
the old behavior, then SET bytea_output=’escape’ in your database.
Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
Enhanced: 2.0.0 support for higher coordinate dimensions was introduced.
Enhanced: 2.0.0 support for specifying endian with geography was introduced.
Availability: 1.5.0 geography support was introduced.
Changed: 2.0.0 Inputs to this function can not be unknown -- must be geometry. Constructs such as ST_AsBinary(’POINT(1
2)’) are no longer valid and you will get an n st_asbinary(unknown) is not unique error. Code like that
needs to be changed to ST_AsBinary(’POINT(1 2)’::geometry);. If that is not possible, then install legacy.sql.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.1
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
st_asbinary
--------------------------------
\x01030000000100000005000000000000000000000000000000000000000000000000000000000000
000000f03f000000000000f03f000000000000f03f000000000000f03f0000000000000000000000
00000000000000000000000000
See Also
8.9.2.2 ST_AsEWKB
ST_AsEWKB — Return the Extended Well-Known Binary (EWKB) representation of the geometry with SRID meta data.
PostGIS 3.3.2 Manual 222 / 902
Synopsis
Description
Returns the Extended Well-Known Binary (EWKB) representation of the geometry with SRID metadata. The first function
variant defaults to encoding using server machine endian. The second function variant takes a text argument specifying the
endian encoding, either little-endian (’NDR’) or big-endian (’XDR’).
WKB format is useful to read geometry data from the database and maintaining full numeric precision. This avoids the precision
rounding that can happen with text formats such as WKT.
To perform the inverse conversion of EWKB to PostGIS geometry use ST_GeomFromEWKB.
Note
To get the OGC/ISO WKB format use ST_AsBinary. Note that OGC/ISO WKB format does not include the SRID.
Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
st_asewkb
--------------------------------
\x0103000020e610000001000000050000000000000000000000000000000000000000000000000000
00000000000000f03f000000000000f03f000000000000f03f000000000000f03f00000000000000
0000000000000000000000000000000000
See Also
8.9.2.3 ST_AsHEXEWKB
ST_AsHEXEWKB — Returns a Geometry in HEXEWKB format (as text) using either little-endian (NDR) or big-endian (XDR)
encoding.
PostGIS 3.3.2 Manual 223 / 902
Synopsis
Description
Returns a Geometry in HEXEWKB format (as text) using either little-endian (NDR) or big-endian (XDR) encoding. If no
encoding is specified, then NDR is used.
Note
Availability: 1.2.2
Examples
st_ashexewkb
--------
0103000020E6100000010000000500
00000000000000000000000000000000
00000000000000000000000000000000F03F
000000000000F03F000000000000F03F000000000000F03
F000000000000000000000000000000000000000000000000
8.9.3.1 ST_AsEncodedPolyline
Synopsis
Description
Returns the geometry as an Encoded Polyline. This format is used by Google Maps with precision=5 and by Open Source
Routing Machine with precision=5 and 6.
Optional precision specifies how many decimal places will be preserved in Encoded Polyline. Value should be the same on
encoding and decoding, or coordinates will be incorrect.
Availability: 2.2.0
PostGIS 3.3.2 Manual 224 / 902
Examples
Basic
SELECT ST_AsEncodedPolyline(GeomFromEWKT('SRID=4326;LINESTRING(-120.2 38.5,-120.95 ←-
40.7,-126.453 43.252)'));
--result--
|_p~iF~ps|U_ulLnnqC_mqNvxq ` @
Use in conjunction with geography linestring and geography segmentize, and put on google maps
-- the SQL for Boston to San Francisco, segments every 100 KM
SELECT ST_AsEncodedPolyline(
ST_Segmentize(
ST_GeogFromText('LINESTRING(-71.0519 42.4935,-122.4483 37.64)'),
100000)::geometry) As encodedFlightPath;
javascript will look something like this where $ variable you replace with query result
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries= ←-
geometry"></script>
<script type="text/javascript">
flightPath = new google.maps.Polyline({
path: google.maps.geometry.encoding.decodePath("$encodedFlightPath"),
map: map,
strokeColor: '#0000CC',
strokeOpacity: 1.0,
strokeWeight: 4
});
</script>
See Also
ST_LineFromEncodedPolyline, ST_Segmentize
8.9.3.2 ST_AsFlatGeobuf
Synopsis
Description
Return a FlatGeobuf representation (http://flatgeobuf.org) of a set of rows corresponding to a FeatureCollection. NOTE: Post-
greSQL bytea cannot exceed 1GB.
row row data with at least a geometry column.
index toggle spatial index creation. Default is false.
geom_name is the name of the geometry column in the row data. If NULL it will default to the first found geometry column.
Availability: 3.2.0
PostGIS 3.3.2 Manual 225 / 902
8.9.3.3 ST_AsGeobuf
Synopsis
Description
Examples
8.9.3.4 ST_AsGeoJSON
Synopsis
Description
Returns a geometry as a GeoJSON "geometry", or a row as a GeoJSON "feature". (See the GeoJSON specifications RFC 7946).
2D and 3D Geometries are both supported. GeoJSON only support SFS 1.1 geometry types (no curve support for example).
The maxdecimaldigits argument may be used to reduce the maximum number of decimal places used in output (defaults
to 9). If you are using EPSG:4326 and are outputting the geometry only for display, maxdecimaldigits=6 can be a good
choice for many maps.
Warning
Using the maxdecimaldigits parameter can cause output geometry to become invalid. To avoid this use
ST_ReducePrecision with a suitable gridsize first.
PostGIS 3.3.2 Manual 226 / 902
The options argument can be used to add BBOX or CRS in GeoJSON output:
• 0: means no option
• 1: GeoJSON BBOX
• 2: GeoJSON Short CRS (e.g EPSG:4326)
The GeoJSON specification states that polygons are oriented using the Right-Hand Rule, and some clients require this orientation.
This can be ensured by using ST_ForcePolygonCCW . The specification also requires that geometry be in the WGS84 coordinate
system (SRID = 4326). If necessary geometry can be projected into WGS84 using ST_Transform: ST_Transform( geom,
4326 ).
GeoJSON can be tested and viewed online at geojson.io and geojsonlint.com. It is widely supported by web mapping frameworks:
Availability: 1.3.4
Availability: 1.5.0 geography support was introduced.
Changed: 2.0.0 support default args and named args.
Changed: 3.0.0 support records as input
Changed: 3.0.0 output SRID if not EPSG:4326.
Examples
Generate a FeatureCollection:
SELECT json_build_object(
'type', 'FeatureCollection',
'features', json_agg(ST_AsGeoJSON(t.*)::json)
)
FROM ( VALUES (1, 'one', 'POINT(1 1)'::geometry),
(2, 'two', 'POINT(2 2)'),
(3, 'three', 'POINT(3 3)')
) as t(id, name, geom);
Generate a Feature:
SELECT ST_AsGeoJSON(t.*)
FROM (VALUES (1, 'one', 'POINT(1 1)'::geometry)) AS t(id, name, geom);
PostGIS 3.3.2 Manual 227 / 902
st_asgeojson
-----------------------------------------------------------------------------------------------------
An alternate way to generate Features with an id property is to use JSONB functions and operators:
SELECT jsonb_build_object(
'type', 'Feature',
'id', id,
'geometry', ST_AsGeoJSON(geom)::jsonb,
'properties', to_jsonb( t.* ) - 'id' - 'geom'
) AS json
FROM (VALUES (1, 'one', 'POINT(1 1)'::geometry)) AS t(id, name, geom);
json
-----------------------------------------------------------------------------------------------------
{"id": 1, "type": "Feature", "geometry": {"type": "Point", "coordinates": [1, 1]}, " ←-
properties": {"name": "one"}}
Don’t forget to transform your data to WGS84 longitude, latitude to conform with the GeoJSON specification:
SELECT ST_AsGeoJSON(ST_Transform(geom,4326)) from fe_edges limit 1;
st_asgeojson
-----------------------------------------------------------------------------------------------------
{"type":"MultiLineString","coordinates":[[[-89.734634999999997,31.492072000000000],
[-89.734955999999997,31.492237999999997]]]}
{"type":"LineString","coordinates":[[1,2,3],[4,5,6]]}
See Also
8.9.3.5 ST_AsGML
Synopsis
Description
Return the geometry as a Geography Markup Language (GML) element. The version parameter, if specified, may be either 2 or
3. If no version parameter is specified then the default is assumed to be 2. The maxdecimaldigits argument may be used to
reduce the maximum number of decimal places used in output (defaults to 15).
Warning
Using the maxdecimaldigits parameter can cause output geometry to become invalid. To avoid this use
ST_ReducePrecision with a suitable gridsize first.
• 4: For GML 3 only, use <LineString> rather than <Curve> tag for lines.
• 16: Declare that datas are lat/lon (e.g srid=4326). Default is to assume that data are planars. This option is useful for GML
3.1.1 output only, related to axis order. So if you set it, it will swap the coordinates so order is lat lon instead of database lon
lat.
The ’namespace prefix’ argument may be used to specify a custom namespace prefix or no prefix (if empty). If null or omitted
’gml’ prefix is used
Availability: 1.3.2
Availability: 1.5.0 geography support was introduced.
Enhanced: 2.0.0 prefix support was introduced. Option 4 for GML3 was introduced to allow using LineString instead of Curve
tag for lines. GML3 Support for Polyhedral surfaces and TINS was introduced. Option 32 was introduced to output the box.
Changed: 2.0.0 use default named args
Enhanced: 2.1.0 id support was introduced, for GML 3.
Note
Only version 3+ of ST_AsGML supports Polyhedral Surfaces and TINS.
This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 17.2
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
PostGIS 3.3.2 Manual 229 / 902
Examples: Version 2
Examples: Version 3
-- Output the envelope (32) , reverse (lat lon instead of lon lat) (16), long srs (1)= 32 | ←-
16 | 1 = 49 --
SELECT ST_AsGML(3, ST_GeomFromText('LINESTRING(1 2, 3 4, 10 20)',4326), 5, 49);
st_asgml
--------
<gml:Envelope srsName="urn:ogc:def:crs:EPSG::4326">
<gml:lowerCorner>2 1</gml:lowerCorner>
<gml:upperCorner>20 10</gml:upperCorner>
</gml:Envelope>
-- Polyhedral Example --
SELECT ST_AsGML(3, ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0) ←-
),
((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)),
((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)),
((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )'));
st_asgml
--------
<gml:PolyhedralSurface>
<gml:polygonPatches>
<gml:PolygonPatch>
<gml:exterior>
<gml:LinearRing>
<gml:posList srsDimension="3">0 0 0 0 0 1 0 1 1 0 1 0 0 0 0</gml:posList>
</gml:LinearRing>
</gml:exterior>
</gml:PolygonPatch>
<gml:PolygonPatch>
<gml:exterior>
<gml:LinearRing>
<gml:posList srsDimension="3">0 0 0 0 1 0 1 1 0 1 0 0 0 0 0</gml:posList>
</gml:LinearRing>
PostGIS 3.3.2 Manual 230 / 902
</gml:exterior>
</gml:PolygonPatch>
<gml:PolygonPatch>
<gml:exterior>
<gml:LinearRing>
<gml:posList srsDimension="3">0 0 0 1 0 0 1 0 1 0 0 1 0 0 0</gml:posList>
</gml:LinearRing>
</gml:exterior>
</gml:PolygonPatch>
<gml:PolygonPatch>
<gml:exterior>
<gml:LinearRing>
<gml:posList srsDimension="3">1 1 0 1 1 1 1 0 1 1 0 0 1 1 0</gml:posList>
</gml:LinearRing>
</gml:exterior>
</gml:PolygonPatch>
<gml:PolygonPatch>
<gml:exterior>
<gml:LinearRing>
<gml:posList srsDimension="3">0 1 0 0 1 1 1 1 1 1 1 0 0 1 0</gml:posList>
</gml:LinearRing>
</gml:exterior>
</gml:PolygonPatch>
<gml:PolygonPatch>
<gml:exterior>
<gml:LinearRing>
<gml:posList srsDimension="3">0 0 1 1 0 1 1 1 1 0 1 1 0 0 1</gml:posList>
</gml:LinearRing>
</gml:exterior>
</gml:PolygonPatch>
</gml:polygonPatches>
</gml:PolyhedralSurface>
See Also
ST_GeomFromGML
8.9.3.6 ST_AsKML
Synopsis
Description
Return the geometry as a Keyhole Markup Language (KML) element. default maximum number of decimal places is 15, default
namespace is no prefix.
Warning
Using the maxdecimaldigits parameter can cause output geometry to become invalid. To avoid this use
ST_ReducePrecision with a suitable gridsize first.
PostGIS 3.3.2 Manual 231 / 902
Note
Requires PostGIS be compiled with Proj support. Use PostGIS_Full_Version to confirm you have proj support compiled
in.
Note
Availability: 1.2.2 - later variants that include version param came in 1.3.2
Note
Enhanced: 2.0.0 - Add prefix namespace, use default and named args
Note
Changed: 3.0.0 - Removed the "versioned" variant signature
Note
AsKML output will not work with geometries that do not have an SRID
Examples
st_askml
--------
<Polygon><outerBoundaryIs><LinearRing><coordinates>0,0 0,1 1,1 1,0 0,0</coordinates></ ←-
LinearRing></outerBoundaryIs></Polygon>
--3d linestring
SELECT ST_AsKML('SRID=4326;LINESTRING(1 2 3, 4 5 6)');
<LineString><coordinates>1,2,3 4,5,6</coordinates></LineString>
See Also
ST_AsSVG, ST_AsGML
8.9.3.7 ST_AsLatLonText
ST_AsLatLonText — Return the Degrees, Minutes, Seconds representation of the given point.
Synopsis
Description
Note
It is assumed the point is in a lat/lon projection. The X (lon) and Y (lat) coordinates are normalized in the output to the
"normal" range (-180 to +180 for lon, -90 to +90 for lat).
The text parameter is a format string containing the format for the resulting text, similar to a date format string. Valid tokens
are "D" for degrees, "M" for minutes, "S" for seconds, and "C" for cardinal direction (NSEW). DMS tokens may be repeated to
indicate desired width and precision ("SSS.SSSS" means " 1.0023").
"M", "S", and "C" are optional. If "C" is omitted, degrees are shown with a "-" sign if south or west. If "S" is omitted, minutes
will be shown as decimal with as many digits of precision as you specify. If "M" is also omitted, degrees are shown as decimal
with as many digits precision as you specify.
If the format string is omitted (or zero-length) a default format will be used.
Availability: 2.0
Examples
Default format.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)'));
st_aslatlontext
----------------------------
2\textdegree{}19'29.928"S 3\textdegree{}14'3.243"W
Decimal degrees.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D.DDDD degrees C'));
st_aslatlontext
-----------------------------------
2.3250 degrees S 3.2342 degrees W
8.9.3.8 ST_AsMARC21
Synopsis
Description
This function returns a MARC21/XML record with Coded Cartographic Mathematical Data representing the bounding box of a
given geometry. The format parameter allows to encode the coordinates in subfields $d,$e,$f and $g in all formats supported
by the MARC21/XML standard. Valid formats are:
• MARC21/XML 1.1
Availability: 3.3.0
Note
This function does not support non lon/lat geometries, as they are not supported by the MARC21/XML standard (Coded
Cartographic Mathematical Data).
Note
The MARC21/XML Standard does not provide any means to annotate the spatial reference system for Coded Carto-
graphic Mathematical Data, which means that this information will be lost after conversion to MARC21/XML.
PostGIS 3.3.2 Manual 234 / 902
Examples
st_asmarc21
-------------------------------------------------
<record xmlns="http://www.loc.gov/MARC21/slim">
<datafield tag="034" ind1="1" ind2=" ">
<subfield code="a">a</subfield>
<subfield code="d">W0043015</subfield>
<subfield code="e">W0043015</subfield>
<subfield code="f">N0541512</subfield>
<subfield code="g">N0541512</subfield>
</datafield>
</record>
SELECT ST_AsMARC21('SRID=4326;POLYGON((-4.5792388916015625 ←-
54.18172660239091,-4.56756591796875 ←-
54.196993557130355,-4.546623229980469 ←-
54.18313300502024,-4.5792388916015625 54.18172660239091))'::geometry,' ←-
hddd.dddd');
<record xmlns="http://www.loc.gov/MARC21/slim">
<datafield tag="034" ind1="1" ind2=" ">
<subfield code="a">a</subfield>
<subfield code="d">W004.5792</subfield>
<subfield code="e">W004.5466</subfield>
<subfield code="f">N054.1970</subfield>
<subfield code="g">N054.1817</subfield>
</datafield>
</record>
Converting a GEOMETRYCOLLECTION to MARC21/XML formated in decimal minutes. The geometries order in the MARC21/XML
output correspond to their order in the collection.
SELECT ST_AsMARC21('SRID=4326;GEOMETRYCOLLECTION(POLYGON((13.1 ←-
52.65,13.516666666666667 52.65,13.516666666666667 52.38333333333333,13.1 ←-
52.38333333333333,13.1 52.65)),POINT(-4.5 54.25))'::geometry,'hdddmm. ←-
mmmm');
st_asmarc21
-------------------------------------------------
<record xmlns="http://www.loc.gov/MARC21/slim">
<datafield tag="034" ind1="1" ind2=" ">
<subfield code="a">a</subfield>
<subfield code="d">E01307.0000</subfield>
<subfield code="e">E01331.0000</subfield>
<subfield code="f">N05240.0000</subfield>
<subfield code="g">N05224.0000</subfield>
</datafield>
<datafield tag="034" ind1="1" ind2=" ">
PostGIS 3.3.2 Manual 235 / 902
<subfield code="a">a</subfield>
<subfield code="d">W00430.0000</subfield>
<subfield code="e">W00430.0000</subfield>
<subfield code="f">N05415.0000</subfield>
<subfield code="g">N05415.0000</subfield>
</datafield>
</record>
See Also
ST_GeomFromMARC21
8.9.3.9 ST_AsMVTGeom
Synopsis
geometry ST_AsMVTGeom(geometry geom, box2d bounds, integer extent=4096, integer buffer=256, boolean clip_geom=true);
Description
Transforms a geometry into the coordinate space of a MVT (Mapbox Vector Tile) tile, clipping it to the tile bounds if required.
The geometry must be in the coordinate system of the target map (using ST_Transform if needed). Commonly this is Web
Mercator (SRID:3857).
The function attempts to preserve geometry validity, and corrects it if needed. This may cause the result geometry to collapse to
a lower dimension.
The rectangular bounds of the tile in the target map coordinate space must be provided, so the geometry can be transformed, and
clipped if required. The bounds can be generated using ST_TileEnvelope.
This function is used to convert geometry into the tile coordinate space required by ST_AsMVT.
geom is the geometry to transform, in the coordinate system of the target map.
bounds is the rectangular bounds of the tile in map coordinate space, with no buffer.
extent is the tile extent size in tile coordinate space as defined by the MVT specification. Defaults to 4096.
buffer is the buffer size in tile coordinate space for geometry clippig. Defaults to 256.
clip_geom is a boolean to control if geometries are clipped or encoded as-is. Defaults to true.
Availability: 2.4.0
Note
From 3.0, Wagyu can be chosen at configure time to clip and validate MVT polygons. This library is faster and produces
more correct results than the GEOS default, but it might drop small polygons.
PostGIS 3.3.2 Manual 236 / 902
Examples
SELECT ST_AsText(ST_AsMVTGeom(
ST_GeomFromText('POLYGON ((0 0, 10 0, 10 5, 0 -5, 0 0))'),
ST_MakeBox2D(ST_Point(0, 0), ST_Point(4096, 4096)),
4096, 0, false));
st_astext
--------------------------------------------------------------------
MULTIPOLYGON(((5 4096,10 4091,10 4096,5 4096)),((5 4096,0 4101,0 4096,5 4096)))
Canonical example for a Web Mercator tile using a computed tile bounds to query and clip geometry.
SELECT ST_AsMVTGeom(
ST_Transform( geom, 3857 ),
ST_TileEnvelope(12, 513, 412), extent => 4096, buffer => 64) AS geom
FROM data
WHERE geom && ST_TileEnvelope(12, 513, 412, margin => (64.0 / 4096))
See Also
8.9.3.10 ST_AsMVT
Synopsis
Description
An aggregate function which returns a binary Mapbox Vector Tile representation of a set of rows corresponding to a tile layer.
The rows must contain a geometry column which will be encoded as a feature geometry. The geometry must be in tile coordinate
space and valid as per the MVT specification. ST_AsMVTGeom can be used to transform geometry into tile coordinate space.
Other row columns are encoded as feature attributes.
The Mapbox Vector Tile format can store features with varying sets of attributes. To use this capability supply a JSONB column
in the row data containing Json objects one level deep. The keys and values in the JSONB values will be encoded as feature
attributes.
Tiles with multiple layers can be created by concatenating multiple calls to this function using || or STRING_AGG.
Important
Do not call with a GEOMETRYCOLLECTION as an element in the row. However you can use ST_AsMVTGeom to
prepare a geometry collection for inclusion.
PostGIS 3.3.2 Manual 237 / 902
Examples
WITH mvtgeom AS
(
SELECT ST_AsMVTGeom(geom, ST_TileEnvelope(12, 513, 412), extent => 4096, buffer => 64) AS ←-
geom, name, description
FROM points_of_interest
WHERE geom && ST_TileEnvelope(12, 513, 412, margin => (64.0 / 4096))
)
SELECT ST_AsMVT(mvtgeom.*)
FROM mvtgeom;
See Also
ST_AsMVTGeom, ST_TileEnvelope
8.9.3.11 ST_AsSVG
Synopsis
Description
Return the geometry as Scalar Vector Graphics (SVG) path data. Use 1 as second argument to have the path data implemented
in terms of relative moves, the default (or 0) uses absolute moves. Third argument may be used to reduce the maximum number
of decimal digits used in output (defaults to 15). Point geometries will be rendered as cx/cy when ’rel’ arg is 0, x/y when ’rel’ is
1. Multipoint geometries are delimited by commas (","), GeometryCollection geometries are delimited by semicolons (";").
Note
Availability: 1.2.2. Availability: 1.4.0 Changed in PostGIS 1.4.0 to include L command in absolute path to conform to
http://www.w3.org/TR/SVG/paths.html#PathDataBNF
Examples
st_assvg
--------
M 0 0 L 0 -1 1 -1 1 0 Z
8.9.3.12 ST_AsTWKB
Synopsis
bytea ST_AsTWKB(geometry g1, integer decimaldigits_xy=0, integer decimaldigits_z=0, integer decimaldigits_m=0, boolean
include_sizes=false, boolean include_bounding boxes=false);
bytea ST_AsTWKB(geometry[] geometries, bigint[] unique_ids, integer decimaldigits_xy=0, integer decimaldigits_z=0, integer
decimaldigits_m=0, boolean include_sizes=false, boolean include_bounding_boxes=false);
Description
Returns the geometry in TWKB (Tiny Well-Known Binary) format. TWKB is a compressed binary format with a focus on
minimizing the size of the output.
The decimal digits parameters control how much precision is stored in the output. By default, values are rounded to the nearest
unit before encoding. If you want to transfer more precision, increase the number. For example, a value of 1 implies that the first
digit to the right of the decimal point will be preserved.
The sizes and bounding boxes parameters control whether optional information about the encoded length of the object and the
bounds of the object are included in the output. By default they are not. Do not turn them on unless your client software has a
use for them, as they just use up space (and saving space is the point of TWKB).
The array-input form of the function is used to convert a collection of geometries and unique identifiers into a TWKB collection
that preserves the identifiers. This is useful for clients that expect to unpack a collection and then access further information
about the objects inside. You can create the arrays using the array_agg function. The other parameters operate the same as for
the simple form of the function.
Note
The format specification is available online at https://github.com/TWKB/Specification, and code for building a JavaScript
client can be found at https://github.com/TWKB/twkb.js.
Examples
To create an aggregate TWKB object including identifiers aggregate the desired geometries and objects first, using "array_agg()",
then call the appropriate TWKB function.
PostGIS 3.3.2 Manual 239 / 902
See Also
8.9.3.13 ST_AsX3D
Synopsis
Description
Note
There are various options for translating PostGIS geometries to X3D since X3D geometry types don’t map directly
to PostGIS geometry types and some newer X3D types that might be better mappings we have avoided since most
rendering tools don’t currently support them. These are the mappings we have settled on. Feel free to post a bug ticket
if you have thoughts on the idea or ways we can allow people to denote their preferred mappings.
Below is how we currently map PostGIS 2D/3D types to X3D types
The ’options’ argument is a bitfield. For PostGIS 2.2+, this is used to denote whether to represent coordinates with X3D
GeoCoordinates Geospatial node and also whether to flip the x/y axis. By default, ST_AsX3D outputs in database form (long,lat
or X,Y), but X3D default of lat/lon, y/x may be preferred.
• 0: X/Y in database order (e.g. long/lat = X,Y is standard database order), default value, and non-spatial coordinates (just
regular old Coordinate tag).
• 1: Flip X and Y. If used in conjunction with the GeoCoordinate option switch, then output will be default "latitude_first" and
coordinates will be flipped as well.
• 2: Output coordinates in GeoSpatial GeoCoordinates. This option will throw an error if geometries are not in WGS 84 long
lat (srid: 4326). This is currently the only GeoCoordinate type supported. Refer to X3D specs specifying a spatial reference
system.. Default output will be GeoCoordinate geoSystem=’"GD" "WE" "longitude_first"’. If you prefer
the X3D default of GeoCoordinate geoSystem=’"GD" "WE" "latitude_first"’ use (2 + 1) = 3
Note
2D geometry support not yet complete. Inner rings currently just drawn as separate polygons. We are working on
these.
Lots of advancements happening in 3D space particularly with X3D Integration with HTML5
There is also a nice open source X3D viewer you can use to view rendered geometries. Free Wrl http://freewrl.sourceforge.net/
binaries available for Mac, Linux, and Windows. Use the FreeWRL_Launcher packaged to view the geometries.
Also check out PostGIS minimalist X3D viewer that utilizes this function and x3dDom html/js open source toolkit.
Availability: 2.0.0: ISO-IEC-19776-1.2-X3DEncodings-XML
Enhanced: 2.2.0: Support for GeoCoordinates and axis (x/y, long/lat) flipping. Look at options for details.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Example: Create a fully functional X3D document - This will generate a cube that is viewable in FreeWrl and other X3D
viewers.
x3ddoc
--------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE X3D PUBLIC "ISO//Web3D//DTD X3D 3.0//EN" "http://www.web3d.org/specifications/x3d ←-
-3.0.dtd">
<X3D>
<Scene>
<Transform>
<Shape>
<Appearance>
<Material emissiveColor='0 0 1'/>
</Appearance>
<IndexedFaceSet coordIndex='0 1 2 3 -1 4 5 6 7 -1 8 9 10 11 -1 12 13 14 15 -1 16 17 ←-
18 19 -1 20 21 22 23'>
<Coordinate point='0 0 0 0 0 1 0 1 1 0 1 0 0 0 0 0 1 0 1 1 0 1 0 0 0 0 0 1 0 0 ←-
1 0 1 0 0 1 1 1 0 1 1 1 1 0 1 1 0 0 0 1 0 0 1 1 1 1 1 1 1 0 0 0 1 1 0 1 1 1 ←-
1 0 1 1' />
PostGIS 3.3.2 Manual 241 / 902
</IndexedFaceSet>
</Shape>
</Transform>
</Scene>
</X3D>
PostGIS buildings
Copy and paste the output of this query to x3d scene viewer and click Show
SELECT string_agg('<Shape>' || ST_AsX3D(ST_Extrude(geom, 0,0, i*0.5)) ||
'<Appearance>
<Material diffuseColor="' || (0.01*i)::text || ' 0.8 0.2" specularColor="' || ←-
(0.05*i)::text || ' 0 0.5"/>
</Appearance>
</Shape>', '')
FROM ST_Subdivide(ST_Letters('PostGIS'),20) WITH ORDINALITY AS f(geom,i);
SELECT ST_AsX3D(
ST_Translate(
ST_Force_3d(
ST_Buffer(ST_Point(10,10),5, 'quad_segs=2')), 0,0,
3)
,6) As x3dfrag;
x3dfrag
--------
<IndexedFaceSet coordIndex="0 1 2 3 4 5 6 7">
<Coordinate point="15 10 3 13.535534 6.464466 3 10 5 3 6.464466 6.464466 3 5 10 3 ←-
6.464466 13.535534 3 10 15 3 13.535534 13.535534 3 " />
</IndexedFaceSet>
Example: TIN
0 1 0,
1 1 0,
0 0 0
))
)')) As x3dfrag;
x3dfrag
--------
<IndexedTriangleSet index='0 1 2 3 4 5'><Coordinate point='0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 1 ←-
1 0'/></IndexedTriangleSet>
SELECT ST_AsX3D(
ST_GeomFromEWKT('MULTILINESTRING((20 0 10,16 -12 10,0 -16 10,-12 -12 10,-20 0 ←-
10,-12 16 10,0 24 10,16 16 10,20 0 10),
(12 0 10,8 8 10,0 12 10,-8 8 10,-8 0 10,-8 -4 10,0 -8 10,8 -4 10,12 0 10))')
) As x3dfrag;
x3dfrag
--------
<IndexedLineSet coordIndex='0 1 2 3 4 5 6 7 0 -1 8 9 10 11 12 13 14 15 8'>
<Coordinate point='20 0 10 16 -12 10 0 -16 10 -12 -12 10 -20 0 10 -12 16 10 0 24 10 16 ←-
16 10 12 0 10 8 8 10 0 12 10 -8 8 10 -8 0 10 -8 -4 10 0 -8 10 8 -4 10 ' />
</IndexedLineSet>
8.9.3.14 ST_GeoHash
Synopsis
Description
Return a GeoHash representation (http://en.wikipedia.org/wiki/Geohash) of the geometry. A GeoHash encodes a point into a text
form that is sortable and searchable based on prefixing. A shorter GeoHash is a less precise representation of a point. It can also
be thought of as a box, that contains the actual point.
If no maxchars is specified ST_GeoHash returns a GeoHash based on full precision of the input geometry type. Points return
a GeoHash with 20 characters of precision (about enough to hold the full double precision of the input). Other types return a
GeoHash with a variable amount of precision, based on the size of the feature. Larger features are represented with less precision,
smaller features with more precision. The idea is that the box implied by the GeoHash will always contain the input feature.
If maxchars is specified ST_GeoHash returns a GeoHash with at most that many characters so a possibly lower precision
representation of the input geometry. For non-points, the starting point of the calculation is the center of the bounding box of the
geometry.
Availability: 1.4.0
Note
ST_GeoHash will not work with geometries that are not in geographic (lon/lat) coordinates.
Examples
SELECT ST_GeoHash(ST_SetSRID(ST_Point(-126,48),4326));
st_geohash
----------------------
c0w3hf1s70w3hf1s70w3
SELECT ST_GeoHash(ST_SetSRID(ST_Point(-126,48),4326),5);
st_geohash
------------
c0w3h
See Also
ST_GeomFromGeoHash
8.10 Operators
8.10.1.1 &&
&& — Returns TRUE if A’s 2D bounding box intersects B’s 2D bounding box.
Synopsis
Description
The && operator returns TRUE if the 2D bounding box of geometry A intersects the 2D bounding box of geometry B.
Note
This operand will make use of any indexes that may be available on the geometries.
Examples
See Also
8.10.1.2 &&(geometry,box2df)
&&(geometry,box2df) — Returns TRUE if a geometry’s (cached) 2D bounding box intersects a 2D float precision bounding box
(BOX2DF).
Synopsis
Description
The && operator returns TRUE if the cached 2D bounding box of geometry A intersects the 2D bounding box B, using float
precision. This means that if B is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box
(BOX2DF)
Note
This operand is intended to be used internally by BRIN indexes, more than by users.
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
Examples
overlaps
----------
t
(1 row)
PostGIS 3.3.2 Manual 245 / 902
See Also
8.10.1.3 &&(box2df,geometry)
&&(box2df,geometry) — Returns TRUE if a 2D float precision bounding box (BOX2DF) intersects a geometry’s (cached) 2D
bounding box.
Synopsis
Description
The && operator returns TRUE if the 2D bounding box A intersects the cached 2D bounding box of geometry B, using float
precision. This means that if A is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box
(BOX2DF)
Note
This operand is intended to be used internally by BRIN indexes, more than by users.
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
Examples
overlaps
----------
t
(1 row)
See Also
8.10.1.4 &&(box2df,box2df)
&&(box2df,box2df) — Returns TRUE if two 2D float precision bounding boxes (BOX2DF) intersect each other.
Synopsis
Description
The && operator returns TRUE if two 2D bounding boxes A and B intersect each other, using float precision. This means that if
A (or B) is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
Note
This operator is intended to be used internally by BRIN indexes, more than by users.
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
Examples
overlaps
----------
t
(1 row)
See Also
8.10.1.5 &&&
&&& — Returns TRUE if A’s n-D bounding box intersects B’s n-D bounding box.
Synopsis
Description
The &&& operator returns TRUE if the n-D bounding box of geometry A intersects the n-D bounding box of geometry B.
Note
This operand will make use of any indexes that may be available on the geometries.
Availability: 2.0.0
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples: 3D LineStrings
Examples: 3M LineStrings
See Also
&&
8.10.1.6 &&&(geometry,gidx)
&&&(geometry,gidx) — Returns TRUE if a geometry’s (cached) n-D bounding box intersects a n-D float precision bounding
box (GIDX).
Synopsis
Description
The &&& operator returns TRUE if the cached n-D bounding box of geometry A intersects the n-D bounding box B, using float
precision. This means that if B is a (double precision) box3d, it will be internally converted to a float precision 3D bounding box
(GIDX)
Note
This operator is intended to be used internally by BRIN indexes, more than by users.
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
overlaps
----------
t
(1 row)
See Also
&&&(gidx,geometry), &&&(gidx,gidx)
8.10.1.7 &&&(gidx,geometry)
&&&(gidx,geometry) — Returns TRUE if a n-D float precision bounding box (GIDX) intersects a geometry’s (cached) n-D
bounding box.
Synopsis
Description
The &&& operator returns TRUE if the n-D bounding box A intersects the cached n-D bounding box of geometry B, using float
precision. This means that if A is a (double precision) box3d, it will be internally converted to a float precision 3D bounding box
(GIDX)
Note
This operator is intended to be used internally by BRIN indexes, more than by users.
PostGIS 3.3.2 Manual 249 / 902
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
overlaps
----------
t
(1 row)
See Also
&&&(geometry,gidx), &&&(gidx,gidx)
8.10.1.8 &&&(gidx,gidx)
&&&(gidx,gidx) — Returns TRUE if two n-D float precision bounding boxes (GIDX) intersect each other.
Synopsis
Description
The &&& operator returns TRUE if two n-D bounding boxes A and B intersect each other, using float precision. This means that
if A (or B) is a (double precision) box3d, it will be internally converted to a float precision 3D bounding box (GIDX)
Note
This operator is intended to be used internally by BRIN indexes, more than by users.
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
overlaps
----------
t
(1 row)
See Also
&&&(geometry,gidx), &&&(gidx,geometry)
8.10.1.9 &<
&< — Returns TRUE if A’s bounding box overlaps or is to the left of B’s.
Synopsis
Description
The &< operator returns TRUE if the bounding box of geometry A overlaps or is to the left of the bounding box of geometry B,
or more accurately, overlaps or is NOT to the right of the bounding box of geometry B.
Note
This operand will make use of any indexes that may be available on the geometries.
Examples
See Also
8.10.1.10 &<|
Synopsis
Description
The &<| operator returns TRUE if the bounding box of geometry A overlaps or is below of the bounding box of geometry B, or
more accurately, overlaps or is NOT above the bounding box of geometry B.
Note
This operand will make use of any indexes that may be available on the geometries.
Examples
See Also
8.10.1.11 &>
Synopsis
Description
The &> operator returns TRUE if the bounding box of geometry A overlaps or is to the right of the bounding box of geometry B,
or more accurately, overlaps or is NOT to the left of the bounding box of geometry B.
Note
This operand will make use of any indexes that may be available on the geometries.
Examples
See Also
8.10.1.12 <<
<< — Returns TRUE if A’s bounding box is strictly to the left of B’s.
Synopsis
Description
The << operator returns TRUE if the bounding box of geometry A is strictly to the left of the bounding box of geometry B.
Note
This operand will make use of any indexes that may be available on the geometries.
PostGIS 3.3.2 Manual 253 / 902
Examples
See Also
8.10.1.13 <<|
Synopsis
Description
The <<| operator returns TRUE if the bounding box of geometry A is strictly below the bounding box of geometry B.
Note
This operand will make use of any indexes that may be available on the geometries.
Examples
See Also
8.10.1.14 =
= — Returns TRUE if the coordinates and coordinate order geometry/geography A are the same as the coordinates and coordinate
order of geometry/geography B.
Synopsis
Description
The = operator returns TRUE if the coordinates and coordinate order geometry/geography A are the same as the coordinates and
coordinate order of geometry/geography B. PostgreSQL uses the =, <, and > operators defined for geometries to perform internal
orderings and comparison of geometries (ie. in a GROUP BY or ORDER BY clause).
Note
Only geometry/geography that are exactly equal in all respects, with the same coordinates, in the same order, are
considered equal by this operator. For "spatial equality", that ignores things like coordinate order, and can detect
features that cover the same spatial area with different representations, use ST_OrderingEquals or ST_Equals
Caution
This operand will NOT make use of any indexes that may be available on the geometries. For an index assisted exact
equality test, combine = with &&.
Changed: 2.4.0, in prior versions this was bounding box equality not a geometric equality. If you need bounding box equality,
use ~= instead.
Examples
SELECT ST_AsText(column1)
FROM ( VALUES
('LINESTRING(0 0, 1 1)'::geometry),
('LINESTRING(1 1, 0 0)'::geometry)) AS foo;
st_astext
---------------------
LINESTRING(0 0,1 1)
LINESTRING(1 1,0 0)
PostGIS 3.3.2 Manual 255 / 902
(2 rows)
-- Note: the GROUP BY uses the "=" to compare for geometry equivalency.
SELECT ST_AsText(column1)
FROM ( VALUES
('LINESTRING(0 0, 1 1)'::geometry),
('LINESTRING(1 1, 0 0)'::geometry)) AS foo
GROUP BY column1;
st_astext
---------------------
LINESTRING(0 0,1 1)
LINESTRING(1 1,0 0)
(2 rows)
--pt_intersect --
f
See Also
ST_Equals, ST_OrderingEquals, ~=
8.10.1.15 >>
>> — Returns TRUE if A’s bounding box is strictly to the right of B’s.
Synopsis
Description
The >> operator returns TRUE if the bounding box of geometry A is strictly to the right of the bounding box of geometry B.
Note
This operand will make use of any indexes that may be available on the geometries.
Examples
1 | 2 | t
1 | 3 | f
1 | 4 | f
(3 rows)
See Also
8.10.1.16 @
Synopsis
Description
The @ operator returns TRUE if the bounding box of geometry A is completely contained by the bounding box of geometry B.
Note
This operand will make use of any indexes that may be available on the geometries.
Examples
See Also
~, &&
8.10.1.17 @(geometry,box2df)
@(geometry,box2df) — Returns TRUE if a geometry’s 2D bounding box is contained into a 2D float precision bounding box
(BOX2DF).
PostGIS 3.3.2 Manual 257 / 902
Synopsis
Description
The @ operator returns TRUE if the A geometry’s 2D bounding box is contained the 2D bounding box B, using float precision.
This means that if B is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
Note
This operand is intended to be used internally by BRIN indexes, more than by users.
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
Examples
is_contained
--------------
t
(1 row)
See Also
8.10.1.18 @(box2df,geometry)
@(box2df,geometry) — Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into a geometry’s 2D
bounding box.
Synopsis
Description
The @ operator returns TRUE if the 2D bounding box A is contained into the B geometry’s 2D bounding box, using float precision.
This means that if B is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
Note
This operand is intended to be used internally by BRIN indexes, more than by users.
PostGIS 3.3.2 Manual 258 / 902
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
Examples
is_contained
--------------
t
(1 row)
See Also
8.10.1.19 @(box2df,box2df)
@(box2df,box2df) — Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into another 2D float precision
bounding box.
Synopsis
Description
The @ operator returns TRUE if the 2D bounding box A is contained into the 2D bounding box B, using float precision. This means
that if A (or B) is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
Note
This operand is intended to be used internally by BRIN indexes, more than by users.
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
Examples
is_contained
--------------
t
(1 row)
PostGIS 3.3.2 Manual 259 / 902
See Also
8.10.1.20 |&>
Synopsis
Description
The |&> operator returns TRUE if the bounding box of geometry A overlaps or is above the bounding box of geometry B, or
more accurately, overlaps or is NOT below the bounding box of geometry B.
Note
This operand will make use of any indexes that may be available on the geometries.
Examples
See Also
8.10.1.21 |>>
Synopsis
Description
The |>> operator returns TRUE if the bounding box of geometry A is strictly above the bounding box of geometry B.
Note
This operand will make use of any indexes that may be available on the geometries.
Examples
See Also
8.10.1.22 ~
Synopsis
Description
The ~ operator returns TRUE if the bounding box of geometry A completely contains the bounding box of geometry B.
Note
This operand will make use of any indexes that may be available on the geometries.
PostGIS 3.3.2 Manual 261 / 902
Examples
See Also
@, &&
8.10.1.23 ~(geometry,box2df)
~(geometry,box2df) — Returns TRUE if a geometry’s 2D bonding box contains a 2D float precision bounding box (GIDX).
Synopsis
Description
The ~ operator returns TRUE if the 2D bounding box of a geometry A contains the 2D bounding box B, using float precision.
This means that if B is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
Note
This operand is intended to be used internally by BRIN indexes, more than by users.
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
Examples
contains
----------
t
(1 row)
PostGIS 3.3.2 Manual 262 / 902
See Also
8.10.1.24 ~(box2df,geometry)
~(box2df,geometry) — Returns TRUE if a 2D float precision bounding box (BOX2DF) contains a geometry’s 2D bonding box.
Synopsis
Description
The ~ operator returns TRUE if the 2D bounding box A contains the B geometry’s bounding box, using float precision. This
means that if A is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
Note
This operand is intended to be used internally by BRIN indexes, more than by users.
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
Examples
contains
----------
t
(1 row)
See Also
8.10.1.25 ~(box2df,box2df)
~(box2df,box2df) — Returns TRUE if a 2D float precision bounding box (BOX2DF) contains another 2D float precision bounding
box (BOX2DF).
Synopsis
Description
The ~ operator returns TRUE if the 2D bounding box A contains the 2D bounding box B, using float precision. This means that
if A is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
Note
This operand is intended to be used internally by BRIN indexes, more than by users.
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
Examples
contains
----------
t
(1 row)
See Also
8.10.1.26 ~=
Synopsis
Description
The ~= operator returns TRUE if the bounding box of geometry/geography A is the same as the bounding box of geometry/geog-
raphy B.
Note
This operand will make use of any indexes that may be available on the geometries.
Warning
This operator has changed behavior in PostGIS 1.5 from testing for actual geometric equality to only checking for
bounding box equality. To complicate things it also depends on if you have done a hard or soft upgrade which behavior
your database has. To find out which behavior your database has you can run the query below. To check for true
equality use ST_OrderingEquals or ST_Equals.
Examples
See Also
ST_Equals, ST_OrderingEquals, =
8.10.2.1 <->
Synopsis
Description
The <-> operator returns the 2D distance between two geometries. Used in the "ORDER BY" clause provides index-assisted
nearest-neighbor result sets. For PostgreSQL below 9.5 only gives centroid distance of bounding boxes and for PostgreSQL 9.5+,
does true KNN distance search giving true distance between geometries, and distance sphere for geographies.
Note
This operand will make use of 2D GiST indexes that may be available on the geometries. It is different from other
operators that use spatial indexes in that the spatial index is only used when the operator is in the ORDER BY clause.
Note
Index only kicks in if one of the geometries is a constant (not in a subquery/cte). e.g. ’SRID=3005;POINT(1011102
450541)’::geometry instead of a.geom
Changed: 2.2.0 -- For PostgreSQL 9.5 users, old Hybrid syntax may be slower, so you’ll want to get rid of that hack if you are
running your code only on PostGIS 2.2+ 9.5+. See examples below.
Availability: 2.0.0 -- Weak KNN provides nearest neighbors based on geometry centroid distances instead of true distances.
Exact results for points, inexact for all other types. Available for PostgreSQL 9.1+
Examples
d | edabbr | vaabbr
------------------+--------+--------
0 | ALQ | 128
5541.57712511724 | ALQ | 129A
5579.67450712005 | ALQ | 001
6083.4207708641 | ALQ | 131
7691.2205404848 | ALQ | 003
7900.75451037313 | ALQ | 122
8694.20710669982 | ALQ | 129B
9564.24289057111 | ALQ | 130
12089.665931705 | ALQ | 127
18472.5531479404 | ALQ | 002
(10 rows)
d | edabbr | vaabbr
------------------+--------+--------
0 | ALQ | 128
5541.57712511724 | ALQ | 129A
5579.67450712005 | ALQ | 001
6083.4207708641 | ALQ | 131
7691.2205404848 | ALQ | 003
7900.75451037313 | ALQ | 122
8694.20710669982 | ALQ | 129B
9564.24289057111 | ALQ | 130
12089.665931705 | ALQ | 127
18472.5531479404 | ALQ | 002
(10 rows)
If you run "EXPLAIN ANALYZE" on the two queries you would see a performance improvement for the second.
For users running with PostgreSQL < 9.5, use a hybrid query to find the true nearest neighbors. First a CTE query using the
index-assisted KNN, then an exact query to get correct ordering:
WITH index_query AS (
SELECT ST_Distance(geom, 'SRID=3005;POINT(1011102 450541)'::geometry) as d,edabbr, vaabbr
FROM va2005
ORDER BY geom <-> 'SRID=3005;POINT(1011102 450541)'::geometry LIMIT 100)
SELECT *
FROM index_query
ORDER BY d limit 10;
d | edabbr | vaabbr
------------------+--------+--------
0 | ALQ | 128
PostGIS 3.3.2 Manual 266 / 902
See Also
8.10.2.2 |=|
|=| — Returns the distance between A and B trajectories at their closest point of approach.
Synopsis
Description
The |=| operator returns the 3D distance between two trajectories (See ST_IsValidTrajectory). This is the same as ST_DistanceCPA
but as an operator it can be used for doing nearest neighbor searches using an N-dimensional index (requires PostgreSQL 9.5.0
or higher).
Note
This operand will make use of ND GiST indexes that may be available on the geometries. It is different from other
operators that use spatial indexes in that the spatial index is only used when the operator is in the ORDER BY clause.
Note
Index only kicks in if one of the geometries is a constant (not in a subquery/cte). e.g. ’SRID=3005;LINESTRINGM(0 0
0,0 0 1)’::geometry instead of a.geom
Examples
) foo;
track_id dist
----------+-------------------
395 | 0.576496831518066
380 | 5.06797130410151
390 | 7.72262293958322
385 | 9.8004461358071
405 | 10.9534397988433
(5 rows)
See Also
8.10.2.3 <#>
Synopsis
Description
The <#> operator returns distance between two floating point bounding boxes, possibly reading them from a spatial index
(PostgreSQL 9.1+ required). Useful for doing nearest neighbor approximate distance ordering.
Note
This operand will make use of any indexes that may be available on the geometries. It is different from other operators
that use spatial indexes in that the spatial index is only used when the operator is in the ORDER BY clause.
Note
Index only kicks in if one of the geometries is a constant e.g. ORDER BY (ST_GeomFromText(’POINT(1 2)’) <#> geom)
instead of g1.geom <#>.
Examples
SELECT *
FROM (
SELECT b.tlid, b.mtfcc,
b.geom <#> ST_GeomFromText('LINESTRING(746149 2948672,745954 2948576,
745787 2948499,745740 2948468,745712 2948438,
745690 2948384,745677 2948319)',2249) As b_dist,
ST_Distance(b.geom, ST_GeomFromText('LINESTRING(746149 2948672,745954 2948576,
745787 2948499,745740 2948468,745712 2948438,
745690 2948384,745677 2948319)',2249)) As act_dist
FROM bos_roads As b
ORDER BY b_dist, b.tlid
LIMIT 100) As foo
PostGIS 3.3.2 Manual 268 / 902
See Also
8.10.2.4 <<->>
<<->> — Returns the n-D distance between the centroids of A and B bounding boxes.
Synopsis
Description
The <<->> operator returns the n-D (euclidean) distance between the centroids of the bounding boxes of two geometries. Useful
for doing nearest neighbor approximate distance ordering.
Note
This operand will make use of n-D GiST indexes that may be available on the geometries. It is different from other
operators that use spatial indexes in that the spatial index is only used when the operator is in the ORDER BY clause.
Note
Index only kicks in if one of the geometries is a constant (not in a subquery/cte). e.g. ’SRID=3005;POINT(1011102
450541)’::geometry instead of a.geom
See Also
<<#>>, <->
8.10.2.5 <<#>>
Synopsis
Description
The <<#>> operator returns distance between two floating point bounding boxes, possibly reading them from a spatial index
(PostgreSQL 9.1+ required). Useful for doing nearest neighbor approximate distance ordering.
Note
This operand will make use of any indexes that may be available on the geometries. It is different from other operators
that use spatial indexes in that the spatial index is only used when the operator is in the ORDER BY clause.
Note
Index only kicks in if one of the geometries is a constant e.g. ORDER BY (ST_GeomFromText(’POINT(1 2)’) <<#>>
geom) instead of g1.geom <<#>>.
See Also
<<->>, <#>
8.11.1.1 ST_3DIntersects
ST_3DIntersects — Tests if two geometries spatially intersect in 3D - only for points, linestrings, polygons, polyhedral surface
(area).
Synopsis
Description
Overlaps, Touches, Within all imply spatial intersection. If any of the aforementioned returns true, then the geometries also
spatially intersect. Disjoint implies false for spatial intersection.
Note
This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available
on the geometries.
PostGIS 3.3.2 Manual 270 / 902
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1
Geometry Examples
TIN Examples
See Also
ST_Intersects
8.11.1.2 ST_Contains
ST_Contains — Tests if no points of B lie in the exterior of A, and A and B have at least one interior point in common.
Synopsis
Description
Returns TRUE if geometry B is completely inside geometry A. A contains B if and only if no points of B lie in the exterior of A,
and at least one point of the interior of B lies in the interior of A.
A subtlety of the definition is that a geometry does not contain things in its boundary. Thus polygons and lines do not contain lines
and points lying in their boundary. For further details see Subtleties of OGC Covers, Contains, Within. (The ST_Covers predicate
provides a more inclusive relationship.) However, a geometry does contain itself. (In contrast, in the ST_ContainsProperly
predicate a geometry does not properly contain itself.)
ST_Contains is the inverse of ST_Within. So, ST_Contains(A,B) = ST_Within(B,A).
PostGIS 3.3.2 Manual 271 / 902
Note
This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available
on the geometries. To avoid index use, use the function _ST_Contains.
Important
Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION
Important
Do not use this function with invalid geometries. You will get unexpected results.
NOTE: this is the "allowable" version that returns a boolean, not an integer.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 // s2.1.13.3 - same
as within(geometry B, geometry A)
Examples
-- Result
smallcontainsbig | bigcontainssmall | bigcontainsunion | bigisunion | bigcoversexterior | ←-
bigcontainsexterior
PostGIS 3.3.2 Manual 273 / 902
------------------+------------------+------------------+------------+-------------------+-----------
f | t | t | t | t | f
See Also
8.11.1.3 ST_ContainsProperly
ST_ContainsProperly — Tests if B intersects the interior of A but not the boundary or exterior.
Synopsis
Description
Returns true if B intersects the interior of A but not the boundary or exterior.
A does not properly contain itself, but does contain itself.
Every point of the other geometry is a point of this geometry’s interior. The DE-9IM Intersection Matrix for the two geometries
matches [T**FF*FF*] used in ST_Relate
An example use case for this predicate is computing the intersections of a set of geometries with a large polygonal geometry.
Since intersection is a fairly slow operation, it can be more efficient to use containsProperly to filter out test geometries which lie
wholly inside the area. In these cases the intersection is known a priori to be exactly the original test geometry.
Note
This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available
on the geometries. To avoid index use, use the function _ST_ContainsProperly.
Note
The advantage of this predicate over ST_Contains and ST_Intersects is that it can be computed more efficiently, with
no need to compute topology at individual points.
PostGIS 3.3.2 Manual 274 / 902
Important
Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION
Important
Do not use this function with invalid geometries. You will get unexpected results.
Examples
f | t | f | t | t ←-
| f
See Also
8.11.1.4 ST_CoveredBy
Synopsis
Description
Returns true if no point in Geometry/Geography A lies outside Geometry/Geography B. Equivalently, tests if every point of
geometry A is inside (i.e. intersects the interior or boundary of) geometry B.
Note
This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available
on the geometries. To avoid index use, use the function _ST_CoveredBy.
Important
Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION
Important
Do not use this function with invalid geometries. You will get unexpected results.
Examples
See Also
8.11.1.5 ST_Covers
Synopsis
Description
Returns true if no point in Geometry/Geography B is outside Geometry/Geography A. Equivalently, tests if every point of
geometry B is inside (i.e. intersects the interior or boundary of) geometry A.
Note
This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available
on the geometries. To avoid index use, use the function _ST_Covers.
Important
Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION
Important
Do not use this function with invalid geometries. You will get unexpected results.
Examples
Geometry example
--a circle covering a circle
SELECT ST_Covers(smallc,smallc) As smallinsmall,
ST_Covers(smallc, bigc) As smallcoversbig,
ST_Covers(bigc, ST_ExteriorRing(bigc)) As bigcoversexterior,
ST_Contains(bigc, ST_ExteriorRing(bigc)) As bigcontainsexterior
FROM (SELECT ST_Buffer(ST_GeomFromText('POINT(1 2)'), 10) As smallc,
ST_Buffer(ST_GeomFromText('POINT(1 2)'), 20) As bigc) As foo;
--Result
smallinsmall | smallcoversbig | bigcoversexterior | bigcontainsexterior
--------------+----------------+-------------------+---------------------
t | f | t | f
(1 row)
PostGIS 3.3.2 Manual 277 / 902
Geeography Example
-- a point with a 300 meter buffer compared to a point, a point and its 10 meter buffer
SELECT ST_Covers(geog_poly, geog_pt) As poly_covers_pt,
ST_Covers(ST_Buffer(geog_pt,10), geog_pt) As buff_10m_covers_cent
FROM (SELECT ST_Buffer(ST_GeogFromText('SRID=4326;POINT(-99.327 31.4821)'), 300) As ←-
geog_poly,
ST_GeogFromText('SRID=4326;POINT(-99.33 31.483)') As geog_pt ) As foo;
poly_covers_pt | buff_10m_covers_cent
----------------+------------------
f | t
See Also
8.11.1.6 ST_Crosses
ST_Crosses — Tests if two geometries have some, but not all, interior points in common.
Synopsis
Description
Compares two geometry objects and returns true if their intersection "spatially cross", that is, the geometries have some, but
not all interior points in common. The intersection of the interiors of the geometries must be non-empty and must have dimension
less than the maximum dimension of the two input geometries. Additionally, the intersection of the two geometries must not
equal either of the source geometries. Otherwise, it returns false.
In mathematical terms, this is:
Note
This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available
on the geometries.
PostGIS 3.3.2 Manual 278 / 902
Important
Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.13.3
Examples
Consider a situation where a user has two tables: a table of roads and a table of highways.
To determine a list of roads that cross a highway, use a query similiar to:
SELECT roads.id
FROM roads, highways
WHERE ST_Crosses(roads.geom, highways.geom);
See Also
ST_Contains, ST_Overlaps
8.11.1.7 ST_Disjoint
ST_Disjoint — Tests if two geometries are disjoint (they have no point in common).
Synopsis
Description
Overlaps, Touches, Within all imply geometries are not spatially disjoint. If any of the aforementioned returns true, then the
geometries are not spatially disjoint. Disjoint implies false for spatial intersection.
Important
Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION
Note
This function call does not use indexes
Note
NOTE: this is the "allowable" version that returns a boolean, not an integer.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 //s2.1.13.3 -
a.Relate(b, ’FF*FF****’)
Examples
See Also
ST_Intersects
8.11.1.8 ST_Equals
Synopsis
Description
Returns true if the given geometries are "spatially equal". Use this for a ’better’ answer than ’=’. Note by spatially equal we
mean ST_Within(A,B) = true and ST_Within(B,A) = true and also mean ordering of points can be different but represent the same
geometry structure. To verify the order of points is consistent, use ST_OrderingEquals (it must be noted ST_OrderingEquals is
a little more stringent than simply verifying order of points are the same).
Important
Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.2
Examples
st_equals
-----------
t
(1 row)
See Also
8.11.1.9 ST_Intersects
ST_Intersects — Tests if two geometries intersect (they have at least one point in common).
Synopsis
Description
Compares two geometries and returns true if they intersect. Geometries intersect if they have any point in common.
For geography, a distance tolerance of 0.00001 meters is used (so points that are very close are considered to intersect).
Geometries intersect if their DE-9IM Intersection Matrix matches one of:
• T********
• *T*******
• ***T*****
• ****T****
Spatial intersection is implied by all the other spatial relationship tests, except ST_Disjoint, which tests that geometries do NOT
intersect.
Note
This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available
on the geometries.
Changed: 3.0.0 SFCGAL version removed and native support for 2D TINS added.
Enhanced: 2.5.0 Supports GEOMETRYCOLLECTION.
Enhanced: 2.3.0 Enhancement to PIP short-circuit extended to support MultiPoints with few points. Prior versions only supported
point in polygon.
Performed by the GEOS module (for geometry), geography is native
Availability: 1.5 support for geography was introduced.
Note
For geography, this function has a distance tolerance of about 0.00001 meters and uses the sphere rather than spheroid
calculation.
PostGIS 3.3.2 Manual 282 / 902
Note
NOTE: this is the "allowable" version that returns a boolean, not an integer.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 //s2.1.13.3 -
ST_Intersects(g1, g2 ) --> Not (ST_Disjoint(g1, g2 ))
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Geometry Examples
-- Look up in table. Make sure table has a GiST index on geometry column for faster lookup.
SELECT id, name FROM cities WHERE ST_Intersects(geom, 'SRID=4326;POLYGON((28 53,27.707 ←-
52.293,27 52,26.293 52.293,26 53,26.293 53.707,27 54,27.707 53.707,28 53))');
id | name
----+-------
2 | Minsk
(1 row)
Geography Examples
SELECT ST_Intersects(
'SRID=4326;LINESTRING(-43.23456 72.4567,-43.23456 72.4568)'::geography,
'SRID=4326;POINT(-43.23456 72.4567772)'::geography
);
st_intersects
---------------
t
See Also
8.11.1.10 ST_LineCrossingDirection
Synopsis
Description
Given two linestrings returns an integer between -3 and 3 indicating what kind of crossing behavior exists between them. 0
indicates no crossing. This is only supported for LINESTRINGs.
The crossing number has the following meaning:
• 0: LINE NO CROSS
• -1: LINE CROSS LEFT
• 1: LINE CROSS RIGHT
• -2: LINE MULTICROSS END LEFT
• 2: LINE MULTICROSS END RIGHT
• -3: LINE MULTICROSS END SAME FIRST LEFT
• 3: LINE MULTICROSS END SAME FIRST RIGHT
Availability: 1.4
Examples
A_cross_B | B_cross_A
-----------+-----------
-1 | 1
PostGIS 3.3.2 Manual 284 / 902
Example: LINE MULTICROSS END SAME FIRST LEFT and LINE MULTICROSS END SAME FIRST RIGHT
A_cross_B | B_cross_A
-----------+-----------
3 | -3
Example: LINE MULTICROSS END LEFT and LINE MULTICROSS END RIGHT
A_cross_B | B_cross_A
-----------+-----------
-2 | 2
Example: LINE MULTICROSS END LEFT and LINE MULTICROSS END RIGHT
A_cross_B | B_cross_A
-----------+-----------
2 | -2
See Also
ST_Crosses
8.11.1.11 ST_OrderingEquals
ST_OrderingEquals — Tests if two geometries represent the same geometry and have points in the same directional order.
Synopsis
Description
ST_OrderingEquals compares two geometries and returns t (TRUE) if the geometries are equal and the coordinates are in the
same order; otherwise it returns f (FALSE).
Note
This function is implemented as per the ArcSDE SQL specification rather than SQL-MM.
http://edndoc.esri.com/arcsde/9.1/sql_api/sqlapi3.htm#ST_OrderingEquals
Examples
See Also
8.11.1.12 ST_Overlaps
ST_Overlaps — Tests if two geometries intersect and have the same dimension, but are not completely contained by each other.
Synopsis
Description
Returns TRUE if geometry A and B "spatially overlap". Two geometries overlap if they have the same dimension, each has at
least one point not shared by the other (or equivalently neither covers the other), and the intersection of their interiors has the
same dimension. The overlaps relationship is symmetrical.
PostGIS 3.3.2 Manual 287 / 902
Note
This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available
on the geometries. To avoid index use, use the function _ST_Overlaps.
Important
Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION
NOTE: this is the "allowable" version that returns a boolean, not an integer.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 // s2.1.13.3
Examples
A Point on a LineString is contained, but since it has lower dimension it does not overlap or cross.
SELECT ST_Overlaps(a,b) AS overlaps, ST_Crosses(a,b) AS crosses,
ST_Intersects(a, b) AS intersects, ST_Contains(b,a) AS b_contains_a
FROM (SELECT ST_GeomFromText('POINT (100 100)') As a,
ST_GeomFromText('LINESTRING (30 50, 40 160, 160 40, 180 160)') AS b) AS t
A LineString that partly covers a Polygon intersects and crosses, but does not overlap since it has different dimension.
SELECT ST_Overlaps(a,b) AS overlaps, ST_Crosses(a,b) AS crosses,
ST_Intersects(a, b) AS intersects, ST_Contains(a,b) AS contains
FROM (SELECT ST_GeomFromText('POLYGON ((40 170, 90 30, 180 100, 40 170))') AS a,
ST_GeomFromText('LINESTRING(10 10, 190 190)') AS b) AS t;
Two Polygons that intersect but with neither contained by the other overlap, but do not cross because their intersection has the
same dimension.
SELECT ST_Overlaps(a,b) AS overlaps, ST_Crosses(a,b) AS crosses,
ST_Intersects(a, b) AS intersects, ST_Contains(b, a) AS b_contains_a,
ST_Dimension(a) AS dim_a, ST_Dimension(b) AS dim_b,
ST_Dimension(ST_Intersection(a,b)) AS dim_int
FROM (SELECT ST_GeomFromText('POLYGON ((40 170, 90 30, 180 100, 40 170))') AS a,
ST_GeomFromText('POLYGON ((110 180, 20 60, 130 90, 110 180))') AS b) As t;
See Also
8.11.1.13 ST_Relate
ST_Relate — Tests if two geometries have a topological relationship matching an Intersection Matrix pattern, or computes their
Intersection Matrix
Synopsis
Description
These functions allow testing and evaluating the spatial (topological) relationship between two geometries, as defined by the
Dimensionally Extended 9-Intersection Model (DE-9IM).
The DE-9IM is specified as a 9-element matrix indicating the dimension of the intersections between the Interior, Boundary and
Exterior of two geometries. It is represented by a 9-character text string using the symbols ’F’, ’0’, ’1’, ’2’ (e.g. ’FF1FF0102’).
PostGIS 3.3.2 Manual 290 / 902
A specific kind of spatial relationships is evaluated by comparing the intersection matrix to an intersection matrix pattern.
A pattern can include the additional symbols ’T’ and ’*’. Common spatial relationships are provided by the named func-
tions ST_Contains, ST_ContainsProperly, ST_Covers, ST_CoveredBy, ST_Crosses, ST_Disjoint, ST_Equals, ST_Intersects,
ST_Overlaps, ST_Touches, and ST_Within. Using an explicit pattern allows testing multiple conditions of intersects, crosses,
etc in one step. It also allows testing spatial relationships which do not have a named spatial relationship function. For example,
the relationship "Interior-Intersects" has the DE-9IM pattern T********, which is not evaluated by any named predicate.
For more information refer to Section 5.1.
Variant 1: Tests if two geometries are spatially related according to the given intersectionMatrixPattern.
Note
Unlike most of the named spatial relationship predicates, this does NOT automatically include an index call. The reason
is that some relationships are true for geometries which do NOT intersect (e.g. Disjoint). If you are using a relationship
pattern that requires intersection, then include the && index call.
Note
It is better to use a named relationship function if available, since they automatically use a spatial index where one
exists. Also, they may implement performance optimizations which are not available with full relate evalation.
Variant 2: Returns the DE-9IM matrix string for the spatial relationship between the two input geometries. The matrix string
can be tested for matching a DE-9IM pattern using ST_RelateMatch.
Variant 3: Like variant 2, but allows specifying a Boundary Node Rule. A boundary node rule allows finer control over whether
geometry boundary points are considered to lie in the DE-9IM Interior or Boundary. The boundaryNodeRule code is: 1:
OGC/MOD2, 2: Endpoint, 3: MultivalentEndpoint, 4: MonovalentEndpoint.
This function is not in the OGC spec, but is implied. see s2.1.13.2
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 // s2.1.13.3
Important
Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION
Examples
Testing a custom spatial relationship pattern as a query condition, with && to enable using a spatial index.
-- Find compounds that properly intersect (not just touch) a poly (Interior Intersects)
See Also
Section 5.1, ST_RelateMatch, ST_Contains, ST_ContainsProperly, ST_Covers, ST_CoveredBy, ST_Crosses, ST_Disjoint, ST_Equals,
ST_Intersects, ST_Overlaps, ST_Touches, ST_Within
8.11.1.14 ST_RelateMatch
Synopsis
Description
Tests if a Dimensionally Extended 9-Intersection Model (DE-9IM) intersectionMatrix value satisfies an intersectionMatri
Intersection matrix values can be computed by ST_Relate.
For more information refer to Section 5.1.
Performed by the GEOS module
Availability: 2.0.0
Examples
Patterns for common spatial relationships matched against intersection matrix values, for a line in various positions relative to a
polygon
PostGIS 3.3.2 Manual 292 / 902
See Also
8.11.1.15 ST_Touches
ST_Touches — Tests if two geometries have at least one point in common, but their interiors do not intersect.
Synopsis
Description
Returns TRUE if A and B intersect, but their interiors do not intersect. Equivalently, A and B have at least one point in common,
and the common points lie in at least one boundary. For Point/Point inputs the relationship is always FALSE, since points do not
have a boundary.
In mathematical terms, this relationship is:
This relationship holds if the DE-9IM Intersection Matrix for the two geometries matches one of:
• FT*******
• F**T*****
• F***T****
PostGIS 3.3.2 Manual 293 / 902
Note
This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available
on the geometries. To avoid using an index, use _ST_Touches instead.
Important
Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 // s2.1.13.3
Examples
st_touches
------------
f
(1 row)
8.11.1.16 ST_Within
ST_Within — Tests if no points of A lie in the exterior of B, and A and B have at least one interior point in common.
Synopsis
Description
Returns TRUE if geometry A is completely inside geometry B. For this function to make sense, the source geometries must both
be of the same coordinate projection, having the same SRID. It is a given that if ST_Within(A,B) is true and ST_Within(B,A) is
true, then the two geometries are considered spatially equal.
A subtlety of this definition is that the boundary of a geometry is not within the geometry. This means that lines and points lying
in the boundary of a polygon or line are not within the geometry. For further details see Subtleties of OGC Covers, Contains,
Within. (The ST_CoveredBy predicate provides a more inclusive relationship).
ST_Within is the inverse of ST_Contains. So, ST_Within(A,B) = ST_Contains(B,A).
Note
This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available
on the geometries. To avoid index use, use the function _ST_Within.
Important
Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION
Important
Do not use this function with invalid geometries. You will get unexpected results.
NOTE: this is the "allowable" version that returns a boolean, not an integer.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 // s2.1.13.3 -
a.Relate(b, ’T*F**F***’)
Examples
See Also
8.11.2.1 ST_3DDWithin
Synopsis
Description
Returns true if the 3D distance between two geometry values is no larger than distance distance_of_srid. The distance is
specified in units defined by the spatial reference system of the geometries. For this function to make sense the source geometries
must be in the same coordinate system (have the same SRID).
PostGIS 3.3.2 Manual 296 / 902
Note
This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available
on the geometries.
Examples
-- Geometry example - units in meters (SRID: 2163 US National Atlas Equal area) (3D point ←-
and line compared 2D point and line)
-- Note: currently no vertical datum support so Z is not transformed and assumed to be same ←-
units as final.
SELECT ST_3DDWithin(
ST_Transform(ST_GeomFromEWKT('SRID=4326;POINT(-72.1235 42.3521 4)'),2163),
ST_Transform(ST_GeomFromEWKT('SRID=4326;LINESTRING(-72.1260 42.45 15, -72.123 42.1546 ←-
20)'),2163),
126.8
) As within_dist_3d,
ST_DWithin(
ST_Transform(ST_GeomFromEWKT('SRID=4326;POINT(-72.1235 42.3521 4)'),2163),
ST_Transform(ST_GeomFromEWKT('SRID=4326;LINESTRING(-72.1260 42.45 15, -72.123 42.1546 ←-
20)'),2163),
126.8
) As within_dist_2d;
within_dist_3d | within_dist_2d
----------------+----------------
f | t
See Also
8.11.2.2 ST_3DDFullyWithin
Synopsis
Description
Returns true if the 3D geometries are fully within the specified distance of one another. The distance is specified in units defined
by the spatial reference system of the geometries. For this function to make sense, the source geometries must both be of the
same coordinate projection, having the same SRID.
PostGIS 3.3.2 Manual 297 / 902
Note
This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available
on the geometries.
Availability: 2.0.0
Examples
-- This compares the difference between fully within and distance within as well
-- as the distance fully within for the 2D footprint of the line/point vs. the 3d fully ←-
within
SELECT ST_3DDFullyWithin(geom_a, geom_b, 10) as D3DFullyWithin10, ST_3DDWithin(geom_a, ←-
geom_b, 10) as D3DWithin10,
ST_DFullyWithin(geom_a, geom_b, 20) as D2DFullyWithin20,
ST_3DDFullyWithin(geom_a, geom_b, 20) as D3DFullyWithin20 from
(select ST_GeomFromEWKT('POINT(1 1 2)') as geom_a,
ST_GeomFromEWKT('LINESTRING(1 5 2, 2 7 20, 1 9 100, 14 12 3)') as geom_b) t1;
d3dfullywithin10 | d3dwithin10 | d2dfullywithin20 | d3dfullywithin20
------------------+-------------+------------------+------------------
f | t | t | f
See Also
8.11.2.3 ST_DFullyWithin
Synopsis
Description
Returns true if the geometries are entirely within the specified distance of one another. The distance is specified in units defined
by the spatial reference system of the geometries. For this function to make sense, the source geometries must both be of the
same coordinate projection, having the same SRID.
Note
This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available
on the geometries.
Availability: 1.5.0
PostGIS 3.3.2 Manual 298 / 902
Examples
-----------------
DFullyWithin10 | DWithin10 | DFullyWithin20 |
---------------+----------+---------------+
f | t | t |
See Also
8.11.2.4 ST_DWithin
Synopsis
Description
Note
Use ST_3DDWithin for 3D geometries.
Note
This function call includes a bounding box comparison that makes use of any indexes that are available on the geome-
tries.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
Availability: 1.5.0 support for geography was introduced
Enhanced: 2.1.0 improved speed for geography. See Making Geography faster for details.
Enhanced: 2.1.0 support for curved geometries was introduced.
Prior to 1.3, ST_Expand was commonly used in conjunction with && and ST_Distance to test for distance, and in pre-1.3.4 this
function used that logic. From 1.3.4, ST_DWithin uses a faster short-circuit distance function.
PostGIS 3.3.2 Manual 299 / 902
Examples
-- Find broadcasting towers that receiver with limited range can receive.
-- Data is geometry in Spherical Mercator (SRID=3857), ranges are approximate.
-- Create geometry index that will check proximity limit of user to tower
CREATE INDEX ON broadcasting_towers using gist (geom);
-- Create geometry index that will check proximity limit of tower to user
CREATE INDEX ON broadcasting_towers using gist (ST_Expand(geom, sending_range));
See Also
ST_Distance, ST_3DDWithin
8.11.2.5 ST_PointInsideCircle
ST_PointInsideCircle — Tests if a point geometry is inside a circle defined by a center and radius.
Synopsis
Description
Returns true if the geometry is a point and is inside the circle with center center_x,center_y and radius radius.
Warning
Does not use spatial indexes. Use ST_DWithin instead.
PostGIS 3.3.2 Manual 300 / 902
Availability: 1.2
Changed: 2.2.0 In prior versions this was called ST_Point_Inside_Circle
Examples
See Also
ST_DWithin
8.12.1 ST_Area
Synopsis
Description
Returns the area of a polygonal geometry. For geometry types a 2D Cartesian (planar) area is computed, with units specified by
the SRID. For geography types by default area is determined on a spheroid with units in square meters. To compute the area
using the faster but less accurate spherical model use ST_Area(geog,false).
Enhanced: 2.0.0 - support for 2D polyhedral surfaces was introduced.
Enhanced: 2.2.0 - measurement on spheroid performed with GeographicLib for improved accuracy and robustness. Requires
PROJ >= 4.9.0 to take advantage of the new feature.
Changed: 3.0.0 - does not depend on SFCGAL anymore.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
Note
For polyhedral surfaces, only supports 2D polyhedral surfaces (not 2.5D). For 2.5D, may give a non-zero answer, but
only for the faces that sit completely in XY plane.
PostGIS 3.3.2 Manual 301 / 902
Examples
Return area in square feet for a plot of Massachusetts land and multiply by conversion to get square meters. Note this is in square
feet because EPSG:2249 is Massachusetts State Plane Feet
select ST_Area(geom) sqft,
ST_Area(geom) * 0.3048 ^ 2 sqm
from (
select 'SRID=2249;POLYGON((743238 2967416,743238 2967450,
743265 2967450,743265.625 2967416,743238 2967416))' :: geometry geom
) subquery;
┌─────────┬─%
│ sqft │ sqm │
├─────────┼─%
│ 928.625 │ 86.27208552 │
└─────────┴─%
Return area square feet and transform to Massachusetts state plane meters (EPSG:26986) to get square meters. Note this is in
square feet because 2249 is Massachusetts State Plane Feet and transformed area is in square meters since EPSG:26986 is state
plane Massachusetts meters
select ST_Area(geom) sqft,
ST_Area(ST_Transform(geom, 26986)) As sqm
from (
select
'SRID=2249;POLYGON((743238 2967416,743238 2967450,
743265 2967450,743265.625 2967416,743238 2967416))' :: geometry geom
) subquery;
┌─────────┬─%
│ sqft │ sqm │
├─────────┼─%
│ 928.625 │ 86.272430607008 │
└─────────┴─%
Return area square feet and square meters using geography data type. Note that we transform to our geometry to geography
(before you can do that make sure your geometry is in WGS 84 long lat 4326). Geography always measures in meters. This is
just for demonstration to compare. Normally your table will be stored in geography data type already.
See Also
8.12.2 ST_Azimuth
Synopsis
Description
Returns the azimuth in radians of the target point from the origin point, or NULL if the two points are coincident. The azimuth
angle is a positive clockwise angle referenced from the positive Y axis (geometry) or the North meridian (geography): North =
0; Northeast = π/4; East = π/2; Southeast = 3π/4; South = π; Southwest 5π/4; West = 3π/2; Northwest = 7π/4.
For the geography type, the azimuth solution is known as the inverse geodesic problem.
The azimuth is a mathematical concept defined as the angle between a reference vector and a point, with angular units in radians.
The result value in radians can be converted to degrees using the PostgreSQL function degrees().
Azimuth can be used in conjunction with ST_Translate to shift an object along its perpendicular axis. See the upgis_lineshift()
function in the PostGIS wiki for an implementation of this.
Availability: 1.1.0
Enhanced: 2.0.0 support for geography was introduced.
Enhanced: 2.2.0 measurement on spheroid performed with GeographicLib for improved accuracy and robustness. Requires
PROJ >= 4.9.0 to take advantage of the new feature.
Examples
dega_b | degb_a
------------------+------------------
42.2736890060937 | 222.273689006094
PostGIS 3.3.2 Manual 303 / 902
Blue: origin Point(25,45); Green: target Point(75, 100); Blue: origin Point(75, 100); Green: target Point(25, 45);
Yellow: Y axis or North; Red: azimuth angle. Yellow: Y axis or North; Red: azimuth angle.
See Also
8.12.3 ST_Angle
ST_Angle — Returns the angle between two vectors defined by 3 or 4 points, or 2 lines.
Synopsis
Description
Examples
degrees
---------
270
degrees
-------------------
269.9999999999999
Angle between vectors defined by the start and end points of lines
SELECT degrees( ST_Angle('LINESTRING(0 0, 0.3 0.7, 1 1)', 'LINESTRING(0 0, 0.2 0.5, 1 0)') ←-
);
degrees
--------------
45
See Also
ST_Azimuth
8.12.4 ST_ClosestPoint
ST_ClosestPoint — Returns the 2D point on g1 that is closest to g2. This is the first point of the shortest line from one geometry
to the other.
Synopsis
Description
Returns the 2-dimensional point on geom1 that is closest to geom2. This is the first point of the shortest line between the
geometries (as computed by ST_ShortestLine).
Note
If you have a 3D Geometry, you may prefer to use ST_3DClosestPoint.
Availability: 1.5.0
PostGIS 3.3.2 Manual 305 / 902
Examples
The closest point for a Point and a LineString is the point itself. The closest point for a LineString and a Point is a point on the
line.
SELECT ST_AsText( ST_ClosestPoint(pt,line)) AS cp_pt_line,
ST_AsText( ST_ClosestPoint(line,pt)) AS cp_line_pt
FROM (SELECT 'POINT (160 40)'::geometry AS pt,
'LINESTRING (10 30, 50 50, 30 110, 70 90, 180 140, 130 190)'::geometry AS ←-
line ) AS t;
cp_pt_line | cp_line_pt
----------------+------------------------------------------
POINT(160 40) | POINT(125.75342465753425 115.34246575342466)
See Also
8.12.5 ST_3DClosestPoint
ST_3DClosestPoint — Returns the 3D point on g1 that is closest to g2. This is the first point of the 3D shortest line.
Synopsis
Description
Returns the 3-dimensional point on g1 that is closest to g2. This is the first point of the 3D shortest line. The 3D length of the
3D shortest line is the 3D distance.
Examples
cp3d_line_pt | ←-
cp2d_line_pt
-----------------------------------------------------------+--------------------------------------
cp3d_line_pt | cp2d_line_pt
-----------------------------------------------------------+--------------
POINT(54.6993798867619 128.935022917228 11.5475869506606) | POINT(50 75)
PostGIS 3.3.2 Manual 307 / 902
See Also
8.12.6 ST_Distance
Synopsis
Description
For geometry types returns the minimum 2D Cartesian (planar) distance between two geometries, in projected units (spatial ref
units).
For geography types defaults to return the minimum geodesic distance between two geographies in meters, compute on the
spheroid determined by the SRID. If use_spheroid is false, a faster spherical calculation is used.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
Geometry Examples
Geometry example - units in planar degrees 4326 is WGS 84 long lat, units are degrees.
SELECT ST_Distance(
'SRID=4326;POINT(-72.1235 42.3521)'::geometry,
'SRID=4326;LINESTRING(-72.1260 42.45, -72.123 42.1546)'::geometry );
-----------------
0.00150567726382282
Geometry example - units in meters (SRID: 3857, proportional to pixels on popular web maps). Although the value is off, nearby
ones can be compared correctly, which makes it a good choice for algorithms like KNN or KMeans.
SELECT ST_Distance(
ST_Transform('SRID=4326;POINT(-72.1235 42.3521)'::geometry, 3857),
ST_Transform('SRID=4326;LINESTRING(-72.1260 42.45, -72.123 42.1546)'::geometry, 3857) ) ←-
;
-----------------
167.441410065196
Geometry example - units in meters (SRID: 3857 as above, but corrected by cos(lat) to account for distortion)
SELECT ST_Distance(
ST_Transform('SRID=4326;POINT(-72.1235 42.3521)'::geometry, 3857),
ST_Transform('SRID=4326;LINESTRING(-72.1260 42.45, -72.123 42.1546)'::geometry, 3857)
) * cosd(42.3521);
-----------------
123.742351254151
Geometry example - units in meters (SRID: 26986 Massachusetts state plane meters) (most accurate for Massachusetts)
SELECT ST_Distance(
ST_Transform('SRID=4326;POINT(-72.1235 42.3521)'::geometry, 26986),
ST_Transform('SRID=4326;LINESTRING(-72.1260 42.45, -72.123 42.1546)'::geometry, 26986) ←-
);
-----------------
123.797937878454
Geometry example - units in meters (SRID: 2163 US National Atlas Equal area) (least accurate)
SELECT ST_Distance(
ST_Transform('SRID=4326;POINT(-72.1235 42.3521)'::geometry, 2163),
ST_Transform('SRID=4326;LINESTRING(-72.1260 42.45, -72.123 42.1546)'::geometry, 2163) ) ←-
;
------------------
126.664256056812
Geography Examples
Same as geometry example but note units in meters - use sphere for slightly faster and less accurate computation.
SELECT ST_Distance(gg1, gg2) As spheroid_dist, ST_Distance(gg1, gg2, false) As sphere_dist
FROM (SELECT
'SRID=4326;POINT(-72.1235 42.3521)'::geography as gg1,
'SRID=4326;LINESTRING(-72.1260 42.45, -72.123 42.1546)'::geography as gg2
) As foo ;
spheroid_dist | sphere_dist
------------------+------------------
123.802076746848 | 123.475736916397
PostGIS 3.3.2 Manual 309 / 902
See Also
8.12.7 ST_3DDistance
ST_3DDistance — Returns the 3D cartesian minimum distance (based on spatial ref) between two geometries in projected units.
Synopsis
Description
Returns the 3-dimensional minimum cartesian distance between two geometries in projected units (spatial ref units).
Examples
-- Geometry example - units in meters (SRID: 2163 US National Atlas Equal area) (3D point ←-
and line compared 2D point and line)
-- Note: currently no vertical datum support so Z is not transformed and assumed to be same ←-
units as final.
SELECT ST_3DDistance(
ST_Transform('SRID=4326;POINT(-72.1235 42.3521 4)'::geometry,2163),
ST_Transform('SRID=4326;LINESTRING(-72.1260 42.45 15, -72.123 42.1546 20)'::geometry ←-
,2163)
) As dist_3d,
ST_Distance(
ST_Transform('SRID=4326;POINT(-72.1235 42.3521)'::geometry,2163),
ST_Transform('SRID=4326;LINESTRING(-72.1260 42.45, -72.123 42.1546)'::geometry,2163)
) As dist_2d;
dist_3d | dist_2d
------------------+-----------------
127.295059324629 | 126.66425605671
dist3d | dist2d
-------------------+--------
0.716635696066337 | 0
See Also
8.12.8 ST_DistanceSphere
ST_DistanceSphere — Returns minimum distance in meters between two lon/lat geometries using a spherical earth model.
Synopsis
Description
Returns minimum distance in meters between two lon/lat points. Uses a spherical earth and radius derived from the spheroid
defined by the SRID. Faster than ST_DistanceSpheroid, but less accurate. PostGIS Versions prior to 1.5 only implemented for
points.
Availability: 1.5 - support for other geometry types besides points was introduced. Prior versions only work with points.
Changed: 2.2.0 In prior versions this used to be called ST_Distance_Sphere
Examples
See Also
ST_Distance, ST_DistanceSpheroid
8.12.9 ST_DistanceSpheroid
ST_DistanceSpheroid — Returns the minimum distance between two lon/lat geometries using a spheroidal earth model.
PostGIS 3.3.2 Manual 311 / 902
Synopsis
Description
Returns minimum distance in meters between two lon/lat geometries given a particular spheroid. See the explanation of spheroids
given for ST_LengthSpheroid.
Note
This function does not look at the SRID of the geometry. It assumes the geometry coordinates are based on the
provided spheroid.
Availability: 1.5 - support for other geometry types besides points was introduced. Prior versions only work with points.
Changed: 2.2.0 In prior versions this was called ST_Distance_Spheroid
Examples
SELECT round(CAST(
ST_DistanceSpheroid(ST_Centroid(geom), ST_GeomFromText('POINT(-118 38)',4326), ' ←-
SPHEROID["WGS 84",6378137,298.257223563]')
As numeric),2) As dist_meters_spheroid,
round(CAST(ST_DistanceSphere(ST_Centroid(geom), ST_GeomFromText('POINT(-118 38)',4326)) ←-
As numeric),2) As dist_meters_sphere,
round(CAST(ST_Distance(ST_Transform(ST_Centroid(geom),32611),
ST_Transform(ST_GeomFromText('POINT(-118 38)', 4326),32611)) As numeric),2) As ←-
dist_utm11_meters
FROM
(SELECT ST_GeomFromText('LINESTRING(-118.584 38.374,-118.583 38.5)', 4326) As geom) as ←-
foo;
dist_meters_spheroid | dist_meters_sphere | dist_utm11_meters
----------------------+--------------------+-------------------
70454.92 | 70424.47 | 70438.00
See Also
ST_Distance, ST_DistanceSphere
8.12.10 ST_FrechetDistance
Synopsis
Description
Implements algorithm for computing the Fréchet distance restricted to discrete points for both geometries, based on Computing
Discrete Fréchet Distance. The Fréchet distance is a measure of similarity between curves that takes into account the location
and ordering of the points along the curves. Therefore it is often better than the Hausdorff distance.
When the optional densifyFrac is specified, this function performs a segment densification before computing the discrete Fréchet
distance. The densifyFrac parameter sets the fraction by which to densify each segment. Each segment will be split into a number
of equal-length subsegments, whose fraction of the total length is closest to the given fraction.
Units are in the units of the spatial reference system of the geometries.
Note
The current implementation supports only vertices as the discrete locations. This could be extended to allow an arbitrary
density of points to be used.
Note
The smaller densifyFrac we specify, the more acurate Fréchet distance we get. But, the computation time and the
memory usage increase with the square of the number of subsegments.
Examples
See Also
ST_HausdorffDistance
8.12.11 ST_HausdorffDistance
Synopsis
Description
Returns the Hausdorff distance between two geometries. The Hausdorff distance is a measure of how similar or dissimilar 2
geometries are.
The function actually computes the "Discrete Hausdorff Distance". This is the Hausdorff distance computed at discrete points on
the geometries. The densifyFrac parameter can be specified, to provide a more accurate answer by densifying segments before
computing the discrete Hausdorff distance. Each segment is split into a number of equal-length subsegments whose fraction of
the segment length is closest to the given fraction.
Units are in the units of the spatial reference system of the geometries.
Note
This algorithm is NOT equivalent to the standard Hausdorff distance. However, it computes an approximation that is
correct for a large subset of useful cases. One important case is Linestrings that are roughly parallel to each other, and
roughly equal in length. This is a useful metric for line matching.
Availability: 1.5.0
Examples
Example: For each building, find the parcel that best represents it. First we require that the parcel intersect with the building
geometry. DISTINCT ON guarantees we get each building listed only once. ORDER BY .. ST_HausdorffDistance
selects the parcel that is most similar to the building.
SELECT DISTINCT ON (buildings.gid) buildings.gid, parcels.parcel_id
FROM buildings
INNER JOIN parcels
ON ST_Intersects(buildings.geom, parcels.geom)
ORDER BY buildings.gid, ST_HausdorffDistance(buildings.geom, parcels.geom);
See Also
ST_FrechetDistance
8.12.12 ST_Length
Synopsis
Description
For geometry types: returns the 2D Cartesian length of the geometry if it is a LineString, MultiLineString, ST_Curve, ST_MultiCurve.
For areal geometries 0 is returned; use ST_Perimeter instead. The units of length is determined by the spatial reference system
of the geometry.
For geography types: computation is performed using the inverse geodesic calculation. Units of length are in meters. If PostGIS
is compiled with PROJ version 4.8.0 or later, the spheroid is specified by the SRID, otherwise it is exclusive to WGS84. If
use_spheroid=false, then the calculation is based on a sphere instead of a spheroid.
Currently for geometry this is an alias for ST_Length2D, but this may change to support higher dimensions.
Warning
Changed: 2.0.0 Breaking change -- in prior versions applying this to a MULTI/POLYGON of type geography would give
you the perimeter of the POLYGON/MULTIPOLYGON. In 2.0.0 this was changed to return 0 to be in line with geometry
behavior. Please use ST_Perimeter if you want the perimeter of a polygon
Note
For geography the calculation defaults to using a spheroidal model. To use the faster but less accurate spherical
calculation use ST_Length(gg,false);
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.5.1
Geometry Examples
Return length in feet for line string. Note this is in feet because EPSG:2249 is Massachusetts State Plane Feet
SELECT ST_Length(ST_GeomFromText('LINESTRING(743238 2967416,743238 2967450,743265 2967450,
743265.625 2967416,743238 2967416)',2249));
st_length
---------
122.630744000095
st_length
---------
34309.4563576191
Geography Examples
length_spheroid | length_sphere
------------------+------------------
34310.5703627288 | 34346.2060960742
See Also
8.12.13 ST_Length2D
Synopsis
Description
Returns the 2D length of the geometry if it is a linestring or multi-linestring. This is an alias for ST_Length
PostGIS 3.3.2 Manual 316 / 902
See Also
ST_Length, ST_3DLength
8.12.14 ST_3DLength
Synopsis
Description
Returns the 3-dimensional or 2-dimensional length of the geometry if it is a LineString or MultiLineString. For 2-d lines it will
just return the 2-d length (same as ST_Length and ST_Length2D)
This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 7.1, 10.3
Changed: 2.0.0 In prior versions this used to be called ST_Length3D
Examples
Return length in feet for a 3D cable. Note this is in feet because EPSG:2249 is Massachusetts State Plane Feet
SELECT ST_3DLength(ST_GeomFromText('LINESTRING(743238 2967416 1,743238 2967450 1,743265 ←-
2967450 3,
743265.625 2967416 3,743238 2967416 3)',2249));
ST_3DLength
-----------
122.704716741457
See Also
ST_Length, ST_Length2D
8.12.15 ST_LengthSpheroid
Synopsis
Description
Calculates the length or perimeter of a geometry on an ellipsoid. This is useful if the coordinates of the geometry are in longi-
tude/latitude and a length is desired without reprojection. The spheroid is specified by a text value as follows:
SPHEROID[<NAME>,<SEMI-MAJOR AXIS>,<INVERSE FLATTENING>]
For example:
SPHEROID["GRS_1980",6378137,298.257222101]
Availability: 1.2.2
Changed: 2.2.0 In prior versions this was called ST_Length_Spheroid and had the alias ST_3DLength_Spheroid
Examples
--3D
SELECT ST_LengthSpheroid( geom, sph_m ) As tot_len,
ST_LengthSpheroid(ST_GeometryN(geom,1), sph_m) As len_line1,
ST_LengthSpheroid(ST_GeometryN(geom,2), sph_m) As len_line2
FROM (SELECT ST_GeomFromEWKT('MULTILINESTRING((-118.584 38.374 20,-118.583 38.5 30) ←-
,
(-71.05957 42.3589 75, -71.061 43 90))') As geom,
CAST('SPHEROID["GRS_1980",6378137,298.257222101]' As spheroid) As sph_m) as foo;
See Also
ST_GeometryN, ST_Length
8.12.16 ST_LongestLine
Synopsis
Description
Returns the 2-dimensional longest line between the points of two geometries. The line returned starts on g1 and ends on g2.
The longest line always occurs between two vertices. The function returns the first longest line if more than one is found. The
length of the line is equal to the distance returned by ST_MaxDistance.
If g1 and g2 are the same geometry, returns the line between the two vertices farthest apart in the geometry. This is a diameter of
the circle computed by ST_MinimumBoundingCircle
Availability: 1.5.0
Examples
Longest line across a single geometry. The length of the line is equal to the Maximum Distance. The line is a diameter of the
Minimum Bounding Circle.
See Also
8.12.17 ST_3DLongestLine
Synopsis
Description
Returns the 3-dimensional longest line between two geometries. The function returns the first longest line if more than one. The
line returned starts in g1 and ends in g2. The 3D length of the line is equal to the distance returned by ST_3DMaxDistance.
Availability: 2.0.0
Changed: 2.2.0 - if 2 2D geometries are input, a 2D point is returned (instead of old behavior assuming 0 for missing Z). In case
of 2D and 3D, Z is no longer assumed to be 0 for missing Z.
Examples
lol3d_line_pt | lol2d_line_pt
-----------------------------------+----------------------------
LINESTRING(50 75 1000,100 100 30) | LINESTRING(98 190,100 100)
lol3d_line_pt | lol2d_line_pt
---------------------------------+--------------------------
LINESTRING(98 190 1,50 74 1000) | LINESTRING(98 190,50 74)
See Also
8.12.18 ST_MaxDistance
ST_MaxDistance — Returns the 2D largest distance between two geometries in projected units.
Synopsis
Description
Returns the 2-dimensional maximum distance between two geometries, in projected units. The maximum distance always occurs
between two vertices. This is the length of the line returned by ST_LongestLine.
If g1 and g2 are the same geometry, returns the distance between the two vertices farthest apart in that geometry.
Availability: 1.5.0
Examples
See Also
8.12.19 ST_3DMaxDistance
ST_3DMaxDistance — Returns the 3D cartesian maximum distance (based on spatial ref) between two geometries in projected
units.
Synopsis
Description
Returns the 3-dimensional maximum cartesian distance between two geometries in projected units (spatial ref units).
Examples
-- Geometry example - units in meters (SRID: 2163 US National Atlas Equal area) (3D point ←-
and line compared 2D point and line)
-- Note: currently no vertical datum support so Z is not transformed and assumed to be same ←-
units as final.
SELECT ST_3DMaxDistance(
ST_Transform(ST_GeomFromEWKT('SRID=4326;POINT(-72.1235 42.3521 10000)'),2163),
ST_Transform(ST_GeomFromEWKT('SRID=4326;LINESTRING(-72.1260 42.45 15, -72.123 42.1546 ←-
20)'),2163)
) As dist_3d,
ST_MaxDistance(
ST_Transform(ST_GeomFromEWKT('SRID=4326;POINT(-72.1235 42.3521 10000)'),2163),
ST_Transform(ST_GeomFromEWKT('SRID=4326;LINESTRING(-72.1260 42.45 15, -72.123 42.1546 ←-
20)'),2163)
) As dist_2d;
dist_3d | dist_2d
------------------+------------------
24383.7467488441 | 22247.8472107251
See Also
8.12.20 ST_MinimumClearance
Synopsis
Description
It is possible for a geometry to meet the criteria for validity according to ST_IsValid (polygons) or ST_IsSimple (lines), but to
become invalid if one of its vertices is moved by a small distance. This can happen due to loss of precision during conversion to
text formats (such as WKT, KML, GML, GeoJSON), or binary formats that do not use double-precision floating point coordinates
(e.g. MapInfo TAB).
The minimum clearance is a quantitative measure of a geometry’s robustness to change in coordinate precision. It is the largest
distance by which vertices of the geometry can be moved without creating an invalid geometry. Larger values of minimum
clearance indicate greater robustness.
If a geometry has a minimum clearance of e, then:
PostGIS 3.3.2 Manual 323 / 902
• No two distinct vertices in the geometry are closer than the distance e.
• No vertex is closer than e to a line segement of which it is not an endpoint.
If no minimum clearance exists for a geometry (e.g. a single point, or a MultiPoint whose points are identical), the return value
is Infinity.
To avoid validity issues caused by precision loss, ST_ReducePrecision can reduce coordinate precision while ensuring that
polygonal geometry remains valid.
Availability: 2.3.0
Examples
See Also
8.12.21 ST_MinimumClearanceLine
Synopsis
Description
Returns the two-point LineString spanning a geometry’s minimum clearance. If the geometry does not have a minimum clear-
ance, LINESTRING EMPTY is returned.
Performed by the GEOS module.
Availability: 2.3.0 - requires GEOS >= 3.6.0
Examples
See Also
ST_MinimumClearance
8.12.22 ST_Perimeter
Synopsis
Description
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.5.1
Examples: Geometry
Return perimeter in feet for Polygon and MultiPolygon. Note this is in feet because EPSG:2249 is Massachusetts State Plane
Feet
SELECT ST_Perimeter(ST_GeomFromText('POLYGON((743238 2967416,743238 2967450,743265 2967450,
743265.625 2967416,743238 2967416))', 2249));
st_perimeter
---------
122.630744000095
(1 row)
Examples: Geography
Return perimeter in meters and feet for Polygon and MultiPolygon. Note this is geography (WGS 84 long lat)
SELECT ST_Perimeter(geog) As per_meters, ST_Perimeter(geog)/0.3048 As per_ft
FROM ST_GeogFromText('POLYGON((-71.1776848522251 42.3902896512902,-71.1776843766326 ←-
42.3903829478009,
PostGIS 3.3.2 Manual 325 / 902
per_meters | per_ft
-----------------+------------------
37.3790462565251 | 122.634666195949
-- MultiPolygon example --
SELECT ST_Perimeter(geog) As per_meters, ST_Perimeter(geog,false) As per_sphere_meters, ←-
ST_Perimeter(geog)/0.3048 As per_ft
FROM ST_GeogFromText('MULTIPOLYGON(((-71.1044543107478 42.340674480411,-71.1044542869917 ←-
42.3406744369506,
-71.1044553562977 42.340673886454,-71.1044543107478 42.340674480411)),
((-71.1044543107478 42.340674480411,-71.1044860600303 42.3407237015564,-71.1045215770124 ←-
42.3407653385914,
-71.1045498002983 42.3407946553165,-71.1045611902745 42.3408058316308,-71.1046016507427 ←-
42.340837442371,
-71.104617893173 42.3408475056957,-71.1048586153981 42.3409875993595,-71.1048736143677 ←-
42.3409959528211,
-71.1048878050242 42.3410084812078,-71.1044020965803 42.3414730072048,
-71.1039672113619 42.3412202916693,-71.1037740497748 42.3410666421308,
-71.1044280218456 42.3406894151355,-71.1044543107478 42.340674480411)))') As geog;
See Also
8.12.23 ST_Perimeter2D
Synopsis
Description
Note
This is currently an alias for ST_Perimeter. In future versions ST_Perimeter may return the highest dimension perimeter
for a geometry. This is still under consideration
See Also
ST_Perimeter
PostGIS 3.3.2 Manual 326 / 902
8.12.24 ST_3DPerimeter
Synopsis
Description
Returns the 3-dimensional perimeter of the geometry, if it is a polygon or multi-polygon. If the geometry is 2-dimensional, then
the 2-dimensional perimeter is returned.
This method implements the SQL/MM specification. SQL-MM ISO/IEC 13249-3: 8.1, 10.5
Changed: 2.0.0 In prior versions this used to be called ST_Perimeter3D
Examples
Perimeter of a slightly elevated polygon in the air in Massachusetts state plane feet
SELECT ST_3DPerimeter(geom), ST_Perimeter2d(geom), ST_Perimeter(geom) FROM
(SELECT ST_GeomFromEWKT('SRID=2249;POLYGON((743238 2967416 2,743238 2967450 1,
743265.625 2967416 1,743238 2967416 2))') As geom) As foo;
See Also
8.12.25 ST_Project
ST_Project — Returns a point projected from a start point by a distance and bearing (azimuth).
Synopsis
Description
Returns a point projected from a start point along a geodesic using a given distance and azimuth (bearing). This is known as the
direct geodesic problem.
The distance is given in meters. Negative values are supported.
The azimuth (also known as heading or bearing) is given in radians. It is measured clockwise from true north (azimuth zero).
East is azimuth π/2 (90 degrees); south is azimuth π (180 degrees); west is azimuth 3π/2 (270 degrees). Negative azimuth values
and values greater than 2π (360 degrees) are supported.
Availability: 2.0.0
Enhanced: 2.4.0 Allow negative distance and non-normalized azimuth.
PostGIS 3.3.2 Manual 327 / 902
See Also
8.12.26 ST_ShortestLine
Synopsis
Description
Returns the 2-dimensional shortest line between two geometries. The line returned starts in geom1 and ends in geom2. If
geom1 and geom2 intersect the result is a line with start and end at an intersection point. The length of the line is the same as
ST_Distance returns for g1 and g2.
Availability: 1.5.0
Examples
See Also
8.12.27 ST_3DShortestLine
Synopsis
Description
Returns the 3-dimensional shortest line between two geometries. The function will only return the first shortest line if more than
one, that the function finds. If g1 and g2 intersects in just one point the function will return a line with both start and end in that
intersection-point. If g1 and g2 are intersecting with more than one point the function will return a line with start and end in the
same point but it can be any of the intersecting points. The line returned will always start in g1 and end in g2. The 3D length of
the line this function returns will always be the same as ST_3DDistance returns for g1 and g2.
Availability: 2.0.0
Changed: 2.2.0 - if 2 2D geometries are input, a 2D point is returned (instead of old behavior assuming 0 for missing Z). In case
of 2D and 3D, Z is no longer assumed to be 0 for missing Z.
Examples
shl3d_line_pt | ←-
shl2d_line_pt
----------------------------------------------------------------------------+---------------------
shl3d_line_pt | ←-
shl2d_line_pt
---------------------------------------------------------------------------+----------------------
See Also
8.13.1 ST_ClipByBox2D
Synopsis
Description
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.0
Examples
-- Rely on implicit cast from geometry to box2d for the second parameter
SELECT ST_ClipByBox2D(geom, ST_MakeEnvelope(0,0,10,10)) FROM mytab;
See Also
8.13.2 ST_Difference
ST_Difference — Computes a geometry representing the part of geometry A that does not intersect geometry B.
Synopsis
Description
Returns a geometry representing the part of geometry A that does not intersect geometry B. This is equivalent to A - ST_Intersecti
If A is completely contained in B then an empty atomic geometry of appropriate type is returned.
Note
This is the only overlay function where input order matters. ST_Difference(A, B) always returns a portion of A.
If the optional gridSize argument is provided, the inputs are snapped to a grid of the given size, and the result vertices are
computed on that same grid. (Requires GEOS-3.9.0 or higher)
Performed by the GEOS module
Enhanced: 3.1.0 accept a gridSize parameter - requires GEOS >= 3.9.0
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.3
This function supports 3d and will not drop the z-index. However, the result is computed using XY only. The result Z values
are copied, averaged or interpolated.
PostGIS 3.3.2 Manual 331 / 902
Examples
PostGIS 3.3.2 Manual 332 / 902
st_astext
---------
LINESTRING(50 150,50 200)
st_asewkt
---------
MULTIPOINT(-118.6 38.329 6,-118.58 38.38 5)
See Also
8.13.3 ST_Intersection
Synopsis
Description
Returns 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.
If the optional gridSize argument is provided, the inputs are snapped to a grid of the given size, and the result vertices are
computed on that same grid. (Requires GEOS-3.9.0 or higher)
ST_Intersection in conjunction with ST_Intersects 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.
Note
Geography: For geography this is really a thin wrapper around the geometry implementation. 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.
Warning
This function will drop the M coordinate values if present.
Warning
If working with 3D geometries, you may want to use SFGCAL based ST_3DIntersection which does a proper 3D
intersection for 3D geometries. Although this function works with Z-coordinate, it does an averaging of Z-Coordinate.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.3
This function supports 3d and will not drop the z-index. However, the result is computed using XY only. The result Z values
are copied, averaged or interpolated.
Examples
PostGIS 3.3.2 Manual 334 / 902
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));
Examples: 2.5Dish
Note this is not a true intersection, compare to the same example using ST_3DIntersection.
select ST_AsText(ST_Intersection(linestring, polygon)) As wkt
from ST_GeomFromText('LINESTRING Z (2 2 6,1.5 1.5 7,1 1 8,0.5 0.5 8,0 0 10)') AS ←-
linestring
CROSS JOIN ST_GeomFromText('POLYGON((0 0 8, 0 1 8, 1 1 8, 1 0 8, 0 0 8))') AS polygon;
st_astext
---------------------------------------
LINESTRING Z (1 1 8,0.5 0.5 8,0 0 10)
See Also
8.13.4 ST_MemUnion
ST_MemUnion — Aggregate function which unions geometries in a memory-efficent but slower way
Synopsis
Description
An 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.
Note
Produces the same result as ST_Union, 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.
This function supports 3d and will not drop the z-index. 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 Also
ST_Union
8.13.5 ST_Node
Synopsis
Description
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 ST_Polygonize.
Examples
Noding two LineStrings which share common linework. Note that the result linework is dissolved.
SELECT ST_AsText(
ST_Node('MULTILINESTRING ((2 5, 2 1, 7 1), (6 1, 4 1, 2 3, 2 5))'::geometry)
) As output;
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_UnaryUnion
8.13.6 ST_Split
Synopsis
Description
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 ST_Union. 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).
Note
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 ST_Snap with a small tolerance.
Examples
-- result --
GEOMETRYCOLLECTION(
POLYGON((150 90,149.039264020162 80.2454838991936,146.193976625564 ←-
70.8658283817455,..),
POLYGON(..))
)
MultiLineString split by a Point, where the point lies exactly on both LineStrings.
PostGIS 3.3.2 Manual 338 / 902
SELECT ST_AsText(ST_Split(
'MULTILINESTRING((10 10, 190 191), (15 15, 30 30, 100 90))',
ST_Point(30,30))) As split;
split
------
GEOMETRYCOLLECTION(
LINESTRING(10 10,30 30),
LINESTRING(30 30,190 190),
LINESTRING(15 15,30 30),
LINESTRING(30 30,100 90)
)
LineString split by a Point, where the point does not lie exactly on the line. Shows using ST_Snap 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_AsText( ST_Split(line, point)) AS no_split,
ST_AsText( ST_Split( ST_Snap(line, point, 1), point)) AS split
FROM data;
no_split | split
---------------------------------------------+-------------------------------------------------------
See Also
ST_Snap, ST_Union
PostGIS 3.3.2 Manual 339 / 902
8.13.7 ST_Subdivide
Synopsis
Description
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. gridSize can be specified to have
clipping work in fixed-precision space (requires GEOS-3.9.0+).
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.
Note
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.
Examples
Example: Subdivide a polygon into parts with no more than 10 vertices, and assign each part a unique id.
rn │ wkt
────┼───────%
1 │ POLYGON((119 23,85 35,68 29,66 28,32 56,22 64,29.8260869565217 100,119 100,119 ←-
23))
2 │ POLYGON((132 10,119 23,119 56,186 56,186 52,178 34,168 18,147 13,132 10))
3 │ POLYGON((119 56,119 100,190 100,185 79,186 56,119 56))
4 │ POLYGON((29.8260869565217 100,32 110,40 119,36 150,57 158,75 171,92 182,114 ←-
184,114 100,29.8260869565217 100))
5 │ POLYGON((114 184,132 186,146 178,176 184,179 162,184 141,190 122,190 100,114 ←-
100,114 184))
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.
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.
WITH complex_areas_to_subdivide AS (
DELETE from polygons_table
WHERE ST_NPoints(geom) > 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
8.13.8 ST_SymDifference
ST_SymDifference — Computes a geometry representing the portions of geometries A and B that do not intersect.
Synopsis
Description
Returns a geometry representing the portions of geonetries 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
If the optional gridSize argument is provided, the inputs are snapped to a grid of the given size, and the result vertices are
computed on that same grid. (Requires GEOS-3.9.0 or higher)
Performed by the GEOS module
Enhanced: 3.1.0 accept a gridSize parameter - requires GEOS >= 3.9.0
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.3
This function supports 3d and will not drop the z-index. However, the result is computed using XY only. The result Z values
are copied, averaged or interpolated.
Examples
PostGIS 3.3.2 Manual 342 / 902
The original linestrings shown together The symmetric difference of the two linestrings
st_astext
---------
MULTILINESTRING((50 150,50 200),(50 50,50 100))
st_astext
------------
MULTILINESTRING((1 3 2.75,1 4 2),(1 1 3,1 2 2.25))
See Also
8.13.9 ST_UnaryUnion
Synopsis
Description
A single-input variant of ST_Union. 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 ST_MakeValid.
Another use of this function is to node and dissolve a collection of linestrings which cross or overlap to make them simple. (To
add nodes but not dissolve duplicate linework use ST_Node.)
It is possible to combine ST_UnaryUnion with ST_Collect 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 ST_MemUnion.
If the optional gridSize argument is provided, the inputs are snapped to a grid of the given size, and the result vertices are
computed on that same grid. (Requires GEOS-3.9.0 or higher)
This function supports 3d and will not drop the z-index. 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
Availability: 2.0.0
See Also
8.13.10 ST_Union
ST_Union — Computes a geometry representing the point-set union of the input geometries.
Synopsis
Description
Unions 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 ST_UnaryUnion 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
A gridSize can be specified to work in fixed-precision space. The inputs are snapped to a grid of the given size, and the result
vertices are computed on that same grid. (Requires GEOS-3.9.0 or higher)
PostGIS 3.3.2 Manual 344 / 902
Note
ST_Collect 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.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.3
Note
Aggregate version is not explicitly defined in OGC SPEC.
This method implements the SQL/MM specification. SQL-MM 3: 5.1.19 the z-index (elevation) when polygons are in-
volved.
This function supports 3d and will not drop the z-index. However, the result is computed using XY only. The result Z values
are copied, averaged or interpolated.
Examples
Aggregate example
SELECT id,
ST_Union(geom) as singlegeom
FROM sometable f
GROUP BY id;
Non-Aggregate example
select ST_AsText(ST_Union('POINT(1 2)' :: geometry, 'POINT(-2 3)' :: geometry))
st_astext
----------
MULTIPOINT(-2 3,1 2)
st_astext
----------
POINT(1 2)
select ST_AsEWKT(ST_Union(geom))
from (
select 'POLYGON((-7 4.2,-7.1 4.2,-7.1 4.3, -7 4.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;
st_asewkt
---------
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)));
st_asewkt
---------
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)))
--wktunion---
MULTILINESTRING((3 4,4 5),(1 2,3 4))
See Also
8.14.1 ST_Buffer
ST_Buffer — Computes a geometry covering all points within a given distance from a geometry.
PostGIS 3.3.2 Manual 346 / 902
Synopsis
Description
Computes a POLYGON or MULTIPOLYGON that represents all points whose distance from a geometry/geography is less than
or equal to a given distance. A negative distance shrinks the geometry rather than expanding it. A negative distance may shrink a
polygon completely, in which case POLYGON EMPTY is returned. For points and lines negative distances always return empty
results.
For geometry, the distance is specified in the units of the Spatial Reference System of the geometry. For geography, the distance
is specified in meters.
The optional third parameter controls the buffer accuracy and style. The accuracy of circular arcs in the buffer is specified as the
number of line segments used to approximate a quarter circle (default is 8). The buffer style can be specifed by providing a list
of blank-separated key=value pairs as follows:
• ’quad_segs=#’ : number of line segments used to approximate a quarter circle (default is 8).
• ’endcap=round|flat|square’ : endcap style (defaults to "round"). ’butt’ is accepted as a synonym for ’flat’.
• ’join=round|mitre|bevel’ : join style (defaults to "round"). ’miter’ is accepted as a synonym for ’mitre’.
• ’mitre_limit=#.#’ : mitre ratio limit (only affects mitered join style). ’miter_limit’ is accepted as a synonym for ’mitre_limit’.
• ’side=both|left|right’ : ’left’ or ’right’ performs a single-sided buffer on the geometry, with the buffered side relative to the
direction of the line. This is only applicable to LINESTRING geometry and does not affect POINT or POLYGON geometries.
By default end caps are square.
Note
For geography, this is a wrapper around the geometry implementation. It determines a planar spatial reference system
that best fits the bounding box of the geography object (trying UTM, Lambert Azimuthal Equal Area (LAEA) North/South
pole, and finally Mercator ). The buffer is computed in the planar space, and then transformed back to WGS84. This
may not produce the desired behavior if the input object is much larger than a UTM zone or crosses the dateline
Note
Buffer output is always a valid polygonal geometry. Buffer can handle invalid inputs, so buffering by distance 0 is
sometimes used as a way of repairing invalid polygons. ST_MakeValid can also be used for this purpose.
Note
Buffering is sometimes used to perform a within-distance search. For this use case it is more efficient to use
ST_DWithin.
Note
This function ignores the Z dimension. It always gives a 2D result even when used on a 3D geometry.
PostGIS 3.3.2 Manual 347 / 902
Enhanced: 2.5.0 - ST_Buffer geometry support was enhanced to allow for side buffering specification side=both|left|right.
Availability: 1.5 - ST_Buffer was enhanced to support different endcaps and join types. These are useful for example to convert
road linestrings into polygon roads with flat or square edges instead of rounded edges. Thin wrapper for geography was added.
Performed by the GEOS module.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.3
This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1.30
Examples
side=left side=right
SELECT ST_Buffer( SELECT ST_Buffer(
ST_GeomFromText( ST_GeomFromText(
'LINESTRING(50 50,150 150,150 50)' 'LINESTRING(50 50,150 150,150 50)'
), 10, 'side=left'); ), 10, 'side=right');
promisingcircle_pcount | lamecircle_pcount
------------------------+-------------------
33 | 9
See Also
8.14.2 ST_BuildArea
Synopsis
Description
Creates an areal geometry formed by the constituent linework of the input geometry. The input can be LINESTRINGS, MUL-
TILINESTRINGS, POLYGONS, MULTIPOLYGONS, and GeometryCollections. The result is a Polygon or MultiPolygon,
depending on input. If the input linework does not form polygons, NULL is returned.
This function assumes all inner geometries represent holes
Note
Input linework must be correctly noded for this function to work properly
Availability: 1.1.0
Examples
PostGIS 3.3.2 Manual 351 / 902
--using linestrings
SELECT ST_BuildArea(ST_Collect(smallc,bigc))
FROM (SELECT
ST_ExteriorRing(ST_Buffer(
ST_GeomFromText('POINT(100 90)'), 25)) As smallc,
ST_ExteriorRing(ST_Buffer(ST_GeomFromText('POINT(100 90)'), 50)) As bigc) As foo;
See Also
8.14.3 ST_Centroid
Synopsis
Description
Computes a point which is the geometric center of mass of a geometry. For [MULTI]POINTs, the centroid is the arithmetic
mean of the input coordinates. For [MULTI]LINESTRINGs, the centroid is computed using the weighted length of each line
segment. For [MULTI]POLYGONs, the centroid is computed in terms of area. If an empty geometry is supplied, an empty
PostGIS 3.3.2 Manual 352 / 902
This method implements the OGC Simple Features Implementation Specification for SQL 1.1.
Examples
In the following illustrations the red dot is the centroid of the source geometry.
SELECT ST_AsText(ST_Centroid('MULTIPOINT ( -1 0, -1 2, -1 3, -1 4, -1 7, 0 1, 0 3, 1 1, 2 ←-
0, 6 0, 7 8, 9 8, 10 6 )'));
st_astext
------------------------------------------
POINT(2.30769230769231 3.30769230769231)
(1 row)
SELECT ST_AsText(ST_centroid(g))
FROM ST_GeomFromText('CIRCULARSTRING(0 2, -1 1,0 0, 0.5 0, 1 0, 2 1, 1 2, 0.5 2, 0 2)') ←-
AS g ;
------------------------------------------
POINT(0.5 1)
SELECT ST_AsText(ST_centroid(g))
FROM ST_GeomFromText('COMPOUNDCURVE(CIRCULARSTRING(0 2, -1 1,0 0),(0 0, 0.5 0, 1 0), ←-
CIRCULARSTRING( 1 0, 2 1, 1 2),(1 2, 0.5 2, 0 2))' ) AS g;
------------------------------------------
POINT(0.5 1)
See Also
ST_PointOnSurface, ST_GeometricMedian
8.14.4 ST_ChaikinSmoothing
Synopsis
Description
Returns a "smoothed" version of the given geometry using the Chaikin algorithm. See Chaikins-Algorithm for an explanation of
the process. For each iteration the number of vertex points will double. The function puts new vertex points at 1/4 of the line
before and after each point and removes the original point. To reduce the number of points use one of the simplification functions
on the result. The new points gets interpolated values for all included dimensions, also z and m.
Second argument, number of iterations is limited to max 5 iterations
Note third argument is only valid for polygons, and will be ignored for linestrings
This function handles 3D and the third dimension will affect the result.
Note
Note that returned geometry will get more points than the original. To reduce the number of points again use one of the
simplification functions on the result. (see ST_Simplify and ST_SimplifyVW)
Availability: 2.5.0
Examples
A triangle is smoothed
select ST_AsText(ST_ChaikinSmoothing(geom)) smoothed
FROM (SELECT 'POLYGON((0 0, 8 8, 0 16, 0 0))'::geometry geom) As foo;
┌───────────%
│ smoothed │
├───────────%
│ POLYGON((2 2,6 6,6 10,2 14,0 12,0 4,2 2)) │
└───────────%
See Also
ST_Simplify, ST_SimplifyVW
8.14.5 ST_ConcaveHull
ST_ConcaveHull — Computes a possibly concave geometry that encloses all input geometry vertices
Synopsis
Description
A concave hull of a geometry is a possibly concave geometry that encloses the vertices of the input geometry. In the general
case the concave hull is a Polygon. The polygon will not contain holes unless the optional param_allow_holes argument is
specified as true. The concave hull of two or more collinear points is a two-point LineString. The concave hull of one or more
identical points is a Point.
One can think of a concave hull as "shrink-wrapping" a set of points. This is different to the convex hull, which is more like
wrapping a rubber band around the points. The concave hull generally has a smaller area and represents a more natural boundary
for the input points. Like the convex hull, the vertices of a concave hull are a subset of the input points, and all other input points
are contained within it.
PostGIS 3.3.2 Manual 355 / 902
The param_pctconvex controls the concaveness of the computed hull. A value of 1 produces the convex hull. A value of
0 produces a hull of maximum concaveness (but still a single polygon). Values between 1 and 0 produce hulls of increasing
concaveness. Choosing a suitable value depends on the nature of the input data, but often values between 0.3 and 0.1 produce
reasonable results.
Technically, the param_pctconvex determines a length as a fraction of the difference between the longest and shortest edges
in the Delaunay Triangulation of the input points. Edges longer than this length are "eroded" from the triangulation. The triangles
remaining form the concave hull.
For point and linear inputs, the hull will enclose all the points of the inputs. For polygonal inputs, the hull will enclose all the
points of the input and also all the areas covered by the input. If you want a point-wise hull of a polygonal input, convert it to
points first, using ST_Points.
This is not an aggregate function. To compute the concave hull of a set of geometries use ST_Collect (e.g. ST_ConcaveHull(
ST_Collect( geom ), 0.80).
Availability: 2.0.0
Enhanced: 3.3.0, GEOS native implementation enabled for GEOS 3.11+
Examples
(37 156), (82 170), (180 72), (29 142), (46 41), (59 155), (124 106), (157 80), ←-
(175 82), (56 50), (62 116), (113 95), (144 167))',
0.1 ) );
---st_astext--
POLYGON ((18 142, 21 151, 27 160, 35 167, 44 172, 54 175, 64 178, 74 180, 84 181, 94 181, ←-
104 181, 114 181, 124 181, 134 179, 144 177, 153 173, 162 168, 171 162, 177 154, 182 ←-
145, 184 135, 173 134, 161 134, 150 133, 139 132, 136 142, 128 149, 119 153, 109 155, 99 ←-
155, 89 155, 79 153, 69 150, 61 144, 63 134, 72 128, 82 125, 92 123, 102 121, 112 119, ←-
122 118, 132 116, 142 113, 151 110, 161 106, 170 102, 178 96, 185 88, 189 78, 190 68, ←-
189 58, 185 49, 179 41, 171 34, 162 29, 153 25, 143 23, 133 21, 123 19, 113 19, 102 19, ←-
92 19, 82 19, 72 21, 62 22, 52 25, 43 29, 33 34, 25 41, 19 49, 14 58, 10 72, 21 73, 31 ←-
74, 42 74, 53 76, 56 66, 63 58, 71 51, 81 48, 91 46, 101 45, 111 46, 121 47, 131 50, 140 ←-
55, 145 64, 144 74, 135 80, 125 83, 115 85, 105 87, 95 89, 85 91, 75 93, 65 95, 55 98, ←-
45 102, 37 107, 29 114, 22 122, 19 132, 18 142))
See Also
8.14.6 ST_ConvexHull
Synopsis
Description
Computes the convex hull of a geometry. The convex hull is the smallest convex geometry that encloses all geometries in the
input.
One can think of the convex hull as the geometry obtained by wrapping an rubber band around a set of geometries. This is
different from a concave hull which is analogous to "shrink-wrapping" the geometries. A convex hull is often used to determine
an affected area based on a set of point observations.
In the general case the convex hull is a Polygon. The convex hull of two or more collinear points is a two-point LineString. The
convex hull of one or more identical points is a Point.
This is not an aggregate function. To compute the convex hull of a set of geometries, use ST_Collect to aggregate them into a
geometry collection (e.g. ST_ConvexHull(ST_Collect(geom)).
Performed by the GEOS module
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.3
This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1.16
Examples
SELECT ST_AsText(ST_ConvexHull(
ST_Collect(
ST_GeomFromText('MULTILINESTRING((100 190,10 8),(150 10, 20 30))'),
ST_GeomFromText('MULTIPOINT(50 5, 150 30, 50 10, 10 10)')
)) );
---st_astext--
POLYGON((50 5,10 8,10 10,100 190,150 30,150 10,50 5))
See Also
8.14.7 ST_DelaunayTriangles
Synopsis
Description
Return the Delaunay triangulation of the vertices of the input geometry. Output is a COLLECTION of polygons (for flags=0) or
a MULTILINESTRING (for flags=1) or TIN (for flags=2). The tolerance, if any, is used to snap input vertices together.
PostGIS 3.3.2 Manual 359 / 902
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
2D Examples
Original polygons
-- our original geometry --
ST_Union(ST_GeomFromText('POLYGON((175 150, 20 40,
50 60, 125 100, 175 150))'),
ST_Buffer(ST_GeomFromText('POINT(110 170)'), 20)
)
PostGIS 3.3.2 Manual 360 / 902
ST_DelaunayTriangles of 2 polygons: delaunay triangle polygons each triangle themed in different color
-- geometries overlaid multilinestring triangles
SELECT
ST_DelaunayTriangles(
ST_Union(ST_GeomFromText('POLYGON((175 150, 20 40,
50 60, 125 100, 175 150))'),
ST_Buffer(ST_GeomFromText('POINT(110 170)'), 20)
))
As dtriag;
PostGIS 3.3.2 Manual 361 / 902
---wkt ---
POLYGON((6 194,6 190,14 194,6 194))
POLYGON((14 194,6 190,14 174,14 194))
POLYGON((14 194,14 174,154 14,14 194))
POLYGON((154 14,14 174,14 154,154 14))
POLYGON((154 14,14 154,150 14,154 14))
POLYGON((154 14,150 14,154 6,154 14))
:
:
Example 1
-- 3D multipoint --
SELECT ST_AsText(ST_DelaunayTriangles(ST_GeomFromText(
'MULTIPOINT Z(14 14 10,
150 14 100,34 6 25, 20 10 150)'))) As wkt;
-----wkt----
GEOMETRYCOLLECTION Z (POLYGON Z ((14 14 10,20 10 150,34 6 25,14 14 10))
,POLYGON Z ((14 14 10,34 6 25,150 14 100,14 14 10)))
PostGIS 3.3.2 Manual 363 / 902
8.14.8 ST_FilterByM
Synopsis
geometry ST_FilterByM(geometry geom, double precision min, double precision max = null, boolean returnM = false);
Description
Filters out vertex points based on their M-value. Returns a geometry with only vertex points that have a M-value larger or equal
to the min value and smaller or equal to the max value. If max-value argument is left out only min value is considered. If fourth
argument is left out the m-value will not be in the resulting geometry. If resulting geometry have too few vertex points left for its
geometry type an empty geometry will be returned. In a geometry collection geometries without enough points will just be left
out silently.
This function is mainly intended to be used in conjunction with ST_SetEffectiveArea. ST_EffectiveArea sets the effective area of
a vertex in its m-value. With ST_FilterByM it then is possible to get a simplified version of the geometry without any calculations,
just by filtering
Note
There is a difference in what ST_SimplifyVW returns when not enough points meet the criteria compared to
ST_FilterByM. ST_SimplifyVW returns the geometry with enough points while ST_FilterByM returns an empty ge-
ometry
Note
Note that the returned geometry might be invalid
Note
This function returns all dimensions, including the Z and M values
Availability: 2.5.0
Examples
A linestring is filtered
SELECT ST_AsText(ST_FilterByM(geom,30)) simplified
FROM (SELECT ST_SetEffectiveArea('LINESTRING(5 2, 3 8, 6 20, 7 25, 10 10)'::geometry) geom ←-
) As foo;
-result
simplified
----------------------------
LINESTRING(5 2,7 25,10 10)
See Also
ST_SetEffectiveArea, ST_SimplifyVW
PostGIS 3.3.2 Manual 364 / 902
8.14.9 ST_GeneratePoints
Synopsis
Description
ST_GeneratePoints generates a given number of pseudo-random points which lie within the input area. The optional seed is
used to regenerate a deterministic sequence of points, and must be greater than zero.
Availability: 2.3.0
Enhanced: 3.0.0, added seed parameter
Examples
Generated 12 Points overlaid on top of original polygon using a random seed value 1996
SELECT ST_GeneratePoints(geom, 12, 1996)
FROM (
SELECT ST_Buffer(
ST_GeomFromText(
'LINESTRING(50 50,150 150,150 50)'),
10, 'endcap=round join=round') AS geom
) AS s;
8.14.10 ST_GeometricMedian
Synopsis
geometry ST_GeometricMedian ( geometry geom, float8 tolerance = NULL, int max_iter = 10000, boolean fail_if_not_converged
= false);
PostGIS 3.3.2 Manual 365 / 902
Description
Computes the approximate geometric median of a MultiPoint geometry using the Weiszfeld algorithm. The geometric median
is the point minimizing the sum of distances to the input points. It provides a centrality measure that is less sensitive to outlier
points than the centroid (center of mass).
The algorithm iterates until the distance change between successive iterations is less than the supplied tolerance parame-
ter. If this condition has not been met after max_iterations iterations, the function produces an error and exits, unless
fail_if_not_converged is set to false (the default).
If a tolerance argument is not provided, the tolerance value is calculated based on the extent of the input geometry.
If present, the input point M values are interpreted as their relative weights.
Availability: 2.3.0
Enhanced: 2.5.0 Added support for M as weight of points.
Examples
WITH test AS (
SELECT 'MULTIPOINT((10 10), (10 40), (40 10), (190 190))'::geometry geom)
SELECT
ST_AsText(ST_Centroid(geom)) centroid,
ST_AsText(ST_GeometricMedian(geom)) median
FROM test;
centroid | median
--------------------+----------------------------------------
POINT(62.5 62.5) | POINT(25.01778421249728 25.01778421249728)
(1 row)
See Also
ST_Centroid
PostGIS 3.3.2 Manual 366 / 902
8.14.11 ST_LineMerge
Synopsis
Description
Returns a LineString or MultiLineString formed by joining together the line elements of a MultiLineString. Lines are joined at
their endpoints at 2-way intersections. Lines are not joined across intersections of 3-way or greater degree.
If directed is TRUE, then ST_LineMerge will not change point order within LineStrings, so lines with opposite directions will
not be merged
Note
Only use with MultiLineString/LineStrings. Other geometry types return an empty GeometryCollection
Warning
This function strips the M dimension.
Examples
SELECT ST_AsText(ST_LineMerge(
'MULTILINESTRING((10 160, 60 120), (120 140, 60 120), (120 140, 180 120))'
));
--------------------------------------------
LINESTRING(10 160,60 120,120 140,180 120)
SELECT ST_AsText(ST_LineMerge(
'MULTILINESTRING((10 160, 60 120), (120 140, 60 120), (120 140, 180 120), (100 180, 120 ←-
140))'
));
--------------------------------------------
MULTILINESTRING((10 160,60 120,120 140),(100 180,120 140),(120 140,180 120))
If merging is not possible due to non-touching lines, the original MultiLineString is returned.
SELECT ST_AsText(ST_LineMerge(
'MULTILINESTRING((-29 -27,-30 -29.7,-36 -31,-45 -33),(-45.2 -33.2,-46 -32))'
));
----------------
MULTILINESTRING((-45.2 -33.2,-46 -32),(-29 -27,-30 -29.7,-36 -31,-45 -33))
PostGIS 3.3.2 Manual 368 / 902
SELECT ST_AsText(ST_LineMerge(
'MULTILINESTRING((60 30, 10 70), (120 50, 60 30), (120 50, 180 30))',
TRUE));
-------------------------------------------------------
MULTILINESTRING((120 50,60 30,10 70),(120 50,180 30))
LINESTRING Z (-30 -29.7 5,-29 -27 11,-30 -29.7 10,-36 -31 5,-45 -33 1,-46 -32 11)
See Also
ST_Segmentize, ST_LineSubstring
8.14.12 ST_MaximumInscribedCircle
Synopsis
Description
Finds the largest circle that is contained within a (multi)polygon, or which does not overlap any lines and points. Returns a record
with fields:
For polygonal inputs, the circle is inscribed within the boundary rings, using the internal rings as boundaries. For linear and point
inputs, the circle is inscribed within the convex hull of the input, using the input lines and points as further boundaries.
Availability: 3.1.0 - requires GEOS >= 3.9.0.
See Also
ST_MinimumBoundingCircle
Examples
Maximum inscribed circle of a polygon. Center, nearest point, and radius are returned.
Maximum inscribed circle of a multi-linestring. Center, nearest point, and radius are returned.
See Also
ST_MinimumBoundingRadius
8.14.13 ST_MinimumBoundingCircle
Synopsis
Description
Note
The bounding circle is approximated by a polygon with a default of 48 segments per quarter circle. Because the polygon
is an approximation of the minimum bounding circle, some points in the input geometry may not be contained within
the polygon. The approximation can be improved by increasing the number of segments. For applications where an
approximation is not suitable ST_MinimumBoundingRadius may be used.
This function is not an aggregate. It can be used with ST_Collect to get the minimum bounding circle of a set of geometries.
The ratio of the area of a polygon divided by the area of its Minimum Bounding Circle is referred to as the Reock compactness
score.
Performed by the GEOS module.
Availability: 1.4.0
See Also
ST_Collect, ST_MinimumBoundingRadius
PostGIS 3.3.2 Manual 371 / 902
Examples
SELECT d.disease_type,
ST_MinimumBoundingCircle(ST_Collect(d.geom)) As geom
FROM disease_obs As d
GROUP BY d.disease_type;
Minimum bounding circle of a point and linestring. Using 8 segs to approximate a quarter circle
SELECT ST_AsText(ST_MinimumBoundingCircle(
ST_Collect(
ST_GeomFromText('LINESTRING(55 75,125 150)'),
ST_Point(20, 80)), 8
)) As wktmbc;
wktmbc
-----------
POLYGON((135.59714732062 115,134.384753327498 102.690357210921,130.79416296937 ←-
90.8537670908995,124.963360620072 79.9451031602111,117.116420743937 ←-
70.3835792560632,107.554896839789 62.5366393799277,96.6462329091006 ←-
56.70583703063,84.8096427890789 53.115246672502,72.5000000000001 ←-
51.9028526793802,60.1903572109213 53.1152466725019,48.3537670908996 ←-
56.7058370306299,37.4451031602112 62.5366393799276,27.8835792560632 ←-
70.383579256063,20.0366393799278 79.9451031602109,14.20583703063 ←-
90.8537670908993,10.615246672502 102.690357210921,9.40285267938019 115,10.6152466725019 ←-
127.309642789079,14.2058370306299 139.1462329091,20.0366393799275 ←-
150.054896839789,27.883579256063 159.616420743937,
37.4451031602108 167.463360620072,48.3537670908992 173.29416296937,60.190357210921 ←-
176.884753327498,
72.4999999999998 178.09714732062,84.8096427890786 176.884753327498,96.6462329091003 ←-
173.29416296937,107.554896839789 167.463360620072,
117.116420743937 159.616420743937,124.963360620072 150.054896839789,130.79416296937 ←-
139.146232909101,134.384753327498 127.309642789079,135.59714732062 115))
See Also
ST_Collect, ST_MinimumBoundingRadius
8.14.14 ST_MinimumBoundingRadius
ST_MinimumBoundingRadius — Returns the center point and radius of the smallest circle that contains a geometry.
PostGIS 3.3.2 Manual 372 / 902
Synopsis
Description
Computes the center point and radius of the smallest circle that contains a geometry. Returns a record with fields:
Use in conjunction with ST_Collect to get the minimum bounding circle of a set of geometries.
Availability - 2.3.0
See Also
ST_Collect, ST_MinimumBoundingCircle
Examples
st_astext | radius
------------------------------------------+------------------
POINT(26284.8418027133 65267.1145090825) | 247.436045591407
8.14.15 ST_OrientedEnvelope
Synopsis
Description
Returns the minimum-area rotated rectangle enclosing a geometry. Note that more than one such rectangle may exist. May return
a Point or LineString in the case of degenerate inputs.
Availability: 2.5.0
See Also
ST_Envelope ST_MinimumBoundingCircle
PostGIS 3.3.2 Manual 373 / 902
Examples
st_astext
------------------------------------------------
POLYGON((3 2,2.88 2.16,-1.12 -0.84,-1 -1,3 2))
SELECT ST_AsText(ST_OrientedEnvelope(
ST_Collect(
ST_GeomFromText('LINESTRING(55 75,125 150)'),
ST_Point(20, 80))
)) As wktenv;
wktenv
-----------
POLYGON((19.9999999999997 79.9999999999999,33.0769230769229 ←-
60.3846153846152,138.076923076924 130.384615384616,125.000000000001 ←-
150.000000000001,19.9999999999997 79.9999999999999))
8.14.16 ST_OffsetCurve
ST_OffsetCurve — Returns an offset line at a given distance and side from an input line.
Synopsis
Description
Return an offset line at a given distance and side from an input line. All points of the returned geometries are not further than the
given distance from the input geometry. Useful for computing parallel lines about a center line.
For positive distance the offset is on the left side of the input line and retains the same direction. For a negative distance it is on
the right side and in the opposite direction.
PostGIS 3.3.2 Manual 374 / 902
• ’join=round|mitre|bevel’ : join style (defaults to "round"). ’miter’ is also accepted as a synonym for ’mitre’.
• ’mitre_limit=#.#’ : mitre ratio limit (only affects mitred join style). ’miter_limit’ is also accepted as a synonym for ’mitre_limit’.
Note
This function ignores the Z dimension. It always gives a 2D result even when used on a 3D geometry.
Examples
See Also
ST_Buffer
8.14.17 ST_PointOnSurface
Synopsis
Description
Returns a POINT which is guaranteed to lie in the interior of a surface (POLYGON, MULTIPOLYGON, and CURVED POLY-
GON). In PostGIS this function also works on line and point geometries.
PostGIS 3.3.2 Manual 378 / 902
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.14.2 // s3.2.18.2
This method implements the SQL/MM specification. SQL-MM 3: 8.1.5, 9.5.6. The specifications define ST_PointOnSurface
for surface geometries only. PostGIS extends the function to support all common geometry types. Other databases (Oracle, DB2,
ArcSDE) seem to support this function only for surfaces. SQL Server 2008 supports all common geometry types.
Examples
Example: The result of ST_PointOnSurface is guaranteed to lie within polygons, whereas the point computed by ST_Centroid
may be outside.
pt_on_surf | centroid
-----------------+---------------------------------------------
POINT(62.5 110) | POINT(100.18264840182648 85.11415525114155)
See Also
ST_Centroid, ST_MaximumInscribedCircle
8.14.18 ST_Polygonize
ST_Polygonize — Computes a collection of polygons formed from the linework of a set of geometries.
Synopsis
Description
Creates a GeometryCollection containing the polygons formed by the constituent linework of a set of geometries. Input linework
must be correctly noded for this function to work properly.
Note
To ensure input is fully noded use ST_Node on the input geometry before polygonizing.
Note
GeometryCollections are often difficult to deal with with third party tools. Use ST_Dump to convert the polygonize result
into separate polygons.
geomtextrep
-------------------------------------
SRID=4269;GEOMETRYCOLLECTION(POLYGON((-71.040878 42.285678,-71.040943 42.2856,-71.04096 ←-
42.285752,-71.040878 42.285678)),
POLYGON((-71.17166 42.353675,-71.172026 42.354044,-71.17239 42.354358,-71.171794 ←-
42.354971,-71.170511 42.354855,
-71.17112 42.354238,-71.17166 42.353675)))
(1 row)
--Use ST_Dump to dump out the polygonize geoms into individual polygons
SELECT ST_AsEWKT((ST_Dump(foofoo.polycoll)).geom) As geomtextrep
FROM (SELECT ST_Polygonize(geom_4269) As polycoll
FROM (SELECT geom_4269 FROM ma.suffolk_edges
ORDER BY tlid LIMIT 45) As foo) As foofoo;
geomtextrep
------------------------
SRID=4269;POLYGON((-71.040878 42.285678,-71.040943 42.2856,-71.04096 42.285752,
-71.040878 42.285678))
SRID=4269;POLYGON((-71.17166 42.353675,-71.172026 42.354044,-71.17239 42.354358
,-71.171794 42.354971,-71.170511 42.354855,-71.17112 42.354238,-71.17166 42.353675))
(2 rows)
See Also
ST_Node, ST_Dump
8.14.19 ST_ReducePrecision
Synopsis
Description
Returns a valid geometry with all points rounded to the provided grid tolerance, and features below the tolerance removed.
Unlike ST_SnapToGrid the returned geometry will be valid, with no ring self-intersections or collapsed components.
Precision reduction can be used to:
Examples
See Also
8.14.20 ST_SharedPaths
ST_SharedPaths — Returns a collection containing paths shared by the two input linestrings/multilinestrings.
Synopsis
Description
Returns a collection containing paths shared by the two input geometries. Those going in the same direction are in the first
element of the collection, those going in the opposite direction are in the second element. The paths themselves are given in the
direction of the first geometry.
Performed by the GEOS module.
Availability: 2.0.0
The shared path of multilinestring and linestring overlaid with original geometries.
SELECT ST_AsText(
ST_SharedPaths(
ST_GeomFromText('MULTILINESTRING((26 125,26 200,126 200,126 125,26 125),
(51 150,101 150,76 175,51 150))'),
ST_GeomFromText('LINESTRING(151 100,126 156.25,126 125,90 161, 76 175)')
)
) As wkt
wkt
-------------------------------------------------------------
GEOMETRYCOLLECTION(MULTILINESTRING((126 156.25,126 125),
(101 150,90 161),(90 161,76 175)),MULTILINESTRING EMPTY)
wkt
-------------------------------------------------------------
GEOMETRYCOLLECTION(MULTILINESTRING EMPTY,
MULTILINESTRING((76 175,90 161),(90 161,101 150),(126 125,126 156.25)))
See Also
8.14.21 ST_Simplify
Synopsis
Description
Returns a "simplified" version of the given geometry using the Douglas-Peucker algorithm. Will actually do something only
with (multi)lines and (multi)polygons but you can safely call it with any kind of geometry. Since simplification occurs on a
object-by-object basis you can also feed a GeometryCollection to this function.
The "preserve collapsed" flag will retain objects that would otherwise be too small given the tolerance. For example, a 1m long
line simplified with a 10m tolerance. If preserveCollapsed argument is specified as true, the line will not disappear. This
flag is useful for rendering engines, to avoid having large numbers of very small objects disappear from a map leaving surprising
gaps.
Note
Note that returned geometry might lose its simplicity (see ST_IsSimple)
Note
Note topology may not be preserved and may result in invalid geometries. Use (see ST_SimplifyPreserveTopology) to
preserve topology.
Availability: 1.2.2
Examples
49 | 33 | 17 | 9 | 4 | t
See Also
8.14.22 ST_SimplifyPreserveTopology
ST_SimplifyPreserveTopology — Returns a simplified and valid version of a geometry, using the Douglas-Peucker algorithm.
PostGIS 3.3.2 Manual 385 / 902
Synopsis
Description
Returns a "simplified" version of the given geometry using the Douglas-Peucker algorithm. Will avoid creating derived ge-
ometries (polygons in particular) that are invalid. Will actually do something only with (multi)lines and (multi)polygons but
you can safely call it with any kind of geometry. Since simplification occurs on a object-by-object basis you can also feed a
GeometryCollection to this function.
Performed by the GEOS module.
Availability: 1.3.3
Examples
Same example as Simplify, but we see Preserve Topology prevents oversimplification. The circle can at most become a square.
SELECT ST_Npoints(geom) As np_before, ST_NPoints(ST_SimplifyPreserveTopology(geom,0.1)) As ←-
np01_notbadcircle, ST_NPoints(ST_SimplifyPreserveTopology(geom,0.5)) As ←-
np05_notquitecircle,
ST_NPoints(ST_SimplifyPreserveTopology(geom,1)) As np1_octagon, ST_NPoints( ←-
ST_SimplifyPreserveTopology(geom,10)) As np10_square,
ST_NPoints(ST_SimplifyPreserveTopology(geom,100)) As np100_stillsquare
FROM (SELECT ST_Buffer('POINT(1 3)', 10,12) As geom) As foo;
--result--
np_before | np01_notbadcircle | np05_notquitecircle | np1_octagon | np10_square | ←-
np100_stillsquare
-----------+-------------------+---------------------+-------------+---------------+-----------------
49 | 33 | 17 | 9 | 5 | ←-
5
See Also
ST_Simplify
8.14.23 ST_SimplifyPolygonHull
Synopsis
Description
Computes a simplified topology-preserving outer or inner hull of a polygonal geometry. An outer hull completely covers the
input geometry. An inner hull is completely covered by the input geometry. The result is a polygonal geometry formed by a
subset of the input vertices. MultiPolygons and holes are handled and produce a result with the same structure as the input.
The reduction in vertex count is controlled by the vertex_fraction parameter, which is a number in the range 0 to 1. Lower
values produce simpler results, with smaller vertex count and less concaveness. For both outer and inner hulls a vertex fraction
PostGIS 3.3.2 Manual 386 / 902
of 1.0 produces the orginal geometry. For outer hulls a value of 0.0 produces the convex hull (for a single polygon); for inner
hulls it produces a triangle.
The simplification process operates by progressively removing concave corners that contain the least amount of area, until the
vertex count target is reached. It prevents edges from crossing, so the result is always a valid polygonal geometry.
To get better results with geometries that contain relatively long line segments, it might be necessary to "segmentize" the input,
as shown below.
Performed by the GEOS module.
Availability: 3.3.0 - requires GEOS >= 3.11.0
Examples
SELECT ST_SimplifyPolygonHull(
'POLYGON ((131 158, 136 163, 161 165, 173 156, 179 148, 169 140, 186 144, 190 137, 185 ←-
131, 174 128, 174 124, 166 119, 158 121, 158 115, 165 107, 161 97, 166 88, 166 79, 158 ←-
57, 145 57, 112 53, 111 47, 93 43, 90 48, 88 40, 80 39, 68 32, 51 33, 40 31, 39 34, ←-
49 38, 34 38, 25 34, 28 39, 36 40, 44 46, 24 41, 17 41, 14 46, 19 50, 33 54, 21 55, 13 ←-
52, 11 57, 22 60, 34 59, 41 68, 75 72, 62 77, 56 70, 46 72, 31 69, 46 76, 52 82, 47 ←-
84, 56 90, 66 90, 64 94, 56 91, 33 97, 36 100, 23 100, 22 107, 29 106, 31 112, 46 116, ←-
36 118, 28 131, 53 132, 59 127, 62 131, 76 130, 80 135, 89 137, 87 143, 73 145, 80 ←-
150, 88 150, 85 157, 99 162, 116 158, 115 165, 123 165, 122 170, 134 164, 131 158))',
0.3);
PostGIS 3.3.2 Manual 387 / 902
See Also
8.14.24 ST_SimplifyVW
Synopsis
Description
Returns a "simplified" version of the given geometry using the Visvalingam-Whyatt algorithm. Will actually do something only
with (multi)lines and (multi)polygons but you can safely call it with any kind of geometry. Since simplification occurs on a
object-by-object basis you can also feed a GeometryCollection to this function.
Note
Note that returned geometry might lose its simplicity (see ST_IsSimple)
Note
Note topology may not be preserved and may result in invalid geometries. Use (see ST_SimplifyPreserveTopology) to
preserve topology.
Note
This function handles 3D and the third dimension will affect the result.
Availability: 2.2.0
Examples
See Also
8.14.25 ST_SetEffectiveArea
ST_SetEffectiveArea — Sets the effective area for each vertex, using the Visvalingam-Whyatt algorithm.
PostGIS 3.3.2 Manual 389 / 902
Synopsis
Description
Sets the effective area for each vertex, using the Visvalingam-Whyatt algorithm. The effective area is stored as the M-value of
the vertex. If the optional "theshold" parameter is used, a simplified geometry will be returned, containing only vertices with an
effective area greater than or equal to the threshold value.
This function can be used for server-side simplification when a threshold is specified. Another option is to use a threshold value
of zero. In this case, the full geometry will be returned with effective areas as M-values, which can be used by the client to
simplify very quickly.
Will actually do something only with (multi)lines and (multi)polygons but you can safely call it with any kind of geometry. Since
simplification occurs on a object-by-object basis you can also feed a GeometryCollection to this function.
Note
Note that returned geometry might lose its simplicity (see ST_IsSimple)
Note
Note topology may not be preserved and may result in invalid geometries. Use (see ST_SimplifyPreserveTopology) to
preserve topology.
Note
The output geometry will lose all previous information in the M-values
Note
This function handles 3D and the third dimension will affect the effective area
Availability: 2.2.0
Examples
Calculating the effective area of a LineString. Because we use a threshold value of zero, all vertices in the input geometry are
returned.
See Also
ST_SimplifyVW
8.14.26 ST_TriangulatePolygon
Synopsis
Description
Computes the constrained Delaunay triangulation of polygons. Holes and Multipolygons are supported.
The "constrained Delaunay triangulation" of a polygon is a set of triangles formed from the vertices of the polygon, and covering
it exactly, with the maximum total interior angle over all possible triangulations. It provides the "best quality" triangulation of
the polygon.
Availability: 3.3.0
Example
Triangulation of a square.
SELECT ST_AsText(
ST_TriangulatePolygon('POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))'));
st_astext
---------------------------------------------------------------------------
GEOMETRYCOLLECTION(POLYGON((0 0,0 1,1 1,0 0)),POLYGON((1 1,1 0,0 0,1 1)))
Example
Polygon Triangulation
See Also
8.14.27 ST_VoronoiLines
ST_VoronoiLines — Returns the boundaries of the Voronoi diagram of the vertices of a geometry.
Synopsis
Description
ST_VoronoiLines computes a two-dimensional Voronoi diagram from the vertices of the supplied geometry and returns the
boundaries between cells in that diagram as a MultiLineString. Returns null if input geometry is null. Returns an empty geometry
collection if the input geometry contains only one vertex. Returns an empty geometry collection if the extend_to envelope has
zero area.
Optional parameters:
• ’tolerance’ : The distance within which vertices will be considered equivalent. Robustness of the algorithm can be improved
by supplying a nonzero tolerance distance. (default = 0.0)
• ’extend_to’ : If a geometry is supplied as the "extend_to" parameter, the diagram will be extended to cover the envelope
of the "extend_to" geometry, unless that envelope is smaller than the default envelope (default = NULL, default envelope is
boundingbox of input geometry extended by about 50% in each direction).
Examples
PostGIS 3.3.2 Manual 392 / 902
-- ST_AsText output
MULTILINESTRING((135.555555555556 270,36.8181818181818 92.2727272727273) ←-
,(36.8181818181818 92.2727272727273,-110 43.3333333333333),(230 ←-
-45.7142857142858,36.8181818181818 92.2727272727273))
See Also
8.14.28 ST_VoronoiPolygons
ST_VoronoiPolygons — Returns the cells of the Voronoi diagram of the vertices of a geometry.
Synopsis
Description
ST_VoronoiPolygons computes a two-dimensional Voronoi diagram from the vertices of the supplied geometry. The result is
a GeometryCollection of Polygons that covers an envelope larger than the extent of the input vertices. Returns null if input
geometry is null. Returns an empty geometry collection if the input geometry contains only one vertex. Returns an empty
geometry collection if the extend_to envelope has zero area.
Optional parameters:
• ’tolerance’ : The distance within which vertices will be considered equivalent. Robustness of the algorithm can be improved
by supplying a nonzero tolerance distance. (default = 0.0)
PostGIS 3.3.2 Manual 393 / 902
• ’extend_to’ : If a geometry is supplied as the "extend_to" parameter, the diagram will be extended to cover the envelope
of the "extend_to" geometry, unless that envelope is smaller than the default envelope (default = NULL, default envelope is
boundingbox of input geometry extended by about 50% in each direction).
Examples
-- ST_AsText output
GEOMETRYCOLLECTION(POLYGON((-110 43.3333333333333,-110 270,100.5 270,59.3478260869565 ←-
132.826086956522,36.8181818181818 92.2727272727273,-110 43.3333333333333)),
POLYGON((55 -90,-110 -90,-110 43.3333333333333,36.8181818181818 92.2727272727273,55 ←-
79.2857142857143,55 -90)),
POLYGON((230 47.5,230 -20.7142857142857,55 79.2857142857143,36.8181818181818 ←-
92.2727272727273,59.3478260869565 132.826086956522,230 47.5)),POLYGON((230 ←-
-20.7142857142857,230 -90,55 -90,55 79.2857142857143,230 -20.7142857142857)),
POLYGON((100.5 270,230 270,230 47.5,59.3478260869565 132.826086956522,100.5 270)))
PostGIS 3.3.2 Manual 394 / 902
-- ST_AsText output
GEOMETRYCOLLECTION(POLYGON((-110 43.3333333333333,-110 270,100.5 270,59.3478260869565 ←-
132.826086956522,36.8181818181818 92.2727272727273,-110 43.3333333333333)),
POLYGON((230 47.5,230 -45.7142857142858,36.8181818181818 ←-
92.2727272727273,59.3478260869565 132.826086956522,230 47.5)),POLYGON((230 ←-
-45.7142857142858,230 -90,-110 -90,-110 43.3333333333333,36.8181818181818 ←-
92.2727272727273,230 -45.7142857142858)),
POLYGON((100.5 270,230 270,230 47.5,59.3478260869565 132.826086956522,100.5 270)))
PostGIS 3.3.2 Manual 395 / 902
-- ST_AsText output
MULTILINESTRING((135.555555555556 270,36.8181818181818 92.2727272727273) ←-
,(36.8181818181818 92.2727272727273,-110 43.3333333333333),(230 ←-
-45.7142857142858,36.8181818181818 92.2727272727273))
See Also
8.15.1 ST_Affine
Synopsis
geometry ST_Affine(geometry geomA, float a, float b, float c, float d, float e, float f, float g, float h, float i, float xoff, float yoff,
float zoff);
geometry ST_Affine(geometry geomA, float a, float b, float d, float e, float xoff, float yoff);
Description
Applies a 3D affine transformation to the geometry to do things like translate, rotate, scale in one step.
Version 1: The call
ST_Affine(geom, a, b, c, d, e, f, g, h, i, xoff, yoff, zoff)
/ a b c xoff \
| d e f yoff |
| g h i zoff |
\ 0 0 0 1 /
All of the translate / scale functions below are expressed via such an affine transformation.
Version 2: Applies a 2d affine transformation to the geometry. The call
ST_Affine(geom, a, b, d, e, xoff, yoff)
Note
Prior to 1.3.4, this function crashes if used with geometries that contain CURVES. This is fixed in 1.3.4+
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
--Rotate a 3d line 180 degrees about the z axis. Note this is long-hand for doing ←-
ST_Rotate();
SELECT ST_AsEWKT(ST_Affine(geom, cos(pi()), -sin(pi()), 0, sin(pi()), cos(pi()), 0, 0, ←-
0, 1, 0, 0, 0)) As using_affine,
ST_AsEWKT(ST_Rotate(geom, pi())) As using_rotate
FROM (SELECT ST_GeomFromEWKT('LINESTRING(1 2 3, 1 4 3)') As geom) As foo;
using_affine | using_rotate
PostGIS 3.3.2 Manual 397 / 902
-----------------------------+-----------------------------
LINESTRING(-1 -2 3,-1 -4 3) | LINESTRING(-1 -2 3,-1 -4 3)
(1 row)
See Also
8.15.2 ST_Rotate
Synopsis
Description
Rotates geometry rotRadians counter-clockwise about the origin point. The rotation origin can be specified either as a POINT
geometry, or as x and y coordinates. If the origin is not specified, the geometry is rotated about POINT(0 0).
Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
Enhanced: 2.0.0 additional parameters for specifying the origin of rotation were added.
Availability: 1.1.2. Name changed from Rotate to ST_Rotate in 1.2.2
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
See Also
8.15.3 ST_RotateX
Synopsis
Description
Note
ST_RotateX(geomA, rotRadians) is short-hand for ST_Affine(geomA, 1, 0, 0, 0,
cos(rotRadians), -sin(rotRadians), 0, sin(rotRadians), cos(rotRadians), 0,
0, 0).
Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
Availability: 1.1.2. Name changed from RotateX to ST_RotateX in 1.2.2
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
See Also
8.15.4 ST_RotateY
Synopsis
Description
Note
ST_RotateY(geomA, rotRadians) is short-hand for ST_Affine(geomA, cos(rotRadians), 0,
sin(rotRadians), 0, 1, 0, -sin(rotRadians), 0, cos(rotRadians), 0, 0, 0).
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
See Also
8.15.5 ST_RotateZ
Synopsis
Description
Note
This is a synonym for ST_Rotate
Note
ST_RotateZ(geomA, rotRadians) is short-hand for SELECT ST_Affine(geomA,
cos(rotRadians), -sin(rotRadians), 0, sin(rotRadians), cos(rotRadians), 0,
0, 0, 1, 0, 0, 0).
Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
Availability: 1.1.2. Name changed from RotateZ to ST_RotateZ in 1.2.2
Note
Prior to 1.3.4, this function crashes if used with geometries that contain CURVES. This is fixed in 1.3.4+
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
st_asewkt
-----------------------------------------------------------------------------------------------------
See Also
8.15.6 ST_Scale
Synopsis
Description
Scales the geometry to a new size by multiplying the ordinates with the corresponding factor parameters.
The version taking a geometry as the factor parameter allows passing a 2d, 3dm, 3dz or 4d point to set scaling factor for all
supported dimensions. Missing dimensions in the factor point are equivalent to no scaling the corresponding dimension.
The three-geometry variant allows a "false origin" for the scaling to be passed in. This allows "scaling in place", for example
using the centroid of the geometry as the false origin. Without a false origin, scaling takes place relative to the actual origin, so
all coordinates are just multipled by the scale factor.
Note
Prior to 1.3.4, this function crashes if used with geometries that contain CURVES. This is fixed in 1.3.4+
Availability: 1.1.0.
Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
Enhanced: 2.2.0 support for scaling all dimension (factor parameter) was introduced.
Enhanced: 2.5.0 support for scaling relative to a local origin (origin parameter) was introduced.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
--Version 1: scale X, Y, Z
SELECT ST_AsEWKT(ST_Scale(ST_GeomFromEWKT('LINESTRING(1 2 3, 1 1 1)'), 0.5, 0.75, 0.8));
st_asewkt
--------------------------------------
LINESTRING(0.5 1.5 2.4,0.5 0.75 0.8)
--Version 2: Scale X Y
SELECT ST_AsEWKT(ST_Scale(ST_GeomFromEWKT('LINESTRING(1 2 3, 1 1 1)'), 0.5, 0.75));
st_asewkt
----------------------------------
PostGIS 3.3.2 Manual 402 / 902
--Version 3: Scale X Y Z M
SELECT ST_AsEWKT(ST_Scale(ST_GeomFromEWKT('LINESTRING(1 2 3 4, 1 1 1 1)'),
ST_MakePoint(0.5, 0.75, 2, -1)));
st_asewkt
----------------------------------------
LINESTRING(0.5 1.5 6 -4,0.5 0.75 2 -1)
See Also
ST_Affine, ST_TransScale
8.15.7 ST_Translate
Synopsis
Description
Returns a new geometry whose coordinates are translated delta x,delta y,delta z units. Units are based on the units defined in
spatial reference (SRID) for this geometry.
Note
Prior to 1.3.4, this function crashes if used with geometries that contain CURVES. This is fixed in 1.3.4+
Availability: 1.2.2
Examples
wgs_transgeomtxt
---------------------
POINT(-70.01 42.37)
PostGIS 3.3.2 Manual 403 / 902
Move a 3d point
SELECT ST_AsEWKT(ST_Translate(CAST('POINT(0 0 0)' As geometry), 5, 12,3));
st_asewkt
---------
POINT(5 12 3)
See Also
8.15.8 ST_TransScale
Synopsis
geometry ST_TransScale(geometry geomA, float deltaX, float deltaY, float XFactor, float YFactor);
Description
Translates the geometry using the deltaX and deltaY args, then scales it using the XFactor, YFactor args, working in 2D only.
Note
ST_TransScale(geomA, deltaX, deltaY, XFactor, YFactor) is short-hand for
ST_Affine(geomA, XFactor, 0, 0, 0, YFactor, 0, 0, 0, 1, deltaX*XFactor,
deltaY*YFactor, 0).
Note
Prior to 1.3.4, this function crashes if used with geometries that contain CURVES. This is fixed in 1.3.4+
Availability: 1.1.0.
Examples
--Buffer a point to get an approximation of a circle, convert to curve and then translate ←-
1,2 and scale it 3,4
SELECT ST_AsText(ST_Transscale(ST_LineToCurve(ST_Buffer('POINT(234 567)', 3)),1,2,3,4));
st_astext
-----------------------------------------------------------------------------------------------------
See Also
ST_Affine, ST_Translate
8.16.1 ST_ClusterDBSCAN
ST_ClusterDBSCAN — Window function that returns a cluster id for each input geometry using the DBSCAN algorithm.
Synopsis
Description
Returns cluster number for each input geometry, based on a 2D implementation of the Density-based spatial clustering of appli-
cations with noise (DBSCAN) algorithm. Unlike ST_ClusterKMeans, it does not require the number of clusters to be specified,
but instead uses the desired distance (eps) and density (minpoints) parameters to construct each cluster.
An input geometry will be added to a cluster if it is either:
• A "core" geometry, that is within eps distance of at least minpoints input geometries (including itself) or
• A "border" geometry, that is within eps distance of a core geometry.
Note that border geometries may be within eps distance of core geometries in more than one cluster; in this case, either
assignment would be correct, and the border geometry will be arbitrarily asssigned to one of the available clusters. In these
cases, it is possible for a correct cluster to be generated with fewer than minpoints geometries. When assignment of a border
geometry is ambiguous, repeated calls to ST_ClusterDBSCAN will produce identical results if an ORDER BY clause is included
in the window definition, but cluster assignments may differ from other implementations of the same algorithm.
Note
Input geometries that do not meet the criteria to join any other cluster will be assigned a cluster number of NULL.
Availability: 2.3.0
PostGIS 3.3.2 Manual 405 / 902
Examples
Assigning a cluster number to each polygon within 50 meters of each other. Require at least 2 polygons per cluster
name | ←-
bucket
-------------------------------------+-------- ←-
Manulife Tower | ←-
0
Park Lane Seaport I | ←-
0
Park Lane Seaport II | ←-
0
Renaissance Boston Waterfront Hotel | ←-
0
Seaport Boston Hotel | ←-
0
Seaport Hotel & World Trade Center | ←-
0
Waterside Place | ←-
0
World Trade Center East | ←-
0
100 Northern Avenue | ←-
1
100 Pier 4 | ←-
1
The Institute of Contemporary Art | ←-
1
within 50 meters at least 2 per cluster. singletons have 101 Seaport | ←-
2
NULL for cid
District Hall | ←-
SELECT name, ST_ClusterDBSCAN(geom, eps ←- 2
:= 50, minpoints := 2) over () AS cid One Marina Park Drive | ←-
FROM boston_polys 2
WHERE name > '' AND building > '' Twenty Two Liberty | ←-
AND ST_DWithin(geom, 2
ST_Transform( Vertex | ←-
ST_GeomFromText('POINT ←- 2
(-71.04054 42.35141)', 4326), 26986), Vertex | ←-
500); 2
Watermark Seaport | ←-
2
Blue Hills Bank Pavilion | ←-
NULL
World Trade Center West | ←-
NULL
(20 rows)
Combining parcels with the same cluster number into a single geometry. This uses named argument calling
SELECT cid, ST_Collect(geom) AS cluster_geom, array_agg(parcel_id) AS ids_in_cluster FROM (
SELECT parcel_id, ST_ClusterDBSCAN(geom, eps := 0.5, minpoints := 5) over () AS cid, ←-
geom
FROM parcels) sq
GROUP BY cid;
PostGIS 3.3.2 Manual 406 / 902
See Also
8.16.2 ST_ClusterIntersecting
ST_ClusterIntersecting — Aggregate function that clusters the input geometries into connected sets.
Synopsis
Description
ST_ClusterIntersecting is an aggregate function that returns an array of GeometryCollections, where each GeometryCollection
represents an interconnected set of geometries.
Availability: 2.2.0
Examples
WITH testdata AS
(SELECT unnest(ARRAY['LINESTRING (0 0, 1 1)'::geometry,
'LINESTRING (5 5, 4 4)'::geometry,
'LINESTRING (6 6, 7 7)'::geometry,
'LINESTRING (0 0, -1 -1)'::geometry,
'POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0))'::geometry]) AS geom)
--result
st_astext
---------
GEOMETRYCOLLECTION(LINESTRING(0 0,1 1),LINESTRING(5 5,4 4),LINESTRING(0 0,-1 -1),POLYGON((0 ←-
0,4 0,4 4,0 4,0 0)))
GEOMETRYCOLLECTION(LINESTRING(6 6,7 7))
See Also
8.16.3 ST_ClusterKMeans
ST_ClusterKMeans — Window function that returns a cluster id for each input geometry using the K-means algorithm.
Synopsis
Description
Returns K-means cluster number for each input geometry. The distance used for clustering is the distance between the centroids
for 2D geometries, and distance between bounding box centers for 3D geometries. For POINT inputs, M coordinate will be
treated as weight of input and has to be larger than 0.
max_radius, if set, will cause ST_ClusterKMeans to generate more clusters than k ensuring that no cluster in output has
radius larger than max_radius. This is useful in reachability analysis.
Enhanced: 3.2.0 Support for max_radius
Enhanced: 3.1.0 Support for 3D geometries and weights
Availability: 2.3.0
Examples
Example: Clustering a preaggregated planetary-scale data population dataset using 3D clusering and weighting. Identify at least
20 regions based on Kontur Population Data that do not span more than 3000 km from their center:
create table kontur_population_3000km_clusters as
select
geom,
ST_ClusterKMeans(
ST_Force4D(
ST_Transform(ST_Force3D(geom), 4978), -- cluster in 3D XYZ CRS
mvalue := population -- set clustering to be weighed by population
),
20, -- aim to generate at least 20 clusters
max_radius := 3000000 -- but generate more to make each under 3000 km radius
) over () as cid
from
kontur_population;
World population clustered to above specs produces 46 clusters. Clusters are centered at well-populated regions (New York,
Moscow). Greenland is one cluster. There are island clusters that span across the antimeridian. Cluster edges follow Earth’s
curvature.
See Also
8.16.4 ST_ClusterWithin
ST_ClusterWithin — Aggregate function that clusters the input geometries by separation distance.
Synopsis
Description
ST_ClusterWithin is an aggregate function that returns an array of GeometryCollections, where each GeometryCollection repre-
sents a set of geometries separated by no more than the specified distance. (Distances are Cartesian distances in the units of the
SRID.)
Availability: 2.2.0
Examples
WITH testdata AS
(SELECT unnest(ARRAY['LINESTRING (0 0, 1 1)'::geometry,
'LINESTRING (5 5, 4 4)'::geometry,
'LINESTRING (6 6, 7 7)'::geometry,
'LINESTRING (0 0, -1 -1)'::geometry,
'POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0))'::geometry]) AS geom)
--result
st_astext
---------
GEOMETRYCOLLECTION(LINESTRING(0 0,1 1),LINESTRING(5 5,4 4),LINESTRING(0 0,-1 -1),POLYGON((0 ←-
0,4 0,4 4,0 4,0 0)))
GEOMETRYCOLLECTION(LINESTRING(6 6,7 7))
See Also
8.17.1 Box2D
Synopsis
Description
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
PostGIS 3.3.2 Manual 410 / 902
Examples
box2d
---------
BOX(1 2,5 6)
box2d
--------
BOX(220186.984375 150406,220288.25 150506.140625)
See Also
Box3D, ST_GeomFromText
8.17.2 Box3D
Synopsis
Description
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
Box3d
---------
BOX3D(1 2 3,5 6 5)
Box3d
--------
BOX3D(220227 150406 1,220268 150415 1)
PostGIS 3.3.2 Manual 411 / 902
See Also
Box2D, ST_GeomFromEWKT
8.17.3 ST_EstimatedExtent
Synopsis
Description
Returns the estimated extent of a spatial table as a box2d. The current schema is used if not specified. The estimated extent
is taken from the geometry column’s statistics. This is usually much faster than computing the exact extent of the table using
ST_Extent or ST_3DExtent.
The default behavior is to also use statistics collected from child tables (tables with INHERITS) if available. If parent_only
is set to TRUE, only statistics for the given table are used and child tables are ignored.
For PostgreSQL >= 8.0.0 statistics are gathered by VACUUM ANALYZE and the result extent will be about 95% of the actual
one. For PostgreSQL < 8.0.0 statistics are gathered by running update_geometry_stats() and the result extent is exact.
Note
In the absence of statistics (empty table or no ANALYZE called) this function returns NULL. Prior to version 1.5.4 an
exception was thrown instead.
Availability: 1.0.0
Changed: 2.1.0. Up to 2.0.x this was called ST_Estimated_Extent.
Examples
See Also
ST_Extent, ST_3DExtent
8.17.4 ST_Expand
ST_Expand — Returns a bounding box expanded from another bounding box or a geometry.
PostGIS 3.3.2 Manual 412 / 902
Synopsis
Description
Returns a bounding box expanded from the bounding box of the input, either by specifying a single distance with which the box
should be expanded on both axes, or by specifying an expansion distance for each axis. Uses double-precision. Can be used for
distance queries, or to add a bounding box filter to a query to take advantage of a spatial index.
In addition to the version of ST_Expand accepting and returning a geometry, variants are provided that accept and return box2d
and box3d data types.
Distances are in the units of the spatial reference system of the input.
ST_Expand is similar to ST_Buffer, except while buffering expands a geometry in all directions, ST_Expand expands the bound-
ing box along each axis.
Note
Pre version 1.3, ST_Expand was used in conjunction with ST_Distance to do indexable distance queries. For exam-
ple, geom && ST_Expand(’POINT(10 20)’, 10) AND ST_Distance(geom, ’POINT(10 20)’)
< 10. This has been replaced by the simpler and more efficient ST_DWithin function.
Availability: 1.5.0 behavior changed to output double precision instead of float4 coordinates.
Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
Enhanced: 2.3.0 support was added to expand a box by different amounts in different dimensions.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
Note
Examples below use US National Atlas Equal Area (SRID=2163) which is a meter projection
-----------------------------------------------------
BOX3D(778773 2951731 -9,794885 2970052.61545891 20)
--10 meter geometry astext rep of a expand box around a point geometry
SELECT ST_AsEWKT(ST_Expand(ST_GeomFromEWKT('SRID=2163;POINT(2312980 110676)'),10));
st_asewkt
------------------------------------------------------------------------------------------------- ←-
See Also
8.17.5 ST_Extent
Synopsis
Description
An aggregate function that returns a box2d bounding box that bounds a set of geometries.
The bounding box coordinates are in the spatial reference system of the input geometries.
ST_Extent is similar in concept to Oracle Spatial/Locator’s SDO_AGGR_MBR.
Note
ST_Extent returns boxes with only X and Y ordinates even with 3D geometries. To return XYZ ordinates use
ST_3DExtent.
Note
The returned box3d value does not include a SRID. Use ST_SetSRID to convert it into a geometry with SRID meta-
data. The SRID is the same as the input geometries.
Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
PostGIS 3.3.2 Manual 414 / 902
Examples
Note
Examples below use Massachusetts State Plane ft (SRID=2249)
bextent | name
----------------------------------------------------+----------------
BOX(778783.5625 2951741.25,794875.8125 2970042.75) | A
BOX(751315.8125 2919164.75,765202.6875 2935417.25) | B
BOX(739651.875 2917394.75,756688.375 2935866) | C
bextent
--------------------------------------------------------------------------------
SRID=2249;POLYGON((739651.875 2908247.25,739651.875 2970042.75,794875.8125 2970042.75,
794875.8125 2908247.25,739651.875 2908247.25))
See Also
8.17.6 ST_3DExtent
Synopsis
Description
An aggregate function that returns a box3d (includes Z ordinate) bounding box that bounds a set of geometries.
The bounding box coordinates are in the spatial reference system of the input geometries.
Note
The returned box3d value does not include a SRID. Use ST_SetSRID to convert it into a geometry with SRID meta-
data. The SRID is the same as the input geometries.
PostGIS 3.3.2 Manual 415 / 902
Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
Changed: 2.0.0 In prior versions this used to be called ST_Extent3D
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
b3extent
--------------------
BOX3D(1 0 0,4 2 2)
See Also
8.17.7 ST_MakeBox2D
Synopsis
Description
Creates a box2d defined by two Point geometries. This is useful for doing range queries.
PostGIS 3.3.2 Manual 416 / 902
Examples
--Return all features that fall reside or partly reside in a US national atlas coordinate ←-
bounding box
--It is assumed here that the geometries are stored with SRID = 2163 (US National atlas ←-
equal area)
SELECT feature_id, feature_name, geom
FROM features
WHERE geom && ST_SetSRID(ST_MakeBox2D(ST_Point(-989502.1875, 528439.5625),
ST_Point(-987121.375 ,529933.1875)),2163)
See Also
8.17.8 ST_3DMakeBox
Synopsis
Description
Examples
--bb3d--
--------
BOX3D(-989502.1875 528439.5625 10,-987121.375 529933.1875 10)
See Also
8.17.9 ST_XMax
Synopsis
Description
Note
Although this function is only defined for box3d, it also works for box2d and geometry values due to automatic casting.
However, it will not accept a geometry or box2d text representation, since those do not auto-cast.
Examples
See Also
8.17.10 ST_XMin
Synopsis
Description
Note
Although this function is only defined for box3d, it also works for box2d and geometry values due to automatic casting.
However it will not accept a geometry or box2d text representation, since those do not auto-cast.
Examples
See Also
8.17.11 ST_YMax
Synopsis
Description
Note
Although this function is only defined for box3d, it also works for box2d and geometry values due to automatic casting.
However it will not accept a geometry or box2d text representation, since those do not auto-cast.
Examples
See Also
8.17.12 ST_YMin
Synopsis
Description
Note
Although this function is only defined for box3d, it also works for box2d and geometry values due to automatic casting.
However it will not accept a geometry or box2d text representation, since those do not auto-cast.
Examples
See Also
8.17.13 ST_ZMax
Synopsis
Description
Note
Although this function is only defined for box3d, it also works for box2d and geometry values due to automatic casting.
However it will not accept a geometry or box2d text representation, since those do not auto-cast.
Examples
See Also
8.17.14 ST_ZMin
Synopsis
Description
Note
Although this function is only defined for box3d, it also works for box2d and geometry values due to automatic casting.
However it will not accept a geometry or box2d text representation, since those do not auto-cast.
Examples
See Also
8.18.1 ST_LineInterpolatePoint
Synopsis
Description
Returns a point interpolated along a line at a fractional location. First argument must be a LINESTRING. Second argument is a
float between 0 and 1 representing the fraction of line length where the point is to be located. The Z and M values are interpolated
if present.
See ST_LineLocatePoint for computing the line location nearest to a Point.
Note
This function computes points in 2D and then interpolates values for Z and M, while ST_3DLineInterpolatePoint com-
putes points in 3D and only interpolates the M value.
Note
Since release 1.1.1 this function also interpolates M and Z values (when present), while prior releases set them to 0.0.
Examples
See Also
8.18.2 ST_3DLineInterpolatePoint
Synopsis
Description
Returns a point interpolated along a 3D line at a fractional location. First argument must be a LINESTRING. Second argument
is a float between 0 and 1 representing the point location as a fraction of line length. The M value is interpolated if present.
Note
ST_LineInterpolatePoint computes points in 2D and then interpolates the values for Z and M, while this function com-
putes points in 3D and only interpolates the M value.
Availability: 3.0.0
Examples
st_asetext
----------------
POINT Z (59.0675892910822 84.0675892910822 79.0846904776219)
PostGIS 3.3.2 Manual 425 / 902
See Also
8.18.3 ST_LineInterpolatePoints
Synopsis
Description
Returns one or more points interpolated along a line at a fractional interval. The first argument must be a LINESTRING. The
second argument is a float8 between 0 and 1 representing the spacing between the points as a fraction of line length. If the third
argument is false, at most one point will be constructed (which is equivalent to ST_LineInterpolatePoint.)
If the result has zero or one points, it is returned as a POINT. If it has two or more points, it is returned as a MULTIPOINT.
Availability: 2.5.0
Examples
See Also
ST_LineInterpolatePoint, ST_LineLocatePoint
8.18.4 ST_LineLocatePoint
ST_LineLocatePoint — Returns the fractional location of the closest point on a line to a point.
Synopsis
Description
Returns a float between 0 and 1 representing the location of the closest point on a LineString to the given Point, as a fraction of
2d line length.
You can use the returned location to extract a Point (ST_LineInterpolatePoint) or a substring (ST_LineSubstring).
This is useful for approximating numbers of addresses
Availability: 1.1.0
Changed: 2.1.0. Up to 2.0.x this was called ST_Line_Locate_Point.
Examples
--Rough approximation of finding the street number of a point along the street
--Note the whole foo thing is just to generate dummy data that looks
--like house centroids and street
--We use ST_DWithin to exclude
--houses too far away from the street to be considered on the street
SELECT ST_AsText(house_loc) As as_text_house_loc,
startstreet_num +
CAST( (endstreet_num - startstreet_num)
* ST_LineLocatePoint(street_line, house_loc) As integer) As street_num
FROM
(SELECT ST_GeomFromText('LINESTRING(1 2, 3 4)') As street_line,
ST_Point(x*1.01,y*1.03) As house_loc, 10 As startstreet_num,
20 As endstreet_num
FROM generate_series(1,3) x CROSS JOIN generate_series(2,4) As y)
As foo
WHERE ST_DWithin(street_line, house_loc, 0.2);
as_text_house_loc | street_num
-------------------+------------
POINT(1.01 2.06) | 10
POINT(2.02 3.09) | 15
POINT(3.03 4.12) | 20
See Also
8.18.5 ST_LineSubstring
Synopsis
Description
Computes the line which is the section of the input line starting and ending at the given fractional locations. The first argument
must be a LINESTRING. The second and third arguments are values in the range [0, 1] representing the start and end locations
as fractions of line length. The Z and M values are interpolated for added endpoints if present.
If startfraction and endfraction have the same value this is equivalent to ST_LineInterpolatePoint.
Note
This only works with LINESTRINGs. To use on contiguous MULTILINESTRINGs first join them with ST_LineMerge.
Note
Since release 1.1.1 this function interpolates M and Z values. Prior releases set Z and M to unspecified values.
Examples
SELECT ST_AsText(ST_LineSubstring( 'LINESTRING (20 180, 50 20, 90 80, 120 40, 180 150)', ←-
0.333, 0.666));
------------------------------------------------------------------------------------------------ ←-
If start and end locations are the same, the result is a POINT.
SELECT ST_AsText(ST_LineSubstring( 'LINESTRING(25 50, 100 125, 150 190)', 0.333, 0.333));
------------------------------------------
POINT(69.2846934853974 94.2846934853974)
A query to cut a LineString into sections of length 100 or shorter. It uses generate_series() with a CROSS JOIN LAT-
ERAL to produce the equivalent of a FOR loop.
WITH data(id, geom) AS (VALUES
( 'A', 'LINESTRING( 0 0, 200 0)'::geometry ),
( 'B', 'LINESTRING( 0 100, 350 100)'::geometry ),
( 'C', 'LINESTRING( 0 200, 50 200)'::geometry )
)
SELECT id, i,
ST_AsText( ST_LineSubstring( geom, startfrac, LEAST( endfrac, 1 )) ) AS geom
FROM (
SELECT id, geom, ST_Length(geom) len, 100 sublen FROM data
) AS d
CROSS JOIN LATERAL (
SELECT i, (sublen * i) / len AS startfrac,
(sublen * (i+1)) / len AS endfrac
FROM generate_series(0, floor( len / sublen )::integer ) AS t(i)
-- skip last i if line length is exact multiple of sublen
WHERE (sublen * i) / len <> 1.0
) AS d2;
id | i | geom
----+---+-----------------------------
A | 0 | LINESTRING(0 0,100 0)
A | 1 | LINESTRING(100 0,200 0)
B | 0 | LINESTRING(0 100,100 100)
B | 1 | LINESTRING(100 100,200 100)
B | 2 | LINESTRING(200 100,300 100)
B | 3 | LINESTRING(300 100,350 100)
C | 0 | LINESTRING(0 200,50 200)
See Also
8.18.6 ST_LocateAlong
Synopsis
Description
Returns the location(s) along a measured geometry that have the given measure values. The result is a Point or MultiPoint.
Polygonal inputs are not supported.
If offset is provided, the result is offset to the left or right of the input line by the specified distance. A positive offset will be
to the left, and a negative one to the right.
Note
Use this function only for linear geometries with an M component
This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1.13
Examples
SELECT ST_AsText(
ST_LocateAlong(
'MULTILINESTRINGM((1 2 3, 3 4 2, 9 4 3),(1 2 3, 5 4 5))'::geometry,
3 ));
----------------------------------
MULTIPOINT M ((1 2 3),(9 4 3),(1 2 3))
See Also
8.18.7 ST_LocateBetween
Synopsis
geometry ST_LocateBetween(geometry geom, float8 measure_start, float8 measure_end, float8 offset = 0);
Description
Return a geometry (collection) with the portions of the input measured geometry that match the specified measure range (inclu-
sively).
If the offset is provided, the result is offset to the left or right of the input line by the specified distance. A positive offset will
be to the left, and a negative one to the right.
Clipping a non-convex POLYGON may produce invalid geometry.
PostGIS 3.3.2 Manual 430 / 902
This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1
Examples
SELECT ST_AsText(
ST_LocateBetween(
'MULTILINESTRING M ((1 2 3, 3 4 2, 9 4 3),(1 2 3, 5 4 5))':: geometry,
1.5, 3 ));
------------------------------------------------------------------------
GEOMETRYCOLLECTION M (LINESTRING M (1 2 3,3 4 2,9 4 3),POINT M (1 2 3))
A LineString with the section between measures 2 and 8, offset to the left
SELECT ST_AsText( ST_LocateBetween(
ST_AddMeasure('LINESTRING (20 180, 50 20, 100 120, 180 20)', 0, 10),
2, 8,
20
));
------------------------------------------------------------------------
MULTILINESTRING((54.49835019899045 104.53426957938231,58.70056060327303 ←-
82.12248075654186,69.16695286779743 103.05526528559065,82.11145618000168 ←-
128.94427190999915,84.24893681714357 132.32493442618113,87.01636951231555 ←-
135.21267035596549,90.30307285299679 137.49198684843182,93.97759758337769 ←-
139.07172433557758,97.89298381958797 139.8887023914453,101.89263860095893 ←-
139.9102465862721,105.81659870902816 139.13549527600819,109.50792827749828 ←-
137.5954340631298,112.81899532549731 135.351656550512,115.6173761888606 ←-
132.49390095108848,145.31017306064817 95.37790486135405))
See Also
ST_LocateAlong, ST_LocateBetweenElevations
PostGIS 3.3.2 Manual 431 / 902
8.18.8 ST_LocateBetweenElevations
ST_LocateBetweenElevations — Returns the portions of a geometry that lie in an elevation (Z) range.
Synopsis
Description
Returns a geometry (collection) with the portions of a geometry that lie in an elevation (Z) range.
Clipping a non-convex POLYGON may produce invalid geometry.
Availability: 1.4.0
Enhanced: 3.0.0 - added support for POLYGON, TIN, TRIANGLE.
Examples
SELECT ST_AsText(
ST_LocateBetweenElevations(
'LINESTRING(1 2 3, 4 5 6)'::geometry,
2, 4 ));
st_astext
-----------------------------------
MULTILINESTRING Z ((1 2 3,2 3 4))
SELECT ST_AsText(
ST_LocateBetweenElevations(
'LINESTRING(1 2 6, 4 5 -1, 7 8 9)',
6, 9)) As ewelev;
ewelev
-----------------------------------------------------------------------
GEOMETRYCOLLECTION Z (POINT Z (1 2 6),LINESTRING Z (6.1 7.1 6,7 8 9))
See Also
ST_Dump, ST_LocateBetween
8.18.9 ST_InterpolatePoint
Synopsis
Description
Returns an interpolated measure value of a linear measured geometry at the location closest to the given point.
Note
Use this function only for linear geometries with an M component
Availability: 2.0.0
Examples
See Also
8.18.10 ST_AddMeasure
Synopsis
Description
Return a derived geometry with measure values linearly interpolated between the start and end points. If the geometry has
no measure dimension, one is added. If the geometry has a measure dimension, it is over-written with new values. Only
LINESTRINGS and MULTILINESTRINGS are supported.
Availability: 1.5.0
Examples
SELECT ST_AsText(ST_AddMeasure(
ST_GeomFromEWKT('LINESTRING(1 0, 2 0, 4 0)'),1,4)) As ewelev;
ewelev
--------------------------------
LINESTRINGM(1 0 1,2 0 2,4 0 4)
SELECT ST_AsText(ST_AddMeasure(
ST_GeomFromEWKT('LINESTRING(1 0 4, 2 0 4, 4 0 4)'),10,40)) As ewelev;
ewelev
PostGIS 3.3.2 Manual 433 / 902
----------------------------------------
LINESTRING(1 0 4 10,2 0 4 20,4 0 4 40)
SELECT ST_AsText(ST_AddMeasure(
ST_GeomFromEWKT('LINESTRINGM(1 0 4, 2 0 4, 4 0 4)'),10,40)) As ewelev;
ewelev
----------------------------------------
LINESTRINGM(1 0 10,2 0 20,4 0 40)
SELECT ST_AsText(ST_AddMeasure(
ST_GeomFromEWKT('MULTILINESTRINGM((1 0 4, 2 0 4, 4 0 4),(1 0 4, 2 0 4, 4 0 4))'),10,70)) As ←-
ewelev;
ewelev
-----------------------------------------------------------------
MULTILINESTRINGM((1 0 10,2 0 20,4 0 40),(1 0 40,2 0 50,4 0 70))
8.19.1 ST_IsValidTrajectory
Synopsis
Description
Tests if a geometry encodes a valid trajectory. A valid trajectory is represented as a LINESTRING with measures (M values).
The measure values must increase from each vertex to the next.
Valid trajectories are expected as input to spatio-temporal functions like ST_ClosestPointOfApproach
Availability: 2.2.0
Examples
-- A valid trajectory
SELECT ST_IsValidTrajectory(ST_MakeLine(
ST_MakePointM(0,0,1),
ST_MakePointM(0,1,2))
);
t
-- An invalid trajectory
SELECT ST_IsValidTrajectory(ST_MakeLine(ST_MakePointM(0,0,1), ST_MakePointM(0,1,0)));
NOTICE: Measure of vertex 1 (0) not bigger than measure of vertex 0 (1)
st_isvalidtrajectory
----------------------
f
PostGIS 3.3.2 Manual 434 / 902
See Also
ST_ClosestPointOfApproach
8.19.2 ST_ClosestPointOfApproach
Synopsis
Description
Returns the smallest measure at which points interpolated along the given trajectories are at the smallest distance.
Inputs must be valid trajectories as checked by ST_IsValidTrajectory. Null is returned if the trajectories do not overlap in their
M ranges.
See ST_LocateAlong for getting the actual points at the given measure.
Availability: 2.2.0
Examples
-- Return the time in which two objects moving between 10:00 and 11:00
-- are closest to each other and their distance at that point
WITH inp AS ( SELECT
ST_AddMeasure('LINESTRING Z (0 0 0, 10 0 5)'::geometry,
extract(epoch from '2015-05-26 10:00'::timestamptz),
extract(epoch from '2015-05-26 11:00'::timestamptz)
) a,
ST_AddMeasure('LINESTRING Z (0 2 10, 12 1 2)'::geometry,
extract(epoch from '2015-05-26 10:00'::timestamptz),
extract(epoch from '2015-05-26 11:00'::timestamptz)
) b
), cpa AS (
SELECT ST_ClosestPointOfApproach(a,b) m FROM inp
), points AS (
SELECT ST_Force3DZ(ST_GeometryN(ST_LocateAlong(a,m),1)) pa,
ST_Force3DZ(ST_GeometryN(ST_LocateAlong(b,m),1)) pb
FROM inp, cpa
)
SELECT to_timestamp(m) t,
ST_Distance(pa,pb) distance
FROM points, cpa;
t | distance
-------------------------------+------------------
2015-05-26 10:45:31.034483+02 | 1.96036833151395
See Also
8.19.3 ST_DistanceCPA
ST_DistanceCPA — Returns the distance between the closest point of approach of two trajectories.
Synopsis
Description
Returns the minimum distance two moving objects have ever been each other.
Inputs must be valid trajectories as checked by ST_IsValidTrajectory. Null is returned if the trajectories do not overlap in their
M ranges.
Availability: 2.2.0
Examples
-- Return the minimum distance of two objects moving between 10:00 and 11:00
WITH inp AS ( SELECT
ST_AddMeasure('LINESTRING Z (0 0 0, 10 0 5)'::geometry,
extract(epoch from '2015-05-26 10:00'::timestamptz),
extract(epoch from '2015-05-26 11:00'::timestamptz)
) a,
ST_AddMeasure('LINESTRING Z (0 2 10, 12 1 2)'::geometry,
extract(epoch from '2015-05-26 10:00'::timestamptz),
extract(epoch from '2015-05-26 11:00'::timestamptz)
) b
)
SELECT ST_DistanceCPA(a,b) distance FROM inp;
distance
------------------
1.96036833151395
See Also
8.19.4 ST_CPAWithin
ST_CPAWithin — Tests if the closest point of approach of two trajectories is within the specified distance.
Synopsis
Description
Tests whether two moving objects have ever been closer than the specified distance.
Inputs must be valid trajectories as checked by ST_IsValidTrajectory. False is returned if the trajectories do not overlap in their
M ranges.
Availability: 2.2.0
Examples
st_cpawithin | distance
--------------+------------------
t | 1.96521473776207
See Also
8.20.1 postgis_sfcgal_version
Synopsis
text postgis_sfcgal_version(void);
Description
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
PostGIS 3.3.2 Manual 437 / 902
See Also
postgis_sfcgal_full_version
8.20.2 postgis_sfcgal_full_version
postgis_sfcgal_full_version — Returns the full version of SFCGAL in use including CGAL and Boost versions
Synopsis
text postgis_sfcgal_full_version(void);
Description
Returns the full version of SFCGAL in use including CGAL and Boost versions
Availability: 3.3.0
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
See Also
postgis_sfcgal_version
8.20.3 ST_3DArea
Synopsis
floatST_3DArea(geometry geom1);
Description
Availability: 2.1.0
This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 8.1, 10.5
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
PostGIS 3.3.2 Manual 438 / 902
Examples
Note: By default a PolyhedralSurface built from WKT is a surface geometry, not solid. It therefore has surface area. Once
converted to a solid, no area.
SELECT ST_3DArea(geom) As cube_surface_area,
ST_3DArea(ST_MakeSolid(geom)) As solid_surface_area
FROM (SELECT 'POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)),
((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)),
((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)),
((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)),
((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)),
((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )'::geometry) As f(geom);
cube_surface_area | solid_surface_area
-------------------+--------------------
6 | 0
See Also
8.20.4 ST_3DConvexHull
Synopsis
Description
Availability: 3.3.0
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
POLYHEDRALSURFACE Z (((1 5 3,9 5 3,0 0 5,1 5 3)),((1 5 3,0 0 5,5 7 6,1 5 3)),((5 7 6,5 7 ←-
5,1 5 3,5 7 6)),((0 0 5,6 3 5,5 7 6,0 0 5)),((6 3 5,9 5 3,5 7 6,6 3 5)),((0 0 5,9 5 3,6 ←-
3 5,0 0 5)),((9 5 3,5 7 5,5 7 6,9 5 3)),((1 5 3,5 7 5,9 5 3,1 5 3)))
PostGIS 3.3.2 Manual 439 / 902
See Also
ST_Letters, ST_AsX3D
8.20.5 ST_3DIntersection
Synopsis
Description
Return a geometry that is the shared portion between geom1 and geom2.
Availability: 2.1.0
PostGIS 3.3.2 Manual 440 / 902
This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
3D images were generated using PostGIS ST_AsX3D and rendering in HTML using X3Dom HTML Javascript rendering library.
SELECT ST_3DIntersection(geom1,geom2)
SELECT ST_Extrude(ST_Buffer( ←- FROM ( SELECT ST_Extrude(ST_Buffer( ←-
ST_GeomFromText('POINT(100 90)'), ST_GeomFromText('POINT(100 90)'),
50, 'quad_segs=2'),0,0,30) AS geom1, 50, 'quad_segs=2'),0,0,30) AS geom1,
ST_Extrude(ST_Buffer( ←- ST_Extrude(ST_Buffer( ←-
ST_GeomFromText('POINT(80 80)'), ST_GeomFromText('POINT(80 80)'),
50, 'quad_segs=1'),0,0,30) AS geom2; 50, 'quad_segs=1'),0,0,30) AS geom2 ) As ←-
t;
wkt
--------------------------------
LINESTRING Z (1 1 8,0.5 0.5 8)
TIN Z (((0 0 0,0 0 0.5,0 0.5 0.5,0 0 0)),((0 0.5 0,0 0 0,0 0.5 0.5,0 0.5 0)))
Intersection of 2 solids that result in volumetric intersection is also a solid (ST_Dimension returns 3)
SELECT ST_AsText(ST_3DIntersection( ST_Extrude(ST_Buffer('POINT(10 20)'::geometry,10,1) ←-
,0,0,30),
ST_Extrude(ST_Buffer('POINT(10 20)'::geometry,10,1),2,0,10) ));
8.20.6 ST_3DDifference
Synopsis
Description
This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
PostGIS 3.3.2 Manual 442 / 902
Examples
3D images were generated using PostGIS ST_AsX3D and rendering in HTML using X3Dom HTML Javascript rendering library.
SELECT ST_3DDifference(geom1,geom2)
FROM ( SELECT ST_Extrude(ST_Buffer( ←-
SELECT ST_Extrude(ST_Buffer( ←- ST_GeomFromText('POINT(100 90)'),
ST_GeomFromText('POINT(100 90)'), 50, 'quad_segs=2'),0,0,30) AS geom1,
50, 'quad_segs=2'),0,0,30) AS geom1, ST_Extrude(ST_Buffer( ←-
ST_Extrude(ST_Buffer( ←- ST_GeomFromText('POINT(80 80)'),
ST_GeomFromText('POINT(80 80)'), 50, 'quad_segs=1'),0,0,30) AS geom2 ) As ←-
50, 'quad_segs=1'),0,0,30) AS geom2; t;
See Also
8.20.7 ST_3DUnion
Synopsis
Description
Availability: 2.2.0
Availability: 3.3.0 aggregate variant was added
This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Aggregate variant: returns a geometry that is the 3D union of a rowset of geometries. The ST_3DUnion() 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.
Examples
3D images were generated using PostGIS ST_AsX3D and rendering in HTML using X3Dom HTML Javascript rendering library.
SELECT ST_3DUnion(geom1,geom2)
SELECT ST_Extrude(ST_Buffer( ←- FROM ( SELECT ST_Extrude(ST_Buffer( ←-
ST_GeomFromText('POINT(100 90)'), ST_GeomFromText('POINT(100 90)'),
50, 'quad_segs=2'),0,0,30) AS geom1, 50, 'quad_segs=2'),0,0,30) AS geom1,
ST_Extrude(ST_Buffer( ←- ST_Extrude(ST_Buffer( ←-
ST_GeomFromText('POINT(80 80)'), ST_GeomFromText('POINT(80 80)'),
50, 'quad_segs=1'),0,0,30) AS geom2; 50, 'quad_segs=1'),0,0,30) AS geom2 ) As ←-
t;
See Also
8.20.8 ST_AlphaShape
ST_AlphaShape — Computes a possible concave geometry using the CGAL Alpha Shapes algorithm.
Synopsis
Description
Assume we are given a set S of points in 2D [...] and we would like to have something like "the shape formed by these points".
This is quite a vague notion and there are probably many possible interpretations, the α-shape being one of them. Alpha shapes
PostGIS 3.3.2 Manual 444 / 902
can be used for shape reconstruction from a dense unorganized set of data points. Indeed, an α-shape is demarcated by a frontier,
which is a linear approximation of the original shape [1]. [1] F. Bernardini and C. Bajaj. Sampling and reconstructing manifolds
using alpha-shapes. Technical Report CSD-TR-97-013, Dept. Comput. Sci., Purdue Univ., West Lafayette, IN, 1997. Source:
CGAL ALpha Shapes This function compute the concave hull of a set of geometry, but using CGAL and a different algorithm
than ST_ConcaveHull performed by the GEOS module. See : Concave Hulls in JTS
Availability: 3.3.0 - requires SFCGAL >= 1.4.1.
Examples
POLYGON((89 53,91 50,87 42,90 30,88 29,84 19,78 16,73 16,65 16,53 18,43 19,37 23,30 22,28 ←-
33,23 36,26 44,27 54,23 60,24 67,
27 77,24 82,26 85,34 86,39 88,45 90,49 95,52 98,57 97,64 97,72 95,76 88,75 84,83 ←-
72,85 71,88 58,89 53))
PostGIS 3.3.2 Manual 445 / 902
POLYGON((89 53,91 50,87 42,90 30,88 29,84 19,78 16,73 16,65 16,53 18,43 19,37 23,30 22,28 ←-
33,23 36,26 44,27 54,23 60,24 67,27 77,24 82,26 85,34 86,39 88,45 90,49 95,52 98,57 ←-
97,64 97,72 95,76 88,75 84,83 72,85 71,88 58,89 53),
(36 61,36 68,40 75,43 80,50 86,60 81,68 73,77 67,81 60,82 54,81 47,78 43,76 ←-
27,62 22,54 32,48 34,44 42,38 46,36 61))
SELECT ST_AlphaShape(
'MULTIPOINT ((132 64), (114 64), (99 64), (81 64), (63 64), (57 49), (52 36), ←-
(46 20), (37 20), (26 20), (32 36), (39 55), (43 69), (50 84), (57 100), (63 ←-
118), (68 133), (74 149), (81 164), (88 180), (101 180), (112 180), (119 ←-
164), (126 149), (132 131), (139 113), (143 100), (150 84), (157 69), (163 ←-
51), (168 36), (174 20), (163 20), (150 20), (143 36), (139 49), (132 64), ←-
(99 151), (92 138), (88 124), (81 109), (74 93), (70 82), (83 82), (99 82), ←-
(112 82), (126 82), (121 96), (114 109), (110 122), (103 138), (99 151), (34 ←-
27), (43 31), (48 44), (46 58), (52 73), (63 73), (61 84), (72 71), (90 69) ←-
, (101 76), (123 71), (141 62), (166 27), (150 33), (159 36), (146 44), (154 ←-
53), (152 62), (146 73), (134 76), (143 82), (141 91), (130 98), (126 104), ←-
(132 113), (128 127), (117 122), (112 133), (119 144), (108 147), (119 153) ←-
, (110 171), (103 164), (92 171), (86 160), (88 142), (79 140), (72 124), ←-
(83 131), (79 118), (68 113), (63 102), (68 93), (35 45))'::geometry,102.2, ←-
true);
POLYGON((134 80,136 75,130 63,135 45,132 44,126 28,117 24,110 24,98 24,80 27,82 39,72 51,60 ←-
48,56 34,52 52,42 50,
34 54,39 66,40 81,34 90,36 100,40 116,36 123,39 128,51 129,58 132,68 135,74 ←-
142,78 147,86 146,96 146,
108 142,114 132,112 126,112 116,116 110,120 108,125 108,128 106,125 96,132 ←-
87,134 80))
See Also
ST_ConcaveHull, ST_OptimalAlphaShape
8.20.9 ST_ApproximateMedialAxis
Synopsis
Description
Return an approximate medial axis for the areal input based on its straight skeleton. Uses an SFCGAL specific API when built
against a capable version (1.2.0+). Otherwise the function is just a wrapper around ST_StraightSkeleton (slower case).
Availability: 2.2.0
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
See Also
ST_StraightSkeleton
8.20.10 ST_ConstrainedDelaunayTriangles
ST_ConstrainedDelaunayTriangles — Return a constrained Delaunay triangulation around the given input geometry.
Synopsis
Description
Return a Constrained Delaunay triangulation around the vertices of the input geometry. Output is a TIN.
Examples
PostGIS 3.3.2 Manual 448 / 902
See Also
8.20.11 ST_Extrude
Synopsis
Description
Availability: 2.1.0
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
PostGIS 3.3.2 Manual 449 / 902
Examples
3D images were generated using PostGIS ST_AsX3D and rendering in HTML using X3Dom HTML Javascript rendering library.
SELECT ST_Buffer(ST_GeomFromText('POINT ←-
(100 90)'), ST_Extrude(ST_Buffer(ST_GeomFromText(' ←-
50, 'quad_segs=2'),0,0,30); POINT(100 90)'),
50, 'quad_segs=2'),0,0,30);
Original linestring
See Also
ST_AsX3D
PostGIS 3.3.2 Manual 450 / 902
8.20.12 ST_ForceLHR
Synopsis
Description
Availability: 2.1.0
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
8.20.13 ST_IsPlanar
Synopsis
Description
Availability: 2.2.0: This was documented in 2.1.0 but got accidentally left out in 2.1 release.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
8.20.14 ST_IsSolid
Synopsis
Description
Availability: 2.2.0
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
8.20.15 ST_MakeSolid
ST_MakeSolid — Cast the geometry into a solid. No check is performed. To obtain a valid solid, the input geometry must be a
closed Polyhedral Surface or a closed TIN.
Synopsis
Description
Availability: 2.2.0
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
8.20.16 ST_MinkowskiSum
Synopsis
Description
This function performs a 2D minkowski sum of a point, line or polygon with a polygon.
A minkowski sum of two geometries A and B is the set of all points that are the sum of any point in A and B. Minkowski sums
are often used in motion planning and computer-aided design. More details on Wikipedia Minkowski addition.
The first parameter can be any 2D geometry (point, linestring, polygon). If a 3D geometry is passed, it will be converted to 2D
by forcing Z to 0, leading to possible cases of invalidity. The second parameter must be a 2D polygon.
Implementation utilizes CGAL 2D Minkowskisum.
Availability: 2.1.0
Examples
Minkowski Sum of Linestring and circle polygon where Linestring cuts thru the circle
-- wkt --
MULTIPOLYGON(((30 59.9999999999999,30.5764415879031 54.1472903395161,32.2836140246614 ←-
48.5194970290472,35.0559116309237 43.3328930094119,38.7867965644036 ←-
38.7867965644035,43.332893009412 35.0559116309236,48.5194970290474 ←-
32.2836140246614,54.1472903395162 30.5764415879031,60.0000000000001 30,65.8527096604839 ←-
30.5764415879031,71.4805029709527 32.2836140246614,76.6671069905881 ←-
35.0559116309237,81.2132034355964 38.7867965644036,171.213203435596 ←-
128.786796564404,174.944088369076 133.332893009412,177.716385975339 ←-
138.519497029047,179.423558412097 144.147290339516,180 150,179.423558412097 ←-
155.852709660484,177.716385975339 161.480502970953,174.944088369076 ←-
166.667106990588,171.213203435596 171.213203435596,166.667106990588 174.944088369076,
161.480502970953 177.716385975339,155.852709660484 179.423558412097,150 ←-
180,144.147290339516 179.423558412097,138.519497029047 177.716385975339,133.332893009412 ←-
174.944088369076,128.786796564403 171.213203435596,38.7867965644035 ←-
81.2132034355963,35.0559116309236 76.667106990588,32.2836140246614 ←-
71.4805029709526,30.5764415879031 65.8527096604838,30 59.9999999999999)))
-- wkt --
MULTIPOLYGON(
((70 115,100 135,175 175,225 225,70 115)),
((120 65,150 85,225 125,275 175,120 65))
)
8.20.17 ST_OptimalAlphaShape
ST_OptimalAlphaShape — Computes a possible concave geometry using the CGAL Alpha Shapes algorithm after have com-
puted the "optimal" alpha value.
Synopsis
Description
Computes the "optimal" alpha-shapes of the set of geometry. CGAL can automatically find the optimal value of alpha. This
version uses it to find an "optimal" alpha-shape. The result is a single polygon. It will not contain holes unless the optional
param_allow_holes argument is specified as true. The result will be generated such that the number of solid component of
the alpha shape is equal to or smaller than param_nb_components.
Availability: 3.3.0 - requires SFCGAL >= 1.4.1.
Examples
POLYGON((89 53,91 50,87 42,90 30,88 29,84 19,78 16,73 16,65 16,53 18,43 19,37 23,30 22,28 ←-
33,23 36,
26 44,27 54,23 60,24 67,27 77,24 82,26 85,34 86,39 88,45 90,49 95,52 98,57 ←-
97,64 97,72 95,76 88,75 84,75 77,83 72,85 71,83 64,88 58,89 53))
PostGIS 3.3.2 Manual 455 / 902
POLYGON((89 53,91 50,87 42,90 30,88 29,84 19,78 16,73 16,65 16,53 18,43 19,37 23,30 22,28 ←-
33,23 36,26 44,27 54,23 60,24 67,27 77,24 82,26 85,34 86,39 88,45 90,49 95,52 98,57 ←-
97,64 97,72 95,76 88,75 84,75 77,83 72,85 71,83 64,88 58,89 53),(36 61,36 68,40 75,43 ←-
80,50 86,60 81,68 73,77 67,81 60,82 54,81 47,78 43,81 29,76 27,70 20,62 22,55 26,54 ←-
32,48 34,44 42,38 46,36 61))
See Also
ST_ConcaveHull, ST_AlphaShape
8.20.18 ST_Orientation
Synopsis
Description
The function only applies to polygons. It returns -1 if the polygon is counterclockwise oriented and 1 if the polygon is clockwise
oriented.
PostGIS 3.3.2 Manual 456 / 902
Availability: 2.1.0
8.20.19 ST_StraightSkeleton
Synopsis
Description
Availability: 2.1.0
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
Original polygon
PostGIS 3.3.2 Manual 457 / 902
8.20.20 ST_Tesselate
ST_Tesselate — Perform surface Tesselation of a polygon or polyhedralsurface and returns as a TIN or collection of TINS
Synopsis
Description
Takes as input a surface such a MULTI(POLYGON) or POLYHEDRALSURFACE and returns a TIN representation via the
process of tessellation using triangles.
Availability: 2.1.0
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Examples
PostGIS 3.3.2 Manual 458 / 902
SELECT ST_Tesselate(ST_GeomFromText(' ←-
POLYHEDRALSURFACE Z( ((0 0 0, 0 0 1, 0 1 1, 0 1
((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 ←-
0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)),
((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 ←-
0)),
((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 ←-
SELECT ST_GeomFromText('POLYHEDRALSURFACE ←- 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )'))
Z( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)),
ST_AsText output:
((0 0 0, 0 1 0, 1 1 0, 1 ←-
0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1,TIN
0 0Z 0)),
(((0 0 0,0 0 1,0 1 1,0 0 0)),((0 1 ←-
((1 1 0, 1 1 1, 1 0 1, 1 ←- 0,0 0 0,0 1 1,0 1 0)),
0 0, 1 1 0)), ((0 0 0,0 1 0,1 1 0,0 0 0)),
((0 1 0, 0 1 1, 1 1 1, 1 ←- ((1 0 0,0 0 0,1 1 0,1 0 0)),((0 0 ←-
1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1,1
1)) 0)');
0,1 0 1,0 0 1)),
((0 0 1,0 0 0,1 0 0,0 0 1)),
((1 1 0,1 1 1,1 0 1,1 1 0)),((1 0 ←-
0,1 1 0,1 0 1,1 0 0)),
((0 1 0,0 1 1,1 1 1,0 1 0)),((1 1 ←-
0,0 1 0,1 1 1,1 1 0)),
((0 1 1,1 0 1,1 1 1,0 1 1)),((0 1 ←-
1,0 0 1,1 0 1,0 1 1)))
Original Cube
SELECT
ST_Tesselate('POLYGON (( 10 190, ←-
10 70, 80 70, 80 130, 50 160, 120 160, 120 190,
Original polygon
Tesselated Polygon
See Also
ST_ConstrainedDelaunayTriangles, ST_DelaunayTriangles
8.20.21 ST_Volume
ST_Volume — Computes the volume of a 3D solid. If applied to surface (even closed) geometries will return 0.
Synopsis
Description
Availability: 2.2.0
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 9.1 (same as ST_3DVolume)
Example
When closed surfaces are created with WKT, they are treated as areal rather than solid. To make them solid, you need to use
ST_MakeSolid. Areal geometries have no volume. Here is an example to demonstrate.
SELECT ST_Volume(geom) As cube_surface_vol,
ST_Volume(ST_MakeSolid(geom)) As solid_surface_vol
FROM (SELECT 'POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)),
((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)),
((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)),
((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)),
((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)),
((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )'::geometry) As f(geom);
cube_surface_vol | solid_surface_vol
------------------+-------------------
0 | 1
See Also
Note
For the locking mechanism to operate correctly the serializable transaction isolation level must be used.
8.21.1 AddAuth
Synopsis
Description
Examples
---Error--
ERROR: UPDATE where "gid" = '353' requires authorization 'priscilla'
See Also
LockRow
8.21.2 CheckAuth
CheckAuth — Creates a trigger on a table to prevent/allow updates and deletes of rows based on authorization token.
Synopsis
Description
Creates trigger on a table to prevent/allow updates and deletes of rows based on an authorization token. Identify rows using
<rowid_col> column.
If a_schema_name is not passed in, then searches for table in current schema.
Note
If an authorization trigger already exists on this table function errors.
If Transaction support is not enabled, function throws an exception.
Availability: 1.1.3
Examples
See Also
EnableLongTransactions
PostGIS 3.3.2 Manual 462 / 902
8.21.3 DisableLongTransactions
Synopsis
text DisableLongTransactions();
Description
Disables long transaction support. This function removes the long transaction support metadata tables, and drops all triggers
attached to lock-checked tables.
Drops meta table called authorization_table and a view called authorized_tables and all triggers called checkauthtri
Availability: 1.1.3
Examples
SELECT DisableLongTransactions();
--result--
Long transactions support disabled
See Also
EnableLongTransactions
8.21.4 EnableLongTransactions
Synopsis
text EnableLongTransactions();
Description
Enables long transaction support. This function creates the required metadata tables. It must be called once before using the
other functions in this section. Calling it twice is harmless.
Creates a meta table called authorization_table and a view called authorized_tables
Availability: 1.1.3
Examples
SELECT EnableLongTransactions();
--result--
Long transactions support enabled
See Also
DisableLongTransactions
PostGIS 3.3.2 Manual 463 / 902
8.21.5 LockRow
Synopsis
integer LockRow(text a_schema_name, text a_table_name, text a_row_key, text an_auth_token, timestamp expire_dt);
integer LockRow(text a_table_name, text a_row_key, text an_auth_token, timestamp expire_dt);
integer LockRow(text a_table_name, text a_row_key, text an_auth_token);
Description
Sets lock/authorization for a specific row in a table. an_auth_token is a text value. expire_dt is a timestamp which
defaults to now() + 1 hour. Returns 1 if lock has been assigned, 0 otherwise (i.e. row is already locked by another auth.)
Availability: 1.1.3
Examples
--Joey has already locked the record and Priscilla is out of luck
SELECT LockRow('public', 'towns', '2', 'priscilla');
LockRow
-------
0
See Also
UnlockRows
8.21.6 UnlockRows
Synopsis
Description
Removes all locks held by specified authorization token. Returns the number of locks released.
Availability: 1.1.3
PostGIS 3.3.2 Manual 464 / 902
Examples
See Also
LockRow
8.22.1 PostGIS_Extensions_Upgrade
PostGIS_Extensions_Upgrade — Packages and upgrades PostGIS extensions (e.g. postgis_raster, postgis_topology, postgis_sfcgal)
to latest available version.
Synopsis
text PostGIS_Extensions_Upgrade();
Description
Packages and upgrades PostGIS extensions to latest version. Only extensions you have installed in the database will be packaged
and upgraded if needed. Reports full PostGIS version and build configuration infos after. This is short-hand for doing multiple
CREATE EXTENSION .. FROM unpackaged and ALTER EXTENSION .. UPDATE for each PostGIS extension. Currently
only tries to upgrade extensions postgis, postgis_raster, postgis_sfcgal, postgis_topology, and postgis_tiger_geocoder.
Availability: 2.5.0
Note
Changed: 3.3.0 support for upgrades from any PostGIS version. Does not work on all systems.
Changed: 3.0.0 to repackage loose extensions and support postgis_raster.
Examples
SELECT PostGIS_Extensions_Upgrade();
postgis_extensions_upgrade
-------------------------------------------------------------------
Upgrade completed, run SELECT postgis_full_version(); for details
(1 row)
PostGIS 3.3.2 Manual 465 / 902
See Also
8.22.2 PostGIS_Full_Version
Synopsis
text PostGIS_Full_Version();
Description
Reports full PostGIS version and build configuration infos. Also informs about synchronization between libraries and scripts
suggesting upgrades as needed.
Examples
SELECT PostGIS_Full_Version();
postgis_full_version
----------------------------------------------------------------------------------
POSTGIS="3.0.0dev r17211" [EXTENSION] PGSQL="110" GEOS="3.8.0dev-CAPI-1.11.0 df24b6bb" ←-
SFCGAL="1.3.6" PROJ="Rel. 5.2.0, September 15th, 2018"
GDAL="GDAL 2.3.2, released 2018/09/21" LIBXML="2.9.9" LIBJSON="0.13.1" LIBPROTOBUF="1.3.1" ←-
WAGYU="0.4.3 (Internal)" TOPOLOGY RASTER
(1 row)
See Also
8.22.3 PostGIS_GEOS_Version
Synopsis
text PostGIS_GEOS_Version();
Description
Returns the version number of the GEOS library, or NULL if GEOS support is not enabled.
Examples
SELECT PostGIS_GEOS_Version();
postgis_geos_version
----------------------
3.1.0-CAPI-1.5.0
(1 row)
PostGIS 3.3.2 Manual 466 / 902
See Also
8.22.4 PostGIS_Liblwgeom_Version
PostGIS_Liblwgeom_Version — Returns the version number of the liblwgeom library. This should match the version of PostGIS.
Synopsis
text PostGIS_Liblwgeom_Version();
Description
Examples
SELECT PostGIS_Liblwgeom_Version();
postgis_liblwgeom_version
--------------------------
2.3.3 r15473
(1 row)
See Also
8.22.5 PostGIS_LibXML_Version
Synopsis
text PostGIS_LibXML_Version();
Description
Examples
SELECT PostGIS_LibXML_Version();
postgis_libxml_version
----------------------
2.7.6
(1 row)
PostGIS 3.3.2 Manual 467 / 902
See Also
8.22.6 PostGIS_Lib_Build_Date
Synopsis
text PostGIS_Lib_Build_Date();
Description
Examples
SELECT PostGIS_Lib_Build_Date();
postgis_lib_build_date
------------------------
2008-06-21 17:53:21
(1 row)
8.22.7 PostGIS_Lib_Version
Synopsis
text PostGIS_Lib_Version();
Description
Examples
SELECT PostGIS_Lib_Version();
postgis_lib_version
---------------------
1.3.3
(1 row)
See Also
8.22.8 PostGIS_PROJ_Version
Synopsis
text PostGIS_PROJ_Version();
Description
Returns the version number of the PROJ4 library, or NULL if PROJ4 support is not enabled.
Examples
SELECT PostGIS_PROJ_Version();
postgis_proj_version
-------------------------
Rel. 4.4.9, 29 Oct 2004
(1 row)
See Also
8.22.9 PostGIS_Wagyu_Version
Synopsis
text PostGIS_Wagyu_Version();
Description
Returns the version number of the internal Wagyu library, or NULL if Wagyu support is not enabled.
Examples
SELECT PostGIS_Wagyu_Version();
postgis_wagyu_version
-----------------------
0.4.3 (Internal)
(1 row)
See Also
8.22.10 PostGIS_Scripts_Build_Date
Synopsis
text PostGIS_Scripts_Build_Date();
Description
Examples
SELECT PostGIS_Scripts_Build_Date();
postgis_scripts_build_date
-------------------------
2007-08-18 09:09:26
(1 row)
See Also
8.22.11 PostGIS_Scripts_Installed
Synopsis
text PostGIS_Scripts_Installed();
Description
Note
If the output of this function doesn’t match the output of PostGIS_Scripts_Released you probably missed to properly
upgrade an existing database. See the Upgrading section for more info.
Availability: 0.9.0
Examples
SELECT PostGIS_Scripts_Installed();
postgis_scripts_installed
-------------------------
1.5.0SVN
(1 row)
PostGIS 3.3.2 Manual 470 / 902
See Also
8.22.12 PostGIS_Scripts_Released
PostGIS_Scripts_Released — Returns the version number of the postgis.sql script released with the installed PostGIS lib.
Synopsis
text PostGIS_Scripts_Released();
Description
Returns the version number of the postgis.sql script released with the installed PostGIS lib.
Note
Starting with version 1.1.0 this function returns the same value of PostGIS_Lib_Version. Kept for backward compatibil-
ity.
Availability: 0.9.0
Examples
SELECT PostGIS_Scripts_Released();
postgis_scripts_released
-------------------------
1.3.4SVN
(1 row)
See Also
8.22.13 PostGIS_Version
Synopsis
text PostGIS_Version();
Description
Examples
SELECT PostGIS_Version();
postgis_version
---------------------------------------
1.3 USE_GEOS=1 USE_PROJ=1 USE_STATS=1
(1 row)
See Also
8.23.1 postgis.backend
postgis.backend — The backend to service a function where GEOS and SFCGAL overlap. Options: geos or sfcgal. Defaults to
geos.
Description
This GUC is only relevant if you compiled PostGIS with sfcgal support. By default geos backend is used for functions where
both GEOS and SFCGAL have the same named function. This variable allows you to override and make sfcgal the backend to
service the request.
Availability: 2.1.0
Examples
See Also
Section 8.20
8.23.2 postgis.gdal_datapath
postgis.gdal_datapath — A configuration option to assign the value of GDAL’s GDAL_DATA option. If not set, the environmen-
tally set GDAL_DATA variable is used.
PostGIS 3.3.2 Manual 472 / 902
Description
A PostgreSQL GUC variable for setting the value of GDAL’s GDAL_DATA option. The postgis.gdal_datapath value
should be the complete physical path to GDAL’s data files.
This configuration option is of most use for Windows platforms where GDAL’s data files path is not hard-coded. This option
should also be set when GDAL’s data files are not located in GDAL’s expected path.
Note
This option can be set in PostgreSQL’s configuration file postgresql.conf. It can also be set by connection or transaction.
Availability: 2.2.0
Note
Additional information about GDAL_DATA is available at GDAL’s Configuration Options.
Examples
See Also
PostGIS_GDAL_Version, ST_Transform
8.23.3 postgis.gdal_enabled_drivers
postgis.gdal_enabled_drivers — A configuration option to set the enabled GDAL drivers in the PostGIS environment. Affects
the GDAL configuration variable GDAL_SKIP.
Description
A configuration option to set the enabled GDAL drivers in the PostGIS environment. Affects the GDAL configuration variable
GDAL_SKIP. This option can be set in PostgreSQL’s configuration file: postgresql.conf. It can also be set by connection or
transaction.
The initial value of postgis.gdal_enabled_drivers may also be set by passing the environment variable POSTGIS_GDAL_EN
with the list of enabled drivers to the process starting PostgreSQL.
Enabled GDAL specified drivers can be specified by the driver’s short-name or code. Driver short-names or codes can be found
at GDAL Raster Formats. Multiple drivers can be specified by putting a space between each driver.
PostGIS 3.3.2 Manual 473 / 902
Note
There are three special codes available for postgis.gdal_enabled_drivers. The codes are case-sensitive.
• DISABLE_ALL disables all GDAL drivers. If present, DISABLE_ALL overrides all other values in
postgis.gdal_enabled_drivers.
• ENABLE_ALL enables all GDAL drivers.
• VSICURL enables GDAL’s /vsicurl/ virtual file system.
Note
In the standard PostGIS installation, postgis.gdal_enabled_drivers is set to DISABLE_ALL.
Note
Additional information about GDAL_SKIP is available at GDAL’s Configuration Options.
Availability: 2.2.0
Examples
Sets default enabled drivers for all new connections to server. Requires super user access and PostgreSQL 9.4+. Also note that
database, session, and user settings override this.
ALTER SYSTEM SET postgis.gdal_enabled_drivers TO 'GTiff PNG JPEG';
SELECT pg_reload_conf();
See Also
8.23.4 postgis.enable_outdb_rasters
Description
A boolean configuration option to enable access to out-db raster bands. This option can be set in PostgreSQL’s configuration file:
postgresql.conf. It can also be set by connection or transaction.
The initial value of postgis.enable_outdb_rasters may also be set by passing the environment variable POSTGIS_ENABLE_
with a non-zero value to the process starting PostgreSQL.
Note
Even if postgis.enable_outdb_rasters is True, the GUC postgis.gdal_enabled_drivers deter-
mines the accessible raster formats.
Note
In the standard PostGIS installation, postgis.enable_outdb_rasters is set to False.
Availability: 2.2.0
Examples
Setting for whole database cluster. You need to reconnect to the database for changes to take effect.
--writes to postgres.auto.conf
ALTER SYSTEM postgis.enable_outdb_rasters = true;
--Reloads postgres conf
SELECT pg_reload_conf();
See Also
postgis.gdal_enabled_drivers postgis.gdal_config_options
8.23.5 postgis.gdal_config_options
postgis.gdal_config_options — A string configuration to set options used when working with an out-db raster.
PostGIS 3.3.2 Manual 475 / 902
Description
A string configuration to set options used when working with an out-db raster. Configuration options control things like how
much space GDAL allocates to local data cache, whether to read overviews, and what access keys to use for remote out-db data
sources.
Availability: 3.2.0
Examples
Set postgis.gdal_vsi_options just for the current transaction using the LOCAL keyword:
SET LOCAL postgis.gdal_config_options = 'AWS_ACCESS_KEY_ID=xxxxxxxxxxxxxxx ←-
AWS_SECRET_ACCESS_KEY=yyyyyyyyyyyyyyyyyyyyyyyyyy';
See Also
postgis.enable_outdb_rasters postgis.gdal_enabled_drivers
8.24.1 PostGIS_AddBBox
Synopsis
Description
Add bounding box to the geometry. This would make bounding box based queries faster, but will increase the size of the
geometry.
Note
Bounding boxes are automatically added to geometries so in general this is not needed unless the generated bounding
box somehow becomes corrupted or you have an old install that is lacking bounding boxes. Then you need to drop the
old and readd.
Examples
UPDATE sometable
SET geom = PostGIS_AddBBox(geom)
WHERE PostGIS_HasBBox(geom) = false;
PostGIS 3.3.2 Manual 476 / 902
See Also
PostGIS_DropBBox, PostGIS_HasBBox
8.24.2 PostGIS_DropBBox
Synopsis
Description
Drop the bounding box cache from the geometry. This reduces geometry size, but makes bounding-box based queries slower. It
is also used to drop a corrupt bounding box. A tale-tell sign of a corrupt cached bounding box is when your ST_Intersects and
other relation queries leave out geometries that rightfully should return true.
Note
Bounding boxes are automatically added to geometries and improve speed of queries so in general this is not needed
unless the generated bounding box somehow becomes corrupted or you have an old install that is lacking bounding
boxes. Then you need to drop the old and readd. This kind of corruption has been observed in 8.3-8.3.6 series whereby
cached bboxes were not always recalculated when a geometry changed and upgrading to a newer version without a
dump reload will not correct already corrupted boxes. So one can manually correct using below and readd the bbox or
do a dump reload.
Examples
--This example drops bounding boxes where the cached box is not correct
--The force to ST_AsBinary before applying Box2D forces a recalculation of the box, ←-
and Box2D applied to the table geometry always
-- returns the cached bounding box.
UPDATE sometable
SET geom = PostGIS_DropBBox(geom)
WHERE Not (Box2D(ST_AsBinary(geom)) = Box2D(geom));
UPDATE sometable
SET geom = PostGIS_AddBBox(geom)
WHERE Not PostGIS_HasBBOX(geom);
See Also
8.24.3 PostGIS_HasBBox
PostGIS_HasBBox — Returns TRUE if the bbox of this geometry is cached, FALSE otherwise.
PostGIS 3.3.2 Manual 477 / 902
Synopsis
Description
Returns TRUE if the bbox of this geometry is cached, FALSE otherwise. Use PostGIS_AddBBox and PostGIS_DropBBox to
control caching.
Examples
SELECT geom
FROM sometable WHERE PostGIS_HasBBox(geom) = false;
See Also
PostGIS_AddBBox, PostGIS_DropBBox
PostGIS 3.3.2 Manual 478 / 902
Chapter 9
1. Where can I find tutorials, guides and workshops on working with PostGIS
A step by step tutorial guide workshop Introduction to PostGIS. It includes packaged data as well as intro to working with
OpenGeo Suite. It is probably the best tutorial on PostGIS.BostonGIS also has a PostGIS almost idiot’s guide on getting
started. That one is more focused on the windows user.
2. My applications and desktop tools worked with PostGIS 1.5,but they don’t work with PostGIS 2.0. How do I fix this?
A lot of deprecated functions were removed from the PostGIS code base in PostGIS 2.0. This has affected applications
in addition to third-party tools such as Geoserver, MapServer, QuantumGIS, and OpenJump to name a few. There are a
couple of ways to resolve this. For the third-party apps, you can try to upgrade to the latest versions of these which have
many of these issues fixed. For your own code, you can change your code to not use the functions removed. Most of these
functions are non ST_ aliases of ST_Union, ST_Length etc. and as a last resort, install the whole of legacy.sql or
just the portions of legacy.sql you need.The legacy.sql file is located in the same folder as postgis.sql. You can
install this file after you have installed postgis.sql and spatial_ref_sys.sql to get back all the 200 some-odd old functions
we removed.
3. When I load OpenStreetMap data with osm2pgsql, I’m getting an error failed: ERROR: operator class "gist_geometry_ops"
does not exist for access method "gist" Error occurred. This worked fine in PostGIS 1.5.
In PostGIS 2, the default geometry operator class gist_geometry_ops was changed to gist_geometry_ops_2d and the
gist_geometry_ops was completely removed. This was done because PostGIS 2 also introduced Nd spatial indexes for
3D support and the old name was deemed confusing and a misnomer.Some older applications that as part of the process
create tables and indexes, explicitly referenced the operator class name. This was unnecessary if you want the default 2D
index. So if you manage said good, change index creation from:BAD:
CREATE INDEX idx_my_table_geom ON my_table USING gist(geom gist_geometry_ops);
To GOOD:
CREATE INDEX idx_my_table_geom ON my_table USING gist(geom);
The only case where you WILL need to specify the operator class is if you want a 3D spatial index as follows:
CREATE INDEX idx_my_super3d_geom ON my_super3d USING gist(geom gist_geometry_ops_nd);
If you are unfortunate to be stuck with compiled code you can’t change that has the old gist_geometry_ops hard-coded,
then you can create the old class using the legacy_gist.sql packaged in PostGIS 2.0.2+. However if you use this
fix, you are advised to at a later point drop the index and recreate it without the operator class. This will save you grief in
the future when you need to upgrade again.
4. I’m running PostgreSQL 9.0 and I can no longer read/view geometries in OpenJump, Safe FME, and some other tools?
In PostgreSQL 9.0+, the default encoding for bytea data has been changed to hex and older JDBC drivers still assume
escape format. This has affected some applications such as Java applications using older JDBC drivers or .NET ap-
plications that use the older npgsql driver that expect the old behavior of ST_AsBinary. There are two approaches to
PostGIS 3.3.2 Manual 479 / 902
getting this to work again.You can upgrade your JDBC driver to the latest PostgreSQL 9.0 version which you can get
from http://jdbc.postgresql.org/download.htmlIf you are running a .NET app, you can use Npgsql 2.0.11 or higher which
you can download from http://pgfoundry.org/frs/?group_id=1000140 and as described on Francisco Figueiredo’s NpgSQL
2.0.11 released blog entryIf upgrading your PostgreSQL driver is not an option, then you can set the default back to the
old behavior with the following change:
ALTER DATABASE mypostgisdb SET bytea_output='escape';
5. I tried to use PgAdmin to view my geometry column and it is blank, what gives?
PgAdmin doesn’t show anything for large geometries. The best ways to verify you do have data in your geometry columns
are?
-- this should return no records if all your geom fields are filled in
SELECT somefield FROM mytable WHERE geom IS NULL;
If the geometry column definition fails, you probably have not loaded the PostGIS functions and objects into this database
or are using a pre-2.0 version of PostGIS. See the Section 2.2.Then, you can insert a geometry into the table using a SQL
insert statement. The GIS object itself is formatted using the OpenGIS Consortium "well-known text" format:
PostGIS 3.3.2 Manual 480 / 902
For more information about other GIS objects, see the object reference.To view your GIS data in the table:
SELECT id, name, ST_AsText(geom) AS geom FROM gtest;
The "USING GIST" option tells the server to use a GiST (Generalized Search Tree) index.
Note
GiST indexes are assumed to be lossy. Lossy indexes uses a proxy object (in the spatial case, a bounding box)
for building the index.
You should also ensure that the PostgreSQL query planner has enough information about your index to make rational
decisions about when to use it. To do this, you have to "gather statistics" on your geometry tables.For PostgreSQL
8.0.x and greater, just run the VACUUM ANALYZE command.For PostgreSQL 7.4.x and below, run the SELECT UP-
DATE_GEOMETRY_STATS() command.
12. Why aren’t PostgreSQL R-Tree indexes supported?
Early versions of PostGIS used the PostgreSQL R-Tree indexes. However, PostgreSQL R-Trees have been completely
discarded since version 0.6, and spatial indexing is provided with an R-Tree-over-GiST scheme.Our tests have shown
search speed for native R-Tree and GiST to be comparable. Native PostgreSQL R-Trees have two limitations which make
them undesirable for use with GIS features (note that these limitations are due to the current PostgreSQL native R-Tree
implementation, not the R-Tree concept in general):
PostGIS 3.3.2 Manual 481 / 902
• R-Tree indexes in PostgreSQL cannot handle features which are larger than 8K in size. GiST indexes can, using the
"lossy" trick of substituting the bounding box for the feature itself.
• R-Tree indexes in PostgreSQL are not "null safe", so building an index on a geometry column which contains null
geometries will fail.
13. Why should I use the AddGeometryColumn() function and all the other OpenGIS stuff?
If you do not want to use the OpenGIS support functions, you do not have to. Simply create tables as in older versions,
defining your geometry columns in the CREATE statement. All your geometries will have SRIDs of -1, and the OpenGIS
meta-data tables will not be filled in properly. However, this will cause most applications based on PostGIS to fail, and it
is generally suggested that you do use AddGeometryColumn() to create geometry tables.MapServer is one application
which makes use of the geometry_columns meta-data. Specifically, MapServer can use the SRID of the geometry
column to do on-the-fly reprojection of features into the correct map projection.
14. What is the best way to find all objects within a radius of another object?
To use the database most efficiently, it is best to do radius queries which combine the radius test with a bounding box test:
the bounding box test uses the spatial index, giving fast access to a subset of data which the radius test is then applied to.The
ST_DWithin(geometry, geometry, distance) function is a handy way of performing an indexed distance
search. It works by creating a search rectangle large enough to enclose the distance radius, then performing an exact
distance search on the indexed subset of results.For example, to find all objects with 100 meters of POINT(1000 1000) the
following query would work well:
SELECT * FROM geotable
WHERE ST_DWithin(geocolumn, 'POINT(1000 1000)', 100.0);
16. I did an ST_AsEWKT and ST_AsText on my rather large geometry and it returned blank field. What gives?
You are probably using PgAdmin or some other tool that doesn’t output large text. If your geometry is big enough, it will
appear blank in these tools. Use PSQL if you really need to see it or output it in WKT.
--To check number of geometries are really blank
SELECT count(gid) FROM geotable WHERE geom IS NULL;
17. When I do an ST_Intersects, it says my two geometries don’t intersect when I KNOW THEY DO. What gives?
This generally happens in two common cases. Your geometry is invalid -- check ST_IsValid or you are assuming they
intersect because ST_AsText truncates the numbers and you have lots of decimals after it is not showing you.
18. I am releasing software that uses PostGIS, does that mean my software has to be licensed using the GPL like PostGIS?
Will I have to publish all my code if I use PostGIS?
Almost certainly not. As an example, consider Oracle database running on Linux. Linux is GPL, Oracle is not: does
Oracle running on Linux have to be distributed using the GPL? No. Similarly your software can use a PostgreSQL/PostGIS
database as much as it wants and be under any license you like.The only exception would be if you made changes to the
PostGIS source code, and distributed your changed version of PostGIS. In that case you would have to share the code of
your changed PostGIS (but not the code of applications running on top of it). Even in this limited case, you would still only
have to distribute source code to people you distributed binaries to. The GPL does not require that you publish your source
code, only that you share it with people you give binaries to.The above remains true even if you use PostGIS in conjunction
with the optional CGAL-enabled functions. Portions of CGAL are GPL, but so is all of PostGIS already: using CGAL
does not make PostGIS any more GPL than it was to start with.
19. Why are the results of overlay operations and spatial predicates sometimes inconsistent?
This is usually presented as a specific case, such as
PostGIS 3.3.2 Manual 482 / 902
Chapter 10
Topology
The PostGIS Topology types and functions are used to manage topological objects such as faces, edges and nodes.
Sandro Santilli’s presentation at PostGIS Day Paris 2011 conference gives a good synopsis of PostGIS Topology and where it is
headed Topology with PostGIS 2.0 slide deck.
Vincent Picavet provides a good synopsis and overview of what is Topology, how is it used, and various FOSS4G tools that
support it in PostGIS Topology PGConf EU 2012 .
An example of a topologically based GIS database is the US Census Topologically Integrated Geographic Encoding and Ref-
erencing System (TIGER) database. If you want to experiment with PostGIS topology and need some data, check out Topol-
ogy_Load_Tiger.
The PostGIS topology module has existed in prior versions of PostGIS but was never part of the Official PostGIS documentation.
In PostGIS 2.0.0 major cleanup is going on to remove use of all deprecated functions in it, fix known usability issues, better
document the features and functions, add new functions, and enhance to closer conform to SQL-MM standards.
Details of this project can be found at PostGIS Topology Wiki
All functions and tables associated with this module are installed in a schema called topology.
Functions that are defined in SQL/MM standard are prefixed with ST_ and functions specific to PostGIS are not prefixed.
Topology support is build by default starting with PostGIS 2.0, and can be disabled specifying --without-topology configure
option at build time as described in Chapter 2
10.1.1 getfaceedges_returntype
getfaceedges_returntype — A composite type that consists of a sequence number and an edge number.
Description
A composite type that consists of a sequence number and an edge number. This is the return type for ST_GetFaceEdges and
GetNodeEdges functions.
1. sequence is an integer: Refers to a topology defined in the topology.topology table which defines the topology schema
and srid.
2. edge is an integer: The identifier of an edge.
PostGIS 3.3.2 Manual 484 / 902
10.1.2 TopoGeometry
Description
A composite type that refers to a topology geometry in a specific topology layer, having a specific type and a specific id. The
elements of a TopoGeometry are the properties: topology_id, layer_id, id integer, type integer.
1. topology_id is an integer: Refers to a topology defined in the topology.topology table which defines the topology
schema and srid.
2. layer_id is an integer: The layer_id in the layers table that the TopoGeometry belongs to. The combination of topol-
ogy_id, layer_id provides a unique reference in the topology.layers table.
3. id is an integer: The id is the autogenerated sequence number that uniquely defines the topogeometry in the respective
topology layer.
4. type integer between 1 - 4 that defines the geometry type: 1:[multi]point, 2:[multi]line, 3:[multi]poly, 4:collection
Casting Behavior
This section lists the automatic as well as explicit casts allowed for this data type
Cast To Behavior
geometry automatic
See Also
CreateTopoGeom
10.1.3 validatetopology_returntype
validatetopology_returntype — A composite type that consists of an error message and id1 and id2 to denote location of error.
This is the return type for ValidateTopology.
Description
A composite type that consists of an error message and two integers. The ValidateTopology function returns a set of these to
denote validation errors and the id1 and id2 to denote the ids of the topology objects involved in the error.
See Also
ValidateTopology
PostGIS 3.3.2 Manual 485 / 902
10.2.1 TopoElement
Description
Note
For any given hierarchical TopoGeometry all child TopoGeometry elements will come from the same child layer, as
specified in the topology.layer record for the layer of the TopoGeometry being defined.
Examples
SELECT ARRAY[1,2]::topology.topoelement;
te
-------
{1,2}
--Example of what happens when you try to case a 3 element array to topoelement
-- NOTE: topoement has to be a 2 element array so fails dimension check
SELECT ARRAY[1,2,3]::topology.topoelement;
ERROR: value for domain topology.topoelement violates check constraint "dimensions"
See Also
10.2.2 TopoElementArray
Description
An array of 1 or more TopoElement objects, generally used to pass around components of TopoGeometry objects.
PostGIS 3.3.2 Manual 486 / 902
Examples
tea
-------
{{1,2},{4,3}}
See Also
10.3.1 AddTopoGeometryColumn
AddTopoGeometryColumn — Adds a topogeometry column to an existing table, registers this new column as a layer in topol-
ogy.layer and returns the new layer_id.
Synopsis
Description
Each TopoGeometry object belongs to a specific Layer of a specific Topology. Before creating a TopoGeometry object you need
to create its TopologyLayer. A Topology Layer is an association of a feature-table with the topology. It also contain type and
hierarchy information. We create a layer using the AddTopoGeometryColumn() function:
This function will both add the requested column to the table and add a record to the topology.layer table with all the given info.
If you don’t specify [child_layer] (or set it to NULL) this layer would contain Basic TopoGeometries (composed by primitive
topology elements). Otherwise this layer will contain hierarchical TopoGeometries (composed by TopoGeometries from the
child_layer).
Once the layer is created (its id is returned by the AddTopoGeometryColumn function) you’re ready to construct TopoGeometry
objects in it
PostGIS 3.3.2 Manual 487 / 902
Examples
-- Note for this example we created our new table in the ma_topo schema
-- though we could have created it in a different schema -- in which case topology_name and ←-
schema_name would be different
CREATE SCHEMA ma;
CREATE TABLE ma.parcels(gid serial, parcel_id varchar(20) PRIMARY KEY, address text);
SELECT topology.AddTopoGeometryColumn('ma_topo', 'ma', 'parcels', 'topo', 'POLYGON');
See Also
10.3.2 DropTopology
DropTopology — Use with caution: Drops a topology schema and deletes its reference from topology.topology table and refer-
ences to tables in that schema from the geometry_columns table.
Synopsis
Description
Drops a topology schema and deletes its reference from topology.topology table and references to tables in that schema from
the geometry_columns table. This function should be USED WITH CAUTION, as it could destroy data you care about. If the
schema does not exist, it just removes reference entries the named schema.
Availability: 1.1
Examples
Cascade drops the ma_topo schema and removes all references to it in topology.topology and geometry_columns.
SELECT topology.DropTopology('ma_topo');
See Also
DropTopoGeometryColumn
10.3.3 DropTopoGeometryColumn
DropTopoGeometryColumn — Drops the topogeometry column from the table named table_name in schema schema_name
and unregisters the columns from topology.layer table.
PostGIS 3.3.2 Manual 488 / 902
Synopsis
Description
Drops the topogeometry column from the table named table_name in schema schema_name and unregisters the columns
from topology.layer table. Returns summary of drop status. NOTE: it first sets all values to NULL before dropping to bypass
referential integrity checks.
Availability: 1.1
Examples
See Also
AddTopoGeometryColumn
10.3.4 Populate_Topology_Layer
Populate_Topology_Layer — Adds missing entries to topology.layer table by reading metadata from topo tables.
Synopsis
Description
Adds missing entries to the topology.layer table by inspecting topology constraints on tables. This function is useful for
fixing up entries in topology catalog after restores of schemas with topo data.
It returns the list of entries created. Returned columns are schema_name, table_name, feature_column.
Availability: 2.3.0
Examples
SELECT CreateTopology('strk_topo');
CREATE SCHEMA strk;
CREATE TABLE strk.parcels(gid serial, parcel_id varchar(20) PRIMARY KEY, address text);
SELECT topology.AddTopoGeometryColumn('strk_topo', 'strk', 'parcels', 'topo', 'POLYGON');
-- this will return no records because this feature is already registered
SELECT *
FROM topology.Populate_Topology_Layer();
-- let's rebuild
TRUNCATE TABLE topology.layer;
SELECT *
FROM topology.Populate_Topology_Layer();
topology_id | layer_id | sn | tn | fc
-------------+----------+------+---------+------
2 | 2 | strk | parcels | topo
(1 row)
See Also
AddTopoGeometryColumn
10.3.5 TopologySummary
TopologySummary — Takes a topology name and provides summary totals of types of objects in topology.
Synopsis
Description
Takes a topology name and provides summary totals of types of objects in topology.
Availability: 2.0.0
Examples
SELECT topology.topologysummary('city_data');
topologysummary
--------------------------------------------------------
Topology city_data (329), SRID 4326, precision: 0
22 nodes, 24 edges, 10 faces, 29 topogeoms in 5 layers
Layer 1, type Polygonal (3), 9 topogeoms
Deploy: features.land_parcels.feature
Layer 2, type Puntal (1), 8 topogeoms
Deploy: features.traffic_signs.feature
Layer 3, type Lineal (2), 8 topogeoms
Deploy: features.city_streets.feature
Layer 4, type Polygonal (3), 3 topogeoms
Hierarchy level 1, child layer 1
Deploy: features.big_parcels.feature
Layer 5, type Puntal (1), 1 topogeoms
Hierarchy level 1, child layer 2
Deploy: features.big_signs.feature
See Also
Topology_Load_Tiger
PostGIS 3.3.2 Manual 490 / 902
10.3.6 ValidateTopology
Synopsis
Description
Returns a set of validatetopology_returntype objects detailing issues with topology, optionally limiting the check to the area
specified by the bbox parameter.
List of possible errors, what they mean and what the returned ids represent are displayed below:
Availability: 1.0.0
Enhanced: 2.0.0 more efficient edge crossing detection and fixes for false positives that were existent in prior versions.
Changed: 2.2.0 values for id1 and id2 were swapped for ’edge crosses node’ to be consistent with error description.
Changed: 3.2.0 added optional bbox parameter, perform face labeling and edge linking checks.
Examples
See Also
validatetopology_returntype, Topology_Load_Tiger
PostGIS 3.3.2 Manual 492 / 902
10.3.7 ValidateTopologyRelation
Synopsis
Description
Returns a set records giving information about invalidities in the relation table of the topology.
Availability: 3.2.0
See Also
ValidateTopology
10.3.8 FindTopology
Synopsis
Description
Takes a topology identifier or the identifier of a topology-related object and returns a topology.topology record.
Availability: 3.2.0
Examples
See Also
FindLayer
10.3.9 FindLayer
Synopsis
Description
Takes a layer identifier or the identifier of a topology-related object and returns a topology.layer record.
Availability: 3.2.0
Examples
See Also
FindTopology
Adding elements to a topology triggers many database queries for finding existing edges that will be split, adding nodes and
updating edges that will node with the new linework. For this reason it is useful that statistics about the data in the topology
tables are up-to-date.
PostGIS Topology population and editing functions do not automatically update the statistics because a updating stats after each
and every change in a topology would be overkill, so it is the caller’s duty to take care of that.
Note
That the statistics updated by autovacuum will NOT be visible to transactions which started before autovacuum process
completed, so long-running transactions will need to run ANALYZE themselves, to use updated statistics.
10.5.1 CreateTopology
CreateTopology — Creates a new topology schema and registers this new schema in the topology.topology table.
Synopsis
Description
Creates a new schema with name topology_name consisting of tables (edge_data,face,node, relation and registers
this new topology in the topology.topology table. It returns the id of the topology in the topology table. The srid is the spatial
reference identified as defined in spatial_ref_sys table for that topology. Topologies must be uniquely named. The tolerance is
measured in the units of the spatial reference system. If the tolerance (prec) is not specified defaults to 0.
This is similar to the SQL/MM ST_InitTopoGeo but a bit more functional. hasz defaults to false if not specified.
Availability: 1.1
Enhanched: 2.0 added the signature accepting hasZ
Examples
This example creates a new schema called ma_topo that will store edges, faces, and relations in Massachusetts State Plane meters.
The tolerance represents 1/2 meter since the spatial reference system is a meter based spatial reference system
SELECT topology.CreateTopology('ma_topo',26986, 0.5);
See Also
10.5.2 CopyTopology
CopyTopology — Makes a copy of a topology structure (nodes, edges, faces, layers and TopoGeometries).
Synopsis
Description
Creates a new topology with name new_topology_name and SRID and precision taken from existing_topology_name,
copies all nodes, edges and faces in there, copies layers and their TopoGeometries too.
Note
The new rows in topology.layer will contain synthesized values for schema_name, table_name and feature_column.
This is because the TopoGeometry will only exist as a definition but won’t be available in any user-level table yet.
Availability: 2.0.0
PostGIS 3.3.2 Manual 495 / 902
Examples
See Also
10.5.3 ST_InitTopoGeo
ST_InitTopoGeo — Creates a new topology schema and registers this new schema in the topology.topology table and details
summary of process.
Synopsis
Description
This is an SQL-MM equivalent of CreateTopology but lacks the spatial reference and tolerance options of CreateTopology and
outputs a text description of creation instead of topology id.
Availability: 1.1
This method implements the SQL/MM specification. SQL-MM 3 Topo-Geo and Topo-Net 3: Routine Details: X.3.17
Examples
See Also
CreateTopology
10.5.4 ST_CreateTopoGeo
ST_CreateTopoGeo — Adds a collection of geometries to a given empty topology and returns a message detailing success.
Synopsis
Description
Adds a collection of geometries to a given empty topology and returns a message detailing success.
Useful for populating an empty topology.
Availability: 2.0
This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details -- X.3.18
Examples
-- Populate topology --
SELECT topology.ST_CreateTopoGeo('ri_topo',
ST_GeomFromText('MULTILINESTRING((384744 236928,384750 236923,384769 236911,384799 ←-
236895,384811 236890,384833 236884,
384844 236882,384866 236881,384879 236883,384954 236898,385087 236932,385117 236938,
385167 236938,385203 236941,385224 236946,385233 236950,385241 236956,385254 236971,
385260 236979,385268 236999,385273 237018,385273 237037,385271 237047,385267 237057,
385225 237125,385210 237144,385192 237161,385167 237192,385162 237202,385159 237214,
385159 237227,385162 237241,385166 237256,385196 237324,385209 237345,385234 237375,
385237 237383,385238 237399,385236 237407,385227 237419,385213 237430,385193 237439,
385174 237451,385170 237455,385169 237460,385171 237475,385181 237503,385190 237521,
385200 237533,385206 237538,385213 237541,385221 237542,385235 237540,385242 237541,
385249 237544,385260 237555,385270 237570,385289 237584,385292 237589,385291 ←-
237596,385284 237630))',3438)
);
st_createtopogeo
----------------------------
Topology ri_topo populated
See Also
10.5.5 TopoGeo_AddPoint
TopoGeo_AddPoint — Adds a point to an existing topology using a tolerance and possibly splitting an existing edge.
Synopsis
Description
Adds a point to an existing topology and returns its identifier. The given point will snap to existing nodes or edges within given
tolerance. An existing edge may be split by the snapped point.
Availability: 2.0.0
PostGIS 3.3.2 Manual 497 / 902
See Also
10.5.6 TopoGeo_AddLineString
TopoGeo_AddLineString — Adds a linestring to an existing topology using a tolerance and possibly splitting existing edges/-
faces. Returns edge identifiers.
Synopsis
Description
Adds a linestring to an existing topology and returns a set of edge identifiers forming it up. The given line will snap to existing
nodes or edges within given tolerance. Existing edges and faces may be split by the line.
Note
Updating statistics about topologies being loaded via this function is up to caller, see maintaining statistics during
topology editing and population.
Availability: 2.0.0
See Also
10.5.7 TopoGeo_AddPolygon
TopoGeo_AddPolygon — Adds a polygon to an existing topology using a tolerance and possibly splitting existing edges/faces.
Returns face identifiers.
Synopsis
Description
Adds a polygon to an existing topology and returns a set of face identifiers forming it up. The boundary of the given polygon
will snap to existing nodes or edges within given tolerance. Existing edges and faces may be split by the boundary of the new
polygon.
Note
Updating statistics about topologies being loaded via this function is up to caller, see maintaining statistics during
topology editing and population.
Availability: 2.0.0
PostGIS 3.3.2 Manual 498 / 902
See Also
10.6.1 ST_AddIsoNode
ST_AddIsoNode — Adds an isolated node to a face in a topology and returns the nodeid of the new node. If face is null, the
node is still created.
Synopsis
Description
Adds an isolated node with point location apoint to an existing face with faceid aface to a topology atopology and returns
the nodeid of the new node.
If the spatial reference system (srid) of the point geometry is not the same as the topology, the apoint is not a point geometry,
the point is null, or the point intersects an existing edge (even at the boundaries) then an exception is thrown. If the point already
exists as a node, an exception is thrown.
If aface is not null and the apoint is not within the face, then an exception is thrown.
Availability: 1.1
This method implements the SQL/MM specification. SQL-MM: Topo-Net Routines: X+1.3.1
Examples
See Also
10.6.2 ST_AddIsoEdge
ST_AddIsoEdge — Adds an isolated edge defined by geometry alinestring to a topology connecting two existing isolated
nodes anode and anothernode and returns the edge id of the new edge.
Synopsis
Description
Adds an isolated edge defined by geometry alinestring to a topology connecting two existing isolated nodes anode and
anothernode and returns the edge id of the new edge.
If the spatial reference system (srid) of the alinestring geometry is not the same as the topology, any of the input arguments
are null, or the nodes are contained in more than one face, or the nodes are start or end nodes of an existing edge, then an
exception is thrown.
PostGIS 3.3.2 Manual 499 / 902
If the alinestring is not within the face of the face the anode and anothernode belong to, then an exception is thrown.
If the anode and anothernode are not the start and end points of the alinestring then an exception is thrown.
Availability: 1.1
This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.4
Examples
See Also
10.6.3 ST_AddEdgeNewFaces
ST_AddEdgeNewFaces — Add a new edge and, if in doing so it splits a face, delete the original face and replace it with two new
faces.
Synopsis
Description
Add a new edge and, if in doing so it splits a face, delete the original face and replace it with two new faces. Returns the id of
the newly added edge.
Updates all existing joined edges and relationships accordingly.
If any arguments are null, the given nodes are unknown (must already exist in the node table of the topology schema) , the
acurve is not a LINESTRING, the anode and anothernode are not the start and endpoints of acurve then an error is
thrown.
If the spatial reference system (srid) of the acurve geometry is not the same as the topology an exception is thrown.
Availability: 2.0
This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.12
Examples
See Also
ST_RemEdgeNewFace
ST_AddEdgeModFace
10.6.4 ST_AddEdgeModFace
ST_AddEdgeModFace — Add a new edge and, if in doing so it splits a face, modify the original face and add a new face.
Synopsis
Description
Add a new edge and, if doing so splits a face, modify the original face and add a new one.
Note
If possible, the new face will be created on left side of the new edge. This will not be possible if the face on the left side
will need to be the Universe face (unbounded).
This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.13
Examples
See Also
ST_RemEdgeModFace
ST_AddEdgeNewFaces
10.6.5 ST_RemEdgeNewFace
ST_RemEdgeNewFace — Removes an edge and, if the removed edge separated two faces, delete the original faces and replace
them with a new face.
Synopsis
Description
Removes an edge and, if the removed edge separated two faces, delete the original faces and replace them with a new face.
Returns the id of a newly created face or NULL, if no new face is created. No new face is created when the removed edge is
dangling or isolated or confined with the universe face (possibly making the universe flood into the face on the other side).
Updates all existing joined edges and relationships accordingly.
Refuses to remove an edge participating in the definition of an existing TopoGeometry. Refuses to heal two faces if any TopoGe-
ometry is defined by only one of them (and not the other).
If any arguments are null, the given edge is unknown (must already exist in the edge table of the topology schema), the topology
name is invalid then an error is thrown.
Availability: 2.0
This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.14
PostGIS 3.3.2 Manual 501 / 902
Examples
See Also
ST_RemEdgeModFace
ST_AddEdgeNewFaces
10.6.6 ST_RemEdgeModFace
ST_RemEdgeModFace — Removes an edge and, if the removed edge separated two faces, delete one of the them and modify
the other to take the space of both.
Synopsis
Description
Removes an edge and, if the removed edge separated two faces, delete one of the them and modify the other to take the space of
both. Preferentially keeps the face on the right, to be symmetric with ST_AddEdgeModFace also keeping it. Returns the id of
the face remaining in place of the removed edge.
Updates all existing joined edges and relationships accordingly.
Refuses to remove an edge partecipating in the definition of an existing TopoGeometry. Refuses to heal two faces if any Topo-
Geometry is defined by only one of them (and not the other).
If any arguments are null, the given edge is unknown (must already exist in the edge table of the topology schema), the topology
name is invalid then an error is thrown.
Availability: 2.0
This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.15
Examples
See Also
ST_AddEdgeModFace
ST_RemEdgeNewFace
10.6.7 ST_ChangeEdgeGeom
ST_ChangeEdgeGeom — Changes the shape of an edge without affecting the topology structure.
Synopsis
Description
This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details X.3.6
Examples
SELECT topology.ST_ChangeEdgeGeom('ma_topo', 1,
ST_GeomFromText('LINESTRING(227591.9 893900.4,227622.6 893844.3,227641.6 893816.6, ←-
227704.5 893778.5)', 26986) );
----
Edge 1 changed
See Also
ST_AddEdgeModFace
ST_RemEdgeModFace
ST_ModEdgeSplit
10.6.8 ST_ModEdgeSplit
ST_ModEdgeSplit — Split an edge by creating a new node along an existing edge, modifying the original edge and adding a
new edge.
Synopsis
Description
Split an edge by creating a new node along an existing edge, modifying the original edge and adding a new edge. Updates all
existing joined edges and relationships accordingly. Returns the identifier of the newly added node.
Availability: 1.1
Changed: 2.0 - In prior versions, this was misnamed ST_ModEdgesSplit
This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.9
PostGIS 3.3.2 Manual 503 / 902
Examples
-- Add an edge --
SELECT topology.AddEdge('ma_topo', ST_GeomFromText('LINESTRING(227592 893910, 227600 ←-
893910)', 26986) ) As edgeid;
-- edgeid-
3
See Also
10.6.9 ST_ModEdgeHeal
ST_ModEdgeHeal — Heals two edges by deleting the node connecting them, modifying the first edge and deleting the second
edge. Returns the id of the deleted node.
Synopsis
Description
Heals two edges by deleting the node connecting them, modifying the first edge and deleting the second edge. Returns the id of
the deleted node. Updates all existing joined edges and relationships accordingly.
Availability: 2.0
This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.9
See Also
ST_ModEdgeSplit ST_NewEdgesSplit
10.6.10 ST_NewEdgeHeal
ST_NewEdgeHeal — Heals two edges by deleting the node connecting them, deleting both edges, and replacing them with an
edge whose direction is the same as the first edge provided.
Synopsis
Description
Heals two edges by deleting the node connecting them, deleting both edges, and replacing them with an edge whose direction is
the same as the first edge provided. Returns the id of the new edge replacing the healed ones. Updates all existing joined edges
and relationships accordingly.
Availability: 2.0
This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.9
See Also
10.6.11 ST_MoveIsoNode
ST_MoveIsoNode — Moves an isolated node in a topology from one point to another. If new apoint geometry exists as a node
an error is thrown. Returns description of move.
Synopsis
Description
Moves an isolated node in a topology from one point to another. If new apoint geometry exists as a node an error is thrown.
If any arguments are null, the apoint is not a point, the existing node is not isolated (is a start or end point of an existing edge),
new node location intersects an existing edge (even at the end points) or the new location is in a different face (since 3.2.0) then
an exception is thrown.
If the spatial reference system (srid) of the point geometry is not the same as the topology an exception is thrown.
Availability: 2.0.0
Enhanced: 3.2.0 ensures the nod cannot be moved in a different face
This method implements the SQL/MM specification. SQL-MM: Topo-Net Routines: X.3.2
Examples
See Also
ST_AddIsoNode
PostGIS 3.3.2 Manual 505 / 902
10.6.12 ST_NewEdgesSplit
ST_NewEdgesSplit — Split an edge by creating a new node along an existing edge, deleting the original edge and replacing it
with two new edges. Returns the id of the new node created that joins the new edges.
Synopsis
Description
Split an edge with edge id anedge by creating a new node with point location apoint along current edge, deleting the original
edge and replacing it with two new edges. Returns the id of the new node created that joins the new edges. Updates all existing
joined edges and relationships accordingly.
If the spatial reference system (srid) of the point geometry is not the same as the topology, the apoint is not a point geometry,
the point is null, the point already exists as a node, the edge does not correspond to an existing edge or the point is not within the
edge then an exception is thrown.
Availability: 1.1
This method implements the SQL/MM specification. SQL-MM: Topo-Net Routines: X.3.8
Examples
-- Add an edge --
SELECT topology.AddEdge('ma_topo', ST_GeomFromText('LINESTRING(227575 893917,227592 893900) ←-
', 26986) ) As edgeid;
-- result-
edgeid
------
2
-- Split the new edge --
SELECT topology.ST_NewEdgesSplit('ma_topo', 2, ST_GeomFromText('POINT(227578.5 893913.5)', ←-
26986) ) As newnodeid;
newnodeid
---------
6
See Also
10.6.13 ST_RemoveIsoNode
ST_RemoveIsoNode — Removes an isolated node and returns description of action. If the node is not isolated (is start or end of
an edge), then an exception is thrown.
Synopsis
Description
Removes an isolated node and returns description of action. If the node is not isolated (is start or end of an edge), then an
exception is thrown.
Availability: 1.1
This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X+1.3.3
Examples
See Also
ST_AddIsoNode
10.6.14 ST_RemoveIsoEdge
ST_RemoveIsoEdge — Removes an isolated edge and returns description of action. If the edge is not isolated, then an exception
is thrown.
Synopsis
Description
Removes an isolated edge and returns description of action. If the edge is not isolated, then an exception is thrown.
Availability: 1.1
This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X+1.3.3
Examples
See Also
ST_AddIsoNode
PostGIS 3.3.2 Manual 507 / 902
10.7.1 GetEdgeByPoint
Synopsis
Description
Note
If tolerance = 0, the function uses ST_Intersects otherwise uses ST_DWithin.
Examples
-- get error --
ERROR: Two or more edges found
See Also
10.7.2 GetFaceByPoint
Synopsis
Description
Examples
with1mtol | withnotol
-----------+-----------
1 | 0
-- get error --
ERROR: Two or more faces found
See Also
10.7.3 GetFaceContainingPoint
Synopsis
Description
Note
The function relies on a valid topology, using edge linking and face labeling.
Availability: 3.2.0
PostGIS 3.3.2 Manual 509 / 902
See Also
ST_GetFaceGeometry
10.7.4 GetNodeByPoint
Synopsis
Description
Note
If tolerance = 0, the function uses ST_Intersects otherwise uses ST_DWithin.
Examples
----get error--
ERROR: Two or more nodes found
See Also
10.7.5 GetTopologyID
GetTopologyID — Returns the id of a topology in the topology.topology table given the name of the topology.
PostGIS 3.3.2 Manual 510 / 902
Synopsis
Description
Returns the id of a topology in the topology.topology table given the name of the topology.
Availability: 1.1
Examples
See Also
10.7.6 GetTopologySRID
GetTopologySRID — Returns the SRID of a topology in the topology.topology table given the name of the topology.
Synopsis
Description
Returns the spatial reference id of a topology in the topology.topology table given the name of the topology.
Availability: 2.0.0
Examples
See Also
10.7.7 GetTopologyName
GetTopologyName — Returns the name of a topology (schema) given the id of the topology.
PostGIS 3.3.2 Manual 511 / 902
Synopsis
Description
Returns the topology name (schema) of a topology from the topology.topology table given the topology id of the topology.
Availability: 1.1
Examples
See Also
10.7.8 ST_GetFaceEdges
Synopsis
Description
Returns a set of ordered edges that bound aface. Each output consists of a sequence and edgeid. Sequence numbers start with
value 1.
Enumeration of each ring edges start from the edge with smallest identifier. Order of edges follows a left-hand-rule (bound face
is on the left of each directed edge).
Availability: 2.0
This method implements the SQL/MM specification. SQL-MM 3 Topo-Geo and Topo-Net 3: Routine Details: X.3.5
Examples
See Also
10.7.9 ST_GetFaceGeometry
ST_GetFaceGeometry — Returns the polygon in the given topology with the specified face id.
Synopsis
Description
Returns the polygon in the given topology with the specified face id. Builds the polygon from the edges making up the face.
Availability: 1.1
This method implements the SQL/MM specification. SQL-MM 3 Topo-Geo and Topo-Net 3: Routine Details: X.3.16
Examples
--------------------------------------------------------------------------------
POLYGON((234776.9 899563.7,234896.5 899456.7,234914 899436.4,234946.6 899356.9,
234872.5 899328.7,234891 899285.4,234992.5 899145,234890.6 899069,
234755.2 899255.4,234612.7 899379.4,234776.9 899563.7))
See Also
AddFace
10.7.10 GetRingEdges
GetRingEdges — Returns the ordered set of signed edge identifiers met by walking on an a given edge side.
Synopsis
Description
Returns the ordered set of signed edge identifiers met by walking on an a given edge side. Each output consists of a sequence
and a signed edge id. Sequence numbers start with value 1.
If you pass a positive edge id, the walk starts on the left side of the corresponding edge and follows the edge direction. If you
pass a negative edge id, the walk starts on the right side of it and goes backward.
If max_edges is not null no more than those records are returned by that function. This is meant to be a safety parameter when
dealing with possibly invalid topologies.
Note
This function uses edge ring linking metadata.
Availability: 2.0.0
See Also
ST_GetFaceEdges, GetNodeEdges
10.7.11 GetNodeEdges
Synopsis
Description
Returns an ordered set of edges incident to the given node. Each output consists of a sequence and a signed edge id. Sequence
numbers start with value 1. A positive edge starts at the given node. A negative edge ends into the given node. Closed edges will
appear twice (with both signs). Order is clockwise starting from northbound.
Note
This function computes ordering rather than deriving from metadata and is thus usable to build edge ring linking.
Availability: 2.0
See Also
10.8.1 Polygonize
Synopsis
Description
Registers all faces that can be built out a topology edge primitives.
The target topology is assumed to contain no self-intersecting edges.
Note
Already known faces are recognized, so it is safe to call Polygonize multiple times on the same topology.
Note
This function does not use nor set the next_left_edge and next_right_edge fields of the edge table.
Availability: 2.0.0
See Also
AddFace, ST_Polygonize
10.8.2 AddNode
AddNode — Adds a point node to the node table in the specified topology schema and returns the nodeid of new node. If point
already exists as node, the existing nodeid is returned.
Synopsis
Description
Adds a point node to the node table in the specified topology schema. The AddEdge function automatically adds start and end
points of an edge when called so not necessary to explicitly add nodes of an edge.
If any edge crossing the node is found either an exception is raised or the edge is split, depending on the allowEdgeSplitting
parameter value.
If computeContainingFace is true a newly added node would get the correct containing face computed.
Note
If the apoint geometry already exists as a node, the node is not added but the existing nodeid is returned.
Availability: 2.0.0
PostGIS 3.3.2 Manual 515 / 902
Examples
See Also
AddEdge, CreateTopology
10.8.3 AddEdge
AddEdge — Adds a linestring edge to the edge table and associated start and end points to the point nodes table of the specified
topology schema using the specified linestring geometry and returns the edgeid of the new (or existing) edge.
Synopsis
Description
Adds an edge to the edge table and associated nodes to the nodes table of the specified toponame schema using the specified
linestring geometry and returns the edgeid of the new or existing record. The newly added edge has "universe" face on both sides
and links to itself.
Note
If the aline geometry crosses, overlaps, contains or is contained by an existing linestring edge, then an error is thrown
and the edge is not added.
Note
The geometry of aline must have the same srid as defined for the topology otherwise an invalid spatial reference
sys error will be thrown.
Examples
See Also
10.8.4 AddFace
Synopsis
Description
Note
This function does not use nor set the next_left_edge and next_right_edge fields of the edge table.
The target topology is assumed to be valid (containing no self-intersecting edges). An exception is raised if: The polygon
boundary is not fully defined by existing edges or the polygon overlaps an existing face.
If the apolygon geometry already exists as a face, then: if force_new is false (the default) the face id of the existing face is
returned; if force_new is true a new id will be assigned to the newly registered face.
Note
When a new registration of an existing face is performed (force_new=true), no action will be taken to resolve dangling
references to the existing face in the edge, node an relation tables, nor will the MBR field of the existing face record be
updated. It is up to the caller to deal with that.
Note
The apolygon geometry must have the same srid as defined for the topology otherwise an invalid spatial reference
sys error will be thrown.
PostGIS 3.3.2 Manual 517 / 902
Availability: 2.0.0
Examples
SELECT topology.AddFace('ma_topo',
ST_GeomFromText('POLYGON((234896.5 899456.7,234914 899436.4,234946.6 899356.9,234872.5 ←-
899328.7,
234891 899285.4,234992.5 899145, 234890.6 899069,234755.2 899255.4,
234612.7 899379.4,234776.9 899563.7,234896.5 899456.7))', 26986) ) As faceid;
-- result --
faceid
--------
1
See Also
10.8.5 ST_Simplify
ST_Simplify — Returns a "simplified" geometry version of the given TopoGeometry using the Douglas-Peucker algorithm.
Synopsis
Description
Returns a "simplified" geometry version of the given TopoGeometry using the Douglas-Peucker algorithm on each component
edge.
Note
The returned geometry may be non-simple or non-valid.
Splitting component edges may help retaining simplicity/validity.
See Also
10.8.6 RemoveUnusedPrimitives
RemoveUnusedPrimitives — Removes topology primitives which not needed to define existing TopoGeometry objects.
Synopsis
Description
Finds all primitives (nodes, edges, faces) that are not strictly needed to represent existing TopoGeometry objects and removes
them, maintaining topology validity (edge linking, face labeling) and TopoGeometry space occupation.
No new primitive identifiers are created, but rather existing primitives are expanded to include merged faces (upon removing
edges) or healed edges (upon removing nodes).
Availability: 3.3.0
See Also
ST_ModEdgeHeal, ST_RemEdgeModFace
10.9.1 CreateTopoGeom
CreateTopoGeom — Creates a new topo geometry object from topo element array - tg_type: 1:[multi]point, 2:[multi]line,
3:[multi]poly, 4:collection
Synopsis
Description
Creates a topogeometry object for layer denoted by layer_id and registers it in the relations table in the toponame schema.
tg_type is an integer: 1:[multi]point (punctal), 2:[multi]line (lineal), 3:[multi]poly (areal), 4:collection. layer_id is the
layer id in the topology.layer table.
punctal layers are formed from set of nodes, lineal layers are formed from a set of edges, areal layers are formed from a set of
faces, and collections can be formed from a mixture of nodes, edges, and faces.
Omitting the array of components generates an empty TopoGeometry object.
Availability: 1.1
Create a topogeom in ri_topo schema for layer 2 (our ri_roads), of type (2) LINE, for the first edge (we loaded in ST_CreateTopoGeo).
INSERT INTO ri.ri_roads(road_name, topo) VALUES('Unknown', topology.CreateTopoGeom('ri_topo ←-
',2,2,'{{1,2}}'::topology.topoelementarray);
Lets say we have geometries that should be formed from a collection of faces. We have for example blockgroups table and want
to know the topo geometry of each block group. If our data was perfectly aligned, we could do this:
-- create our topo geometry column --
SELECT topology.AddTopoGeometryColumn(
'topo_boston',
'boston', 'blockgroups', 'topo', 'POLYGON');
-- addtopgeometrycolumn --
1
See Also
10.9.2 toTopoGeom
Synopsis
Description
Examples
new_layer_id
-----------
1
-- summary--
Topology topo_boston_test (5), SRID 2249, precision 0
61 nodes, 87 edges, 35 faces, 15 topogeoms in 1 layers
Layer 1, type Polygonal (3), 15 topogeoms
Deploy: public.nei_topo.topo
See Also
10.9.3 TopoElementArray_Agg
Synopsis
Description
Examples
See Also
TopoElement, TopoElementArray
10.10.1 clearTopoGeom
Synopsis
Description
Clears the content a TopoGeometry turning it into an empty one. Mostly useful in conjunction with toTopoGeom to replace the
shape of existing objects and any dependent object in higher hierarchical levels.
Availability: 2.1
Examples
See Also
toTopoGeom
10.10.2 TopoGeom_addElement
Synopsis
Description
Adds a TopoElement to the definition of a TopoGeometry object. Does not error out if the element is already part of the definition.
Availability: 2.3
PostGIS 3.3.2 Manual 523 / 902
Examples
See Also
TopoGeom_remElement, CreateTopoGeom
10.10.3 TopoGeom_remElement
Synopsis
Description
Examples
See Also
TopoGeom_addElement, CreateTopoGeom
10.10.4 TopoGeom_addTopoGeom
Synopsis
Description
Adds the elements of a TopoGeometry to the definition of another TopoGeometry, possibly changing its cached type (type
attribute) to a collection, if needed to hold all elements in the source object.
The two TopoGeometry objects need be defined against the *same* topology and, if hierarchically defined, need be composed
by elements of the same child layer.
Availability: 3.2
PostGIS 3.3.2 Manual 524 / 902
Examples
See Also
10.10.5 toTopoGeom
Description
Refer to toTopoGeom.
10.11.1 GetTopoGeomElementArray
GetTopoGeomElementArray — Returns a topoelementarray (an array of topoelements) containing the topological ele-
ments and type of the given TopoGeometry (primitive elements).
Synopsis
Description
Returns a TopoElementArray containing the topological elements and type of the given TopoGeometry (primitive elements).
This is similar to GetTopoGeomElements except it returns the elements as an array rather than as a dataset.
tg_id is the topogeometry id of the topogeometry object in the topology in the layer denoted by layer_id in the topology.layer
table.
Availability: 1.1
Examples
See Also
GetTopoGeomElements, TopoElementArray
PostGIS 3.3.2 Manual 525 / 902
10.11.2 GetTopoGeomElements
GetTopoGeomElements — Returns a set of topoelement objects containing the topological element_id,element_type of the
given TopoGeometry (primitive elements).
Synopsis
Description
Returns a set of element_id,element_type (topoelements) for a given topogeometry object in toponame schema.
tg_id is the topogeometry id of the topogeometry object in the topology in the layer denoted by layer_id in the topology.layer
table.
Availability: 2.0.0
Examples
See Also
10.11.3 ST_SRID
Synopsis
Description
Returns the spatial reference identifier for the ST_Geometry as defined in spatial_ref_sys table. Section 4.5
Note
spatial_ref_sys table is a table that catalogs all spatial reference systems known to PostGIS and is used for transforma-
tions from one spatial reference system to another. So verifying you have the right spatial reference system identifier is
important if you plan to ever transform your geometries.
Availability: 3.2.0
Examples
See Also
10.12.1 AsGML
Synopsis
Description
Returns the GML representation of a topogeometry in version GML3 format. If no nsprefix_in is specified then gml is
used. Pass in an empty string for nsprefix to get a non-qualified name space. The precision (default: 15) and options (default 1)
parameters, if given, are passed untouched to the underlying call to ST_AsGML.
The visitedTable parameter, if given, is used for keeping track of the visited Node and Edge elements so to use cross-
references (xlink:xref) rather than duplicating definitions. The table is expected to have (at least) two integer fields: ’ele-
ment_type’ and ’element_id’. The calling user must have both read and write privileges on the given table. For best performance,
an index should be defined on element_type and element_id, in that order. Such index would be created automatically
by adding a unique constraint to the fields. Example:
CREATE TABLE visited (
element_type integer, element_id integer,
unique(element_type, element_id)
);
The idprefix parameter, if given, will be prepended to Edge and Node tag identifiers.
The gmlver parameter, if given, will be passed to the underlying ST_AsGML. Defaults to 3.
Availability: 2.0.0
Examples
-- rdgml--
<gml:TopoCurve>
<gml:directedEdge>
PostGIS 3.3.2 Manual 527 / 902
<gml:Edge gml:id="E1">
<gml:directedNode orientation="-">
<gml:Node gml:id="N1"/>
</gml:directedNode>
<gml:directedNode></gml:directedNode>
<gml:curveProperty>
<gml:Curve srsName="urn:ogc:def:crs:EPSG::3438">
<gml:segments>
<gml:LineStringSegment>
<gml:posList srsDimension="2">384744 236928 384750 236923 ←-
384769 236911 384799 236895 384811 236890
384833 236884 384844 236882 384866 236881 384879 236883 384954 ←-
236898 385087 236932 385117 236938
385167 236938 385203 236941 385224 236946 385233 236950 385241 ←-
236956 385254 236971
385260 236979 385268 236999 385273 237018 385273 237037 385271 ←-
237047 385267 237057 385225 237125
385210 237144 385192 237161 385167 237192 385162 237202 385159 ←-
237214 385159 237227 385162 237241
385166 237256 385196 237324 385209 237345 385234 237375 385237 ←-
237383 385238 237399 385236 237407
385227 237419 385213 237430 385193 237439 385174 237451 385170 ←-
237455 385169 237460 385171 237475
385181 237503 385190 237521 385200 237533 385206 237538 385213 ←-
237541 385221 237542 385235 237540 385242 237541
385249 237544 385260 237555 385270 237570 385289 237584 385292 ←-
237589 385291 237596 385284 237630</gml:posList>
</gml:LineStringSegment>
</gml:segments>
</gml:Curve>
</gml:curveProperty>
</gml:Edge>
</gml:directedEdge>
</gml:TopoCurve>
-- rdgml--
<TopoCurve>
<directedEdge>
<Edge id="E1">
<directedNode orientation="-">
<Node id="N1"/>
</directedNode>
<directedNode></directedNode>
<curveProperty>
<Curve srsName="urn:ogc:def:crs:EPSG::3438">
<segments>
<LineStringSegment>
<posList srsDimension="2">384744 236928 384750 236923 384769 ←-
236911 384799 236895 384811 236890
384833 236884 384844 236882 384866 236881 384879 236883 384954 ←-
236898 385087 236932 385117 236938
385167 236938 385203 236941 385224 236946 385233 236950 385241 ←-
236956 385254 236971
385260 236979 385268 236999 385273 237018 385273 237037 385271 ←-
237047 385267 237057 385225 237125
385210 237144 385192 237161 385167 237192 385162 237202 385159 ←-
PostGIS 3.3.2 Manual 528 / 902
See Also
CreateTopoGeom, ST_CreateTopoGeo
10.12.2 AsTopoJSON
Synopsis
Description
Returns the TopoJSON representation of a topogeometry. If edgeMapTable is not null, it will be used as a lookup/storage
mapping of edge identifiers to arc indices. This is to be able to allow for a compact "arcs" array in the final document.
The table, if given, is expected to have an "arc_id" field of type "serial" and an "edge_id" of type integer; the code will query the
table for "edge_id" so it is recommended to add an index on that field.
Note
Arc indices in the TopoJSON output are 0-based but they are 1-based in the "edgeMapTable" table.
A full TopoJSON document will be need to contain, in addition to the snippets returned by this function, the actual arcs plus
some headers. See the TopoJSON specification.
Availability: 2.1.0
Enhanced: 2.2.1 added support for puntal inputs
See Also
ST_AsGeoJSON
PostGIS 3.3.2 Manual 529 / 902
Examples
-- header
SELECT '{ "type": "Topology", "transform": { "scale": [1,1], "translate": [0,0] }, "objects ←-
": {'
-- objects
UNION ALL SELECT '"' || feature_name || '": ' || AsTopoJSON(feature, 'edgemap')
FROM features.big_parcels WHERE feature_name = 'P3P4';
-- arcs
WITH edges AS (
SELECT m.arc_id, e.geom FROM edgemap m, city_data.edge e
WHERE e.edge_id = m.edge_id
), points AS (
SELECT arc_id, (st_dumppoints(geom)).* FROM edges
), compare AS (
SELECT p2.arc_id,
CASE WHEN p1.path IS NULL THEN p2.geom
ELSE ST_Translate(p2.geom, -ST_X(p1.geom), -ST_Y(p1.geom))
END AS geom
FROM points p2 LEFT OUTER JOIN points p1
ON ( p1.arc_id = p2.arc_id AND p2.path[1] = p1.path[1]+1 )
ORDER BY arc_id, p2.path
), arcsdump AS (
SELECT arc_id, (regexp_matches( ST_AsGeoJSON(geom), '\[.*\]'))[1] as t
FROM compare
), arcs AS (
SELECT arc_id, '[' || array_to_string(array_agg(t), ',') || ']' as a FROM arcsdump
GROUP BY arc_id
ORDER BY arc_id
)
SELECT '}, "arcs": [' UNION ALL
SELECT array_to_string(array_agg(a), E',\n') from arcs
-- footer
UNION ALL SELECT ']}'::text as t;
-- Result:
{ "type": "Topology", "transform": { "scale": [1,1], "translate": [0,0] }, "objects": {
"P3P4": { "type": "MultiPolygon", "arcs": [[[-1]],[[6,5,-5,-4,-3,1]]]}
}, "arcs": [
[[25,30],[6,0],[0,10],[-14,0],[0,-10],[8,0]],
[[35,6],[0,8]],
[[35,6],[12,0]],
[[47,6],[0,8]],
[[47,14],[0,8]],
[[35,22],[12,0]],
[[35,14],[0,8]]
]}
10.13.1 Equals
Equals — Returns true if two topogeometries are composed of the same topology primitives.
PostGIS 3.3.2 Manual 530 / 902
Synopsis
Description
Returns true if two topogeometries are composed of the same topology primitives: faces, edges, nodes.
Note
This function not supported for topogeometries that are geometry collections. It also can not compare topogeometries
from different topologies.
Availability: 1.1.0
Examples
See Also
GetTopoGeomElements, ST_Equals
10.13.2 Intersects
Intersects — Returns true if any pair of primitives from the two topogeometries intersect.
Synopsis
Description
Returns true if any pair of primitives from the two topogeometries intersect.
Note
This function not supported for topogeometries that are geometry collections. It also can not compare topogeometries
from different topologies. Also not currently supported for hierarchichal topogeometries (topogeometries composed of
other topogeometries).
Availability: 1.1.0
Examples
PostGIS 3.3.2 Manual 531 / 902
See Also
ST_Intersects
Once you have created topologies, and maybe associated topological layers, you might want to export them into a file-based
format for backup or transfer into another database.
Using the standard dump/restore tools of PostgreSQL is problematic because topologies are composed by a set of tables (4 for
primitives, an arbitrary number for layers) and records in metadata tables (topology.topology and topology.layer). Additionally,
topology identifiers are not univoque across databases so that parameter of your topology will need to be changes upon restoring
it.
In order to simplify export/restore of topologies a pair of executables are provided: pgtopo_export and pgtopo_import.
Example usage:
pgtopo_export dev_db topo1 | pgtopo_import topo1 | psql staging_db
The pgtopo_export script takes the name of a database and a topology and outputs a dump file which can be used to import
the topology (and associated layers) into a new database.
By default pgtopo_export writes the dump file to the standard output so that it can be piped to pgtopo_import or
redirected to a file (refusing to write to terminal). You can optionally specify an output filename with the -f commandline
switch.
By default pgtopo_export includes a dump of all layers defined against the given topology. This may be more data than you
need, or may be non-working (in case your layer tables have complex dependencies) in which case you can request skipping the
layers with the --skip-layers switch and deal with those separately.
Invoking pgtopo_export with the --help (or -h for short) switch will always print short usage string.
The dump file format is a compressed tar archive of a pgtopo_export directory containing at least a pgtopo_dump_
version file with format version info. As of version 1 the directory contains tab-delimited CSV files with data of the topol-
ogy primitive tables (node, edge_data, face, relation), of the topology and layer records associated with it, and optionall (if
--skip-layers is not given) a custom-format PostgreSQL dump of tables reported as being layers of the given topology.
The pgtopo_import script takes a pgtopo_export format topology dump and a name to give to the topology to be created
and outputs an SQL script reconstructing the topology and associated layers.
The generated SQL file will contain statements that create a topology with the given name, load primitive data in it, restores and
registers all topology layers by properly linking all TopoGeometry values to their correct topology.
By default pgtopo_import reads the dump from the standard input so that it can be used in conjuction with pgtopo_
export in a pipeline. You can optionally specify an input filename with the -f commandline switch.
By default pgtopo_import includes in the output SQL file the code to restore all layers found in the dump.
This may be unwanted or non-working in case your target database already have tables with the same name as the ones in the
dump. In that case you can request skipping the layers with the --skip-layers switch and deal with those separately (or
later).
SQL to only load and link layers to a named topology can be generated using the --only-layers switch. This can be useful
to load layers AFTER resolving the naming conflicts or to link layers to a different topology (say a spatially-simplified version
of the starting topology).
PostGIS 3.3.2 Manual 532 / 902
Chapter 11
For most use cases, you will create PostGIS rasters by loading existing raster files using the packaged raster2pgsql raster
loader.
The raster2pgsql is a raster loader executable that loads GDAL supported raster formats into sql suitable for loading into a
PostGIS raster table. It is capable of loading folders of raster files as well as creating overviews of rasters.
Since the raster2pgsql is compiled as part of PostGIS most often (unless you compile your own GDAL library), the raster types
supported by the executable will be the same as those compiled in the GDAL dependency library. To get a list of raster types
your particular raster2pgsql supports use the -G switch. These should be the same as those provided by your PostGIS install
documented here ST_GDALDrivers if you are using the same GDAL library for both.
Note
The older version of this tool was a python script. The executable has replaced the python script. If you still find the
need for the Python script Examples of the python one can be found at GDAL PostGIS Raster Driver Usage. Please
note that the raster2pgsql python script may not work with future versions of PostGIS raster and is no longer supported.
Note
When creating overviews of a specific factor from a set of rasters that are aligned, it is possible for the overviews to not
align. Visit http://trac.osgeo.org/postgis/ticket/1764 for an example where the overviews do not align.
EXAMPLE USAGE:
raster2pgsql raster_options_go_here raster_file someschema.sometable > out.sql
-? Display help screen. Help will also display if you don’t pass in any arguments.
-G Print the supported raster formats.
(c|a|d|p) These are mutually exclusive options:
PostGIS 3.3.2 Manual 533 / 902
-c Create new table and populate it with raster(s), this is the default mode
-a Append raster(s) to an existing table.
-d Drop table, create new one and populate it with raster(s)
-p Prepare mode, only create the table.
Raster processing: Applying constraints for proper registering in raster catalogs
-C Apply raster constraints -- srid, pixelsize etc. to ensure raster is properly registered in raster_columns view.
-x Disable setting the max extent constraint. Only applied if -C flag is also used.
-r Set the constraints (spatially unique and coverage tile) for regular blocking. Only applied if -C flag is also used.
Raster processing: Optional parameters used to manipulate input raster dataset
-s <SRID> Assign output raster with specified SRID. If not provided or is zero, raster’s metadata will be checked to
determine an appropriate SRID.
-b BAND Index (1-based) of band to extract from raster. For more than one band index, separate with comma (,). If
unspecified, all bands of raster will be extracted.
-t TILE_SIZE Cut raster into tiles to be inserted one per table row. TILE_SIZE is expressed as WIDTHxHEIGHT or
set to the value "auto" to allow the loader to compute an appropriate tile size using the first raster and applied to all
rasters.
-P Pad right-most and bottom-most tiles to guarantee that all tiles have the same width and height.
-R, --register Register the raster as a filesystem (out-db) raster.
Only the metadata of the raster and path location to the raster is stored in the database (not the pixels).
-l OVERVIEW_FACTOR Create overview of the raster. For more than one factor, separate with comma(,). Overview
table name follows the pattern o_overview factor_table, where overview factor is a placeholder for
numerical overview factor and table is replaced with the base table name. Created overview is stored in the
database and is not affected by -R. Note that your generated sql file will contain both the main table and overview
tables.
-N NODATA NODATA value to use on bands without a NODATA value.
-V version Specify version of output format. Default is 0. Only 0 is supported at this time.
PostGIS 3.3.2 Manual 534 / 902
An example session using the loader to create an input file and uploading it chunked in 100x100 tiles might look like this:
Note
You can leave the schema name out e.g demelevation instead of public.demelevation and the raster table
will be created in the default schema of the database or user
A conversion and upload can be done all in one step using UNIX pipes:
raster2pgsql -s 4326 -I -C -M *.tif -F -t 100x100 public.demelevation | psql -d gisdb
Load rasters Massachusetts state plane meters aerial tiles into a schema called aerial and create a full view, 2 and 4 level
overview tables, use copy mode for inserting (no intermediary file just straight to db), and -e don’t force everything in a transaction
(good if you want to see data in tables right away without waiting). Break up the rasters into 128x128 pixel tiles and apply raster
constraints. Use copy mode instead of table insert. (-F) Include a field called filename to hold the name of the file the tiles were
cut from.
raster2pgsql -I -C -e -Y -F -s 26986 -t 128x128 -l 2,4 bostonaerials2008/*.jpg aerials. ←-
boston | psql -U postgres -d gisdb -h localhost -p 5432
On many occasions, you’ll want to create rasters and raster tables right in the database. There are a plethora of functions to do
that. The general steps to follow.
1. Create a table with a raster column to hold the new raster records which can be accomplished with:
CREATE TABLE myrasters(rid serial primary key, rast raster);
2. There are many functions to help with that goal. If you are creating rasters not as a derivative of other rasters, you will
want to start with: ST_MakeEmptyRaster, followed by ST_AddBand
You can also create rasters from geometries. To achieve that you’ll want to use ST_AsRaster perhaps accompanied with
other functions such as ST_Union or ST_MapAlgebraFct or any of the family of other map algebra functions.
There are even many more options for creating new raster tables from existing tables. For example you can create a raster
table in a different projection from an existing one using ST_Transform
3. Once you are done populating your table initially, you’ll want to create a spatial index on the raster column with something
like:
CREATE INDEX myrasters_rast_st_convexhull_idx ON myrasters USING gist( ST_ConvexHull( ←-
rast) );
Note the use of ST_ConvexHull since most raster operators are based on the convex hull of the rasters.
Note
Pre-2.0 versions of PostGIS raster were based on the envelop rather than the convex hull. For the spatial indexes
to work properly you’ll need to drop those and replace with convex hull based index.
The raster2pgsql tool uses GDAL to access raster data, and can take advantage of a key GDAL feature: the ability to read
from rasters that are stored remotely in cloud "object stores" (e.g. AWS S3, Google Cloud Storage).
Efficient use of cloud stored rasters requires the use of a "cloud optimized" format. The most well-known and widely used is
the "cloud optimized GeoTIFF" format. Using a non-cloud format, like a JPEG, or an un-tiled TIFF will result in very poor
performance, as the system will have to download the entire raster each time it needs to access a subset.
First, load your raster into the cloud storage of your choice. Once it is loaded, you will have a URI to access it with, either an
"http" URI, or sometimes a URI specific to the service. (e.g., "s3://bucket/object"). To access non-public buckets, you will need
to supply GDAL config options to authenticate your connection. Note that this command is reading from the cloud raster and
writing to the database.
AWS_ACCESS_KEY_ID=xxxxxxxxxxxxxxxxxxxx \
AWS_SECRET_ACCESS_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx \
raster2pgsql \
-s 990000 \
-t 256x256 \
PostGIS 3.3.2 Manual 537 / 902
-I \
-R \
/vsis3/your.bucket.com/your_file.tif \
your_table \
| psql your_db
Once the table is loaded, you need to give the database permission to read from remote rasters, by setting two permissions,
postgis.enable_outdb_rasters and postgis.gdal_enabled_drivers.
SET postgis.enable_outdb_rasters = true;
SET postgis.gdal_enabled_drivers TO 'ENABLE_ALL';
To make the changes sticky, set them directly on your database. You will need to re-connect to experience the new settings.
ALTER DATABASE your_db SET postgis.enable_outdb_rasters = true;
ALTER DATABASE your_db SET postgis.gdal_enabled_drivers TO 'ENABLE_ALL';
For non-public rasters, you may have to provide access keys to read from the cloud rasters. The same keys you used to write
the raster2pgsql call can be set for use inside the database, with the postgis.gdal_config_options configuration. Note that
multiple options can be set by space-separating the key=value pairs.
SET postgis.gdal_vsi_options = 'AWS_ACCESS_KEY_ID=xxxxxxxxxxxxxxxxxxxx
AWS_SECRET_ACCESS_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
Once you have the data loaded and permissions set you can interact with the raster table like any other raster table, using the
same functions. The database will handle all the mechanics of connecting to the cloud data when it needs to read pixel data.
There are two raster catalog views that come packaged with PostGIS. Both views utilize information embedded in the constraints
of the raster tables. As a result the catalog views are always consistent with the raster data in the tables since the constraints are
enforced.
1. raster_columns this view catalogs all the raster table columns in your database.
2. raster_overviews this view catalogs all the raster table columns in your database that serve as overviews for a finer
grained table. Tables of this type are generated when you use the -l switch during load.
The raster_columns is a catalog of all raster table columns in your database that are of type raster. It is a view utilizing the
constraints on the tables so the information is always consistent even if you restore one raster table from a backup of another
database. The following columns exist in the raster_columns catalog.
If you created your tables not with the loader or forgot to specify the -C flag during load, you can enforce the constraints after
the fact using AddRasterConstraints so that the raster_columns catalog registers the common information about your raster
tiles.
• r_table_catalog The database the table is in. This will always read the current database.
• r_table_schema The database schema the raster table belongs to.
• srid The spatial reference identifier of the raster. Should be an entry in the Section 4.5.
• scale_x The scaling between geometric spatial coordinates and pixel. This is only available if all tiles in the raster column
have the same scale_x and this constraint is applied. Refer to ST_ScaleX for more details.
• scale_y The scaling between geometric spatial coordinates and pixel. This is only available if all tiles in the raster column
have the same scale_y and the scale_y constraint is applied. Refer to ST_ScaleY for more details.
• blocksize_x The width (number of pixels across) of each raster tile . Refer to ST_Width for more details.
• blocksize_y The width (number of pixels down) of each raster tile . Refer to ST_Height for more details.
• same_alignment A boolean that is true if all the raster tiles have the same alignment . Refer to ST_SameAlignment for
more details.
• regular_blocking If the raster column has the spatially unique and coverage tile constraints, the value with be TRUE.
Otherwise, it will be FALSE.
• num_bands The number of bands in each tile of your raster set. This is the same information as what is provided by
ST_NumBands
• pixel_types An array defining the pixel type for each band. You will have the same number of elements in this array as
you have number of bands. The pixel_types are one of the following defined in ST_BandPixelType.
• nodata_values An array of double precision numbers denoting the nodata_value for each band. You will have the
same number of elements in this array as you have number of bands. These numbers define the pixel value for each band that
should be ignored for most operations. This is similar information provided by ST_BandNoDataValue.
• out_db An array of boolean flags indicating if the raster bands data is maintained outside the database. You will have the
same number of elements in this array as you have number of bands.
• extent This is the extent of all the raster rows in your raster set. If you plan to load more data that will change the extent of the
set, you’ll want to run the DropRasterConstraints function before load and then reapply constraints with AddRasterConstraints
after load.
• spatial_index A boolean that is true if raster column has a spatial index.
raster_overviews catalogs information about raster table columns used for overviews and additional information about
them that is useful to know when utilizing overviews. Overview tables are cataloged in both raster_columns and raster_overvi
because they are rasters in their own right but also serve an additional special purpose of being a lower resolution caricature of a
higher resolution table. These are generated along-side the main raster table when you use the -l switch in raster loading or can
be generated manually using AddOverviewConstraints.
Overview tables contain the same constraints as other raster tables as well as additional informational only constraints specific to
overviews.
Note
The information in raster_overviews does not duplicate the information in raster_columns. If you need
the information about an overview table present in raster_columns you can join the raster_overviews and
raster_columns together to get the full set of information you need.
1. Low resolution representation of the core tables commonly used for fast mapping zoom-out.
2. Computations are generally faster to do on them than their higher resolution parents because there are fewer records and
each pixel covers more territory. Though the computations are not as accurate as the high-res tables they support, they can
be sufficient in many rule-of-thumb computations.
PostGIS 3.3.2 Manual 539 / 902
• o_table_catalog The database the overview table is in. This will always read the current database.
• o_table_schema The database schema the overview raster table belongs to.
• o_table_name raster overview table name
• o_raster_column the raster column in the overview table.
• r_table_catalog The database the raster table that this overview services is in. This will always read the current database.
• r_table_schema The database schema the raster table that this overview services belongs to.
• r_table_name raster table that this overview services.
• r_raster_column the raster column that this overview column services.
• overview_factor - this is the pyramid level of the overview table. The higher the number the lower the resolution of
the table. raster2pgsql if given a folder of images, will compute overview of each image file and load separately. Level 1
is assumed and always the original file. Level 2 is will have each tile represent 4 of the original. So for example if you
have a folder of 5000x5000 pixel image files that you chose to chunk 125x125, for each image file your base table will have
(5000*5000)/(125*125) records = 1600, your (l=2) o_2 table will have ceiling(1600/Power(2,2)) = 400 rows, your (l=3) o_3
will have ceiling(1600/Power(2,3) ) = 200 rows. If your pixels aren’t divisible by the size of your tiles, you’ll get some scrap
tiles (tiles not completely filled). Note that each overview tile generated by raster2pgsql has the same number of pixels as its
parent, but is of a lower resolution where each pixel of it represents (Power(2,overview_factor) pixels of the original).
The fact that PostGIS raster provides you with SQL functions to render rasters in known image formats gives you a lot of options
for rendering them. For example you can use OpenOffice / LibreOffice for rendering as demonstrated in Rendering PostGIS
Raster graphics with LibreOffice Base Reports. In addition you can use a wide variety of languages as demonstrated in this
section.
11.3.1 PHP Example Outputting using ST_AsPNG in concert with other raster functions
In this section, we’ll demonstrate how to use the PHP PostgreSQL driver and the ST_AsGDALRaster family of functions to
output band 1,2,3 of a raster to a PHP request stream that can then be embedded in an img src html tag.
The sample query demonstrates how to combine a whole bunch of raster functions together to grab all tiles that intersect a
particular wgs 84 bounding box and then unions with ST_Union the intersecting tiles together returning all bands, transforms to
user specified projection using ST_Transform, and then outputs the results as a png using ST_AsPNG.
You would call the below using
http://mywebserver/test_raster.php?srid=2249
/** The set bytea_output may be needed for PostgreSQL 9.0+, but not for 8.4 **/
$sql = "set bytea_output='escape';
SELECT ST_AsPNG(ST_Transform(
ST_AddBand(ST_Union(rast,1), ARRAY[ST_Union(rast,2),ST_Union(rast,3)])
,$input_srid) ) As new_rast
FROM aerials.boston
WHERE
ST_Intersects(rast, ST_Transform(ST_MakeEnvelope(-71.1217, 42.227, -71.1210, ←-
42.218,4326),26986) )";
$result = pg_query($sql);
$row = pg_fetch_row($result);
pg_free_result($result);
if ($row === false) return;
echo pg_unescape_bytea($row[0]);
?>
11.3.2 ASP.NET C# Example Outputting using ST_AsPNG in concert with other raster functions
In this section, we’ll demonstrate how to use Npgsql PostgreSQL .NET driver and the ST_AsGDALRaster family of functions
to output band 1,2,3 of a raster to a PHP request stream that can then be embedded in an img src html tag.
You will need the npgsql .NET PostgreSQL driver for this exercise which you can get the latest of from http://npgsql.projects.postgresql.o
. Just download the latest and drop into your ASP.NET bin folder and you’ll be good to go.
The sample query demonstrates how to combine a whole bunch of raster functions together to grab all tiles that intersect a
particular wgs 84 bounding box and then unions with ST_Union the intersecting tiles together returning all bands, transforms to
user specified projection using ST_Transform, and then outputs the results as a png using ST_AsPNG.
This is same example as Section 11.3.1 except implemented in C#.
You would call the below using
http://mywebserver/TestRaster.ashx?srid=2249
context.Response.ContentType = "image/png";
context.Response.BinaryWrite(GetResults(context));
if (context.Request["srid"] != null)
{
input_srid = Convert.ToInt32(context.Request["srid"]);
}
sql = @"SELECT ST_AsPNG(
ST_Transform(
ST_AddBand(
ST_Union(rast,1), ARRAY[ST_Union(rast,2),ST_Union(rast,3)])
,:input_srid) ) As new_rast
FROM aerials.boston
WHERE
ST_Intersects(rast,
ST_Transform(ST_MakeEnvelope(-71.1217, 42.227, ←-
-71.1210, 42.218,4326),26986) )";
command = new NpgsqlCommand(sql, conn);
command.Parameters.Add(new NpgsqlParameter("input_srid", input_srid));
}
catch (Exception ex)
{
result = null;
context.Response.Write(ex.Message.Trim());
}
return result;
}
}
11.3.3 Java console app that outputs raster query as Image file
This is a simple java console app that takes a query that returns one image and outputs to specified file.
You can download the latest PostgreSQL JDBC drivers from http://jdbc.postgresql.org/download.html
You can compile the following code using a command something like:
set env CLASSPATH .:..\postgresql-9.0-801.jdbc4.jar
javac SaveQueryImage.java
jar cfm SaveQueryImage.jar Manifest.txt *.class
-- Manifest.txt --
Class-Path: postgresql-9.0-801.jdbc4.jar
Main-Class: SaveQueryImage
try {
//java.sql.DriverManager.registerDriver (new org.postgresql.Driver());
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException cnfe) {
System.out.println("Couldn't find the driver!");
cnfe.printStackTrace();
System.exit(1);
}
try {
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mydb","myuser ←-
", "mypwd");
conn.setAutoCommit(false);
ResultSet rs = sGetImg.executeQuery();
FileOutputStream fout;
try
{
rs.next();
/** Output to file name requested by user **/
fout = new FileOutputStream(new File(argv[1]) );
fout.write(rs.getBytes(1));
fout.close();
}
catch(Exception e)
{
System.out.println("Can't create file");
e.printStackTrace();
}
rs.close();
sGetImg.close();
conn.close();
}
catch (SQLException se) {
System.out.println("Couldn't connect: print out a stack trace and exit.");
se.printStackTrace();
System.exit(1);
}
}
PostGIS 3.3.2 Manual 543 / 902
This is a plpython stored function that creates a file in the server directory for each record. Requires you have plpython installed.
Should work fine with both plpythonu and plpython3u.
CREATE OR REPLACE FUNCTION write_file (param_bytes bytea, param_filepath text)
RETURNS text
AS $$
f = open(param_filepath, 'wb+')
f.write(param_bytes)
return param_filepath
$$ LANGUAGE plpythonu;
write_file
---------------------
C:/temp/slices1.png
C:/temp/slices2.png
C:/temp/slices3.png
C:/temp/slices4.png
C:/temp/slices5.png
Sadly PSQL doesn’t have easy to use built-in functionality for outputting binaries. This is a bit of a hack that piggy backs on
PostgreSQL somewhat legacy large object support. To use first launch your psql commandline connected to your database.
Unlike the python approach, this approach creates the file on your local computer.
SELECT oid, lowrite(lo_open(oid, 131072), png) As num_bytes
FROM
( VALUES (lo_create(0),
ST_AsPNG( (SELECT rast FROM aerials.boston WHERE rid=1) )
) ) As v(oid,png);
-- you'll get an output something like --
oid | num_bytes
---------+-----------
2630819 | 74860
-- next note the oid and do this replacing the c:/test.png to file path location
-- on your local computer
\lo_export 2630819 'C:/temp/aerial_samp.png'
Chapter 12
Raster Reference
The functions given below are the ones which a user of PostGIS Raster is likely to need and which are currently available in
PostGIS Raster. There are other functions which are required support functions to the raster objects which are not of use to a
general user.
raster is a new PostGIS type for storing and analyzing raster data.
For loading rasters from raster files please refer to Section 11.1
For the examples in this reference we will be using a raster table of dummy rasters - Formed with the following code
CREATE TABLE dummy_rast(rid integer, rast raster);
INSERT INTO dummy_rast(rid, rast)
VALUES (1,
('01' -- little endian (uint8 ndr)
||
'0000' -- version (uint16 0)
||
'0000' -- nBands (uint16 0)
||
'0000000000000040' -- scaleX (float64 2)
||
'0000000000000840' -- scaleY (float64 3)
||
'000000000000E03F' -- ipX (float64 0.5)
||
'000000000000E03F' -- ipY (float64 0.5)
||
'0000000000000000' -- skewX (float64 0)
||
'0000000000000000' -- skewY (float64 0)
||
'00000000' -- SRID (int32 0)
||
'0A00' -- width (uint16 10)
||
'1400' -- height (uint16 20)
)::raster
),
-- Raster: 5 x 5 pixels, 3 bands, PT_8BUI pixel type, NODATA = 0
(2, ('01000003009A9999999999A93F9A9999999999A9BF000000E02B274A' ||
'41000000007719564100000000000000000000000000000000 ←-
FFFFFFFF050005000400FDFEFDFEFEFDFEFEFDF9FAFEF' ||
' ←-
EFCF9FBFDFEFEFDFCFAFEFEFE04004E627AADD16076B4F9FE6370A9F5FE59637AB0E54F58617087040046566487A1506C
')::raster);
PostGIS 3.3.2 Manual 545 / 902
12.1.1 geomval
geomval — A spatial datatype with two fields - geom (holding a geometry object) and val (holding a double precision pixel value
from a raster band).
Description
geomval is a compound data type consisting of a geometry object referenced by the .geom field and val, a double precision value
that represents the pixel value at a particular geometric location in a raster band. It is used by the ST_DumpAsPolygon and
Raster intersection family of functions as an output type to explode a raster band into geometry polygons.
See Also
Section 15.6
12.1.2 addbandarg
addbandarg — A composite type used as input into the ST_AddBand function defining the attributes and initial value of the new
band.
Description
A composite type used as input into the ST_AddBand function defining the attributes and initial value of the new band.
index integer 1-based value indicating the position where the new band will be added amongst the raster’s bands. If NULL,
the new band will be added at the end of the raster’s bands.
pixeltype text Pixel type of the new band. One of defined pixel types as described in ST_BandPixelType.
initialvalue double precision Initial value that all pixels of new band will be set to.
nodataval double precision NODATA value of the new band. If NULL, the new band will not have a NODATA value
assigned.
See Also
ST_AddBand
12.1.3 rastbandarg
rastbandarg — A composite type for use when needing to express a raster and a band index of that raster.
Description
A composite type for use when needing to express a raster and a band index of that raster.
See Also
12.1.4 raster
Description
raster is a spatial data type used to represent raster data such as those imported from JPEGs, TIFFs, PNGs, digital elevation
models. Each raster has 1 or more bands each having a set of pixel values. Rasters can be georeferenced.
Note
Requires PostGIS be compiled with GDAL support. Currently rasters can be implicitly converted to geometry type, but
the conversion returns the ST_ConvexHull of the raster. This auto casting may be removed in the near future so don’t
rely on it.
Casting Behavior
This section lists the automatic as well as explicit casts allowed for this data type
Cast To Behavior
geometry automatic
See Also
Chapter 12
12.1.5 reclassarg
reclassarg — A composite type used as input into the ST_Reclass function defining the behavior of reclassification.
Description
A composite type used as input into the ST_Reclass function defining the behavior of reclassification.
reclassexpr text range expression consisting of comma delimited range:map_range mappings. : to define mapping that
defines how to map old band values to new band values. ( means >, ) means less than, ] < or equal, [ means > or equal
1. [a-b] = a <= x <= b
nodataval double precision Value to treat as no data. For image outputs that support transparency, these will be blank.
PostGIS 3.3.2 Manual 547 / 902
See Also
ST_Reclass
12.1.6 summarystats
Description
See Also
ST_SummaryStats, ST_SummaryStatsAgg
12.1.7 unionarg
unionarg — A composite type used as input into the ST_Union function defining the bands to be processed and behavior of the
UNION operation.
Description
A composite type used as input into the ST_Union function defining the bands to be processed and behavior of the UNION
operation.
nband integer 1-based value indicating the band of each input raster to be processed.
uniontype text Type of UNION operation. One of defined types as described in ST_Union.
See Also
ST_Union
PostGIS 3.3.2 Manual 548 / 902
12.2.1 AddRasterConstraints
AddRasterConstraints — Adds raster constraints to a loaded raster table for a specific column that constrains spatial ref, scaling,
blocksize, alignment, bands, band type and a flag to denote if raster column is regularly blocked. The table must be loaded with
data for the constraints to be inferred. Returns true if the constraint setting was accomplished and issues a notice otherwise.
Synopsis
boolean AddRasterConstraints(name rasttable, name rastcolumn, boolean srid=true, boolean scale_x=true, boolean scale_y=true,
boolean blocksize_x=true, boolean blocksize_y=true, boolean same_alignment=true, boolean regular_blocking=false, boolean
num_bands=true , boolean pixel_types=true , boolean nodata_values=true , boolean out_db=true , boolean extent=true );
boolean AddRasterConstraints(name rasttable, name rastcolumn, text[] VARIADIC constraints);
boolean AddRasterConstraints(name rastschema, name rasttable, name rastcolumn, text[] VARIADIC constraints);
boolean AddRasterConstraints(name rastschema, name rasttable, name rastcolumn, boolean srid=true, boolean scale_x=true,
boolean scale_y=true, boolean blocksize_x=true, boolean blocksize_y=true, boolean same_alignment=true, boolean regular_blocking=fa
boolean num_bands=true, boolean pixel_types=true, boolean nodata_values=true , boolean out_db=true , boolean extent=true );
Description
Generates constraints on a raster column that are used to display information in the raster_columns raster catalog. The
rastschema is the name of the table schema the table resides in. The srid must be an integer value reference to an entry in
the SPATIAL_REF_SYS table.
raster2pgsql loader uses this function to register raster tables
Valid constraint names to pass in: refer to Section 11.2.1 for more details.
• pixel_types reads array of pixel types for each band ensure all band n have same pixel type
• regular_blocking sets spatially unique (no two rasters can be spatially the same) and coverage tile (raster is aligned to a
coverage) constraints
• same_alignment ensures they all have same alignment meaning any two tiles you compare will return true for. Refer to
ST_SameAlignment.
• srid ensures all have same srid
• More -- any listed as inputs into the above functions
Note
This function infers the constraints from the data already present in the table. As such for it to work, you must create
the raster column first and then load it with data.
PostGIS 3.3.2 Manual 549 / 902
Note
If you need to load more data in your tables after you have already applied constraints, you may want to run the
DropRasterConstraints if the extent of your data has changed.
Availability: 2.0.0
See Also
12.2.2 DropRasterConstraints
DropRasterConstraints — Drops PostGIS raster constraints that refer to a raster table column. Useful if you need to reload data
or update your raster column data.
PostGIS 3.3.2 Manual 550 / 902
Synopsis
boolean DropRasterConstraints(name rasttable, name rastcolumn, boolean srid, boolean scale_x, boolean scale_y, boolean
blocksize_x, boolean blocksize_y, boolean same_alignment, boolean regular_blocking, boolean num_bands=true, boolean pixel_types=t
boolean nodata_values=true, boolean out_db=true , boolean extent=true);
boolean DropRasterConstraints(name rastschema, name rasttable, name rastcolumn, boolean srid=true, boolean scale_x=true,
boolean scale_y=true, boolean blocksize_x=true, boolean blocksize_y=true, boolean same_alignment=true, boolean regular_blocking=fa
boolean num_bands=true, boolean pixel_types=true, boolean nodata_values=true, boolean out_db=true , boolean extent=true);
boolean DropRasterConstraints(name rastschema, name rasttable, name rastcolumn, text[] constraints);
Description
Drops PostGIS raster constraints that refer to a raster table column that were added by AddRasterConstraints. Useful if you need
to load more data or update your raster column data. You do not need to do this if you want to get rid of a raster table or a raster
column.
To drop a raster table use the standard
DROP TABLE mytable
To drop just a raster column and leave the rest of the table, use standard SQL
ALTER TABLE mytable DROP COLUMN rast
the table will disappear from the raster_columns catalog if the column or table is dropped. However if only the constraints
are dropped, the raster column will still be listed in the raster_columns catalog, but there will be no other information about
it aside from the column name and table.
Availability: 2.0.0
Examples
0 | | | | | | |
See Also
AddRasterConstraints
12.2.3 AddOverviewConstraints
Synopsis
boolean AddOverviewConstraints(name ovschema, name ovtable, name ovcolumn, name refschema, name reftable, name
refcolumn, int ovfactor);
boolean AddOverviewConstraints(name ovtable, name ovcolumn, name reftable, name refcolumn, int ovfactor);
Description
Adds constraints on a raster column that are used to display information in the raster_overviews raster catalog.
The ovfactor parameter represents the scale multiplier in the overview column: higher overview factors have lower resolution.
When the ovschema and refschema parameters are omitted, the first table found scanning the search_path will be used.
Availability: 2.0.0
Examples
See Also
12.2.4 DropOverviewConstraints
Synopsis
Description
Remove from a raster column the constraints used to show it as being an overview of another in the raster_overviews
raster catalog.
When the ovschema parameter is omitted, the first table found scanning the search_path will be used.
Availability: 2.0.0
See Also
12.2.5 PostGIS_GDAL_Version
Synopsis
text PostGIS_GDAL_Version();
Description
Reports the version of the GDAL library in use by PostGIS. Will also check and report if GDAL can find its data files.
Examples
SELECT PostGIS_GDAL_Version();
postgis_gdal_version
-----------------------------------
GDAL 1.11dev, released 2013/04/13
See Also
postgis.gdal_datapath
12.2.6 PostGIS_Raster_Lib_Build_Date
Synopsis
text PostGIS_Raster_Lib_Build_Date();
Description
Examples
SELECT PostGIS_Raster_Lib_Build_Date();
postgis_raster_lib_build_date
-----------------------------
2010-04-28 21:15:10
See Also
PostGIS_Raster_Lib_Version
12.2.7 PostGIS_Raster_Lib_Version
Synopsis
text PostGIS_Raster_Lib_Version();
Description
Examples
SELECT PostGIS_Raster_Lib_Version();
postgis_raster_lib_version
-----------------------------
2.0.0
See Also
PostGIS_Lib_Version
12.2.8 ST_GDALDrivers
ST_GDALDrivers — Returns a list of raster formats supported by PostGIS through GDAL. Only those formats with can_write=True
can be used by ST_AsGDALRaster
Synopsis
setof record ST_GDALDrivers(integer OUT idx, text OUT short_name, text OUT long_name, text OUT can_read, text OUT
can_write, text OUT create_options);
PostGIS 3.3.2 Manual 554 / 902
Description
Returns a list of raster formats short_name,long_name and creator options of each format supported by GDAL. Use the short_name
as input in the format parameter of ST_AsGDALRaster. Options vary depending on what drivers your libgdal was compiled
with. create_options returns an xml formatted set of CreationOptionList/Option consisting of name and optional type,
description and set of VALUE for each creator option for the specific driver.
Changed: 2.5.0 - add can_read and can_write columns.
Changed: 2.0.6, 2.1.3 - by default no drivers are enabled, unless GUC or Environment variable gdal_enabled_drivers is set.
Availability: 2.0.0 - requires GDAL >= 1.6.0.
<CreationOptionList>
<Option name="COMPRESS" type="string-select">
<Value>NONE</Value>
<Value>LZW</Value>
<Value>PACKBITS</Value>
<Value>JPEG</Value>
<Value>CCITTRLE</Value>
<Value>CCITTFAX3</Value>
<Value>CCITTFAX4</Value>
<Value>DEFLATE</Value>
</Option>
<Option name="PREDICTOR" type="int" description="Predictor Type"/>
<Option name="JPEG_QUALITY" type="int" description="JPEG quality 1-100" default="75"/>
<Option name="ZLEVEL" type="int" description="DEFLATE compression level 1-9" default ←-
="6"/>
PostGIS 3.3.2 Manual 556 / 902
COMPRESS | string-select | ←-
| NONE, LZW, ←-
PACKBITS, JPEG, CCITTRLE, CCITTFAX3, CCITTFAX4, DEFLATE
PREDICTOR | int | Predictor Type ←-
|
JPEG_QUALITY | int | JPEG quality 1-100 ←-
|
ZLEVEL | int | DEFLATE compression level 1-9 ←-
|
NBITS | int | BITS for sub-byte files (1-7), sub-uint16 (9-15), sub ←-
-uint32 (17-31) |
INTERLEAVE | string-select | ←-
| BAND, PIXEL
TILED | boolean | Switch to tiled format ←-
|
TFW | boolean | Write out world file ←-
|
RPB | boolean | Write out .RPB (RPC) file ←-
|
BLOCKXSIZE | int | Tile Width ←-
|
BLOCKYSIZE | int | Tile/Strip Height ←-
|
PHOTOMETRIC | string-select | ←-
| MINISBLACK, ←-
MINISWHITE, PALETTE, RGB, CMYK, YCBCR, CIELAB, ICCLAB, ITULAB
SPARSE_OK | boolean | Can newly created files have missing blocks? ←-
|
ALPHA | boolean | Mark first extrasample as being alpha ←-
|
PROFILE | string-select | ←-
| GDALGeoTIFF, ←-
GeoTIFF, BASELINE
PIXELTYPE | string-select | ←-
| DEFAULT, ←-
SIGNEDBYTE
BIGTIFF | string-select | Force creation of BigTIFF file ←-
| YES, NO, IF_NEEDED, IF_SAFER
ENDIANNESS | string-select | Force endianness of created file. For DEBUG purpose ←-
mostly | NATIVE, INVERTED, LITTLE, BIG
COPY_SRC_OVERVIEWS | boolean | Force copy of overviews of source dataset (CreateCopy ←-
()) |
(19 rows)
See Also
12.2.9 ST_Contour
ST_Contour — Generates a set of vector contours from the provided raster band, using the GDAL contouring algorithm.
PostGIS 3.3.2 Manual 558 / 902
Synopsis
setof record ST_Contour(raster rast, integer bandnumber, double precision level_interval, double precision level_base, double
precision[] fixed_levels, boolean polygonize);
Description
Generates a set of vector contours from the provided raster band, using the GDAL contouring algorithm.
When the fixed_levels parameter is a non-empty array, the level_interval and level_base parameters are ignored.
The polygonize parameter currently has no effect. Use the ST_Polygonize function to convert contours into polygons.
Return values are a set of records with the following attributes:
value The raster value the line represents. For an elevation DEM input, this would be the elevation of the output contour.
Availability: 3.2.0
Example
WITH c AS (
SELECT (ST_Contour(rast, 1, fixed_levels => ARRAY[100.0, 200.0, 300.0])).*
FROM dem_grid WHERE rid = 1
)
SELECT st_astext(geom), id, value
FROM c;
See Also
ST_InterpolateRaster
12.2.10 ST_InterpolateRaster
ST_InterpolateRaster — Interpolates a gridded surface based on an input set of 3-d points, using the X- and Y-values to position
the points on the grid and the Z-value of the points as the surface elevation.
Synopsis
Description
Interpolates a gridded surface based on an input set of 3-d points, using the X- and Y-values to position the points on the grid
and the Z-value of the points as the surface elevation. There are five interpolation algorithms available: inverse distance, inverse
distance nearest-neighbor, moving average, nearest neighbor, and linear interpolation. See the gdal_grid documentation for more
details on the algorithms and their parameters. For more information on how interpolations are calculated, see the GDAL grid
tutorial.
Input parameters are:
PostGIS 3.3.2 Manual 559 / 902
input_points The points to drive the interpolation. Any geometry with Z-values is acceptable, all points in the input will be
used.
algorithm_options A string defining the algorithm and algorithm options, in the format used by gdal_grid. For example, for an
inverse-distance interpolation with a smoothing of 2, you would use "invdist:smoothing=2.0"
template A raster template to drive the geometry of the output raster. The width, height, pixel size, spatial extent and pixel type
will be read from this template.
template_band_num By default the first band in the template raster is used to drive the output raster, but that can be adjusted
with this parameter.
Availability: 3.2.0
Example
SELECT ST_InterpolateRaster(
'MULTIPOINT(10.5 9.5 1000, 11.5 8.5 1000, 10.5 8.5 500, 11.5 9.5 500)'::geometry,
'invdist:smoothing:2.0',
ST_AddBand(ST_MakeEmptyRaster(200, 400, 10, 10, 0.01, -0.005, 0, 0), '16BSI')
)
See Also
ST_Contour
12.2.11 UpdateRasterSRID
UpdateRasterSRID — Change the SRID of all rasters in the user-specified column and table.
Synopsis
Description
Change the SRID of all rasters in the user-specified column and table. The function will drop all appropriate column constraints
(extent, alignment and SRID) before changing the SRID of the specified column’s rasters.
Note
The data (band pixel values) of the rasters are not touched by this function. Only the raster’s metadata is changed.
Availability: 2.1.0
See Also
UpdateGeometrySRID
PostGIS 3.3.2 Manual 560 / 902
12.2.12 ST_CreateOverview
Synopsis
Description
Create an overview table with resampled tiles from the source table. Output tiles will have the same size of input tiles and cover
the same spatial extent with a lower resolution (pixel size will be 1/factor of the original in both directions).
The overview table will be made available in the raster_overviews catalog and will have raster constraints enforced.
Algorithm options are: ’NearestNeighbor’, ’Bilinear’, ’Cubic’, ’CubicSpline’, and ’Lanczos’. Refer to: GDAL Warp resampling
methods for more details.
Availability: 2.2.0
Example
See Also
12.3.1 ST_AddBand
ST_AddBand — Returns a raster with the new band(s) of given type added with given initial value in the given index location.
If no index is specified, the band is added to the end.
Synopsis
Description
Returns a raster with a new band added in given position (index), of given type, of given initial value, and of given nodata value.
If no index is specified, the band is added to the end. If no fromband is specified, band 1 is assumed. Pixel type is a string
representation of one of the pixel types specified in ST_BandPixelType. If an existing index is specified all subsequent bands >=
that index are incremented by 1. If an initial value greater than the max of the pixel type is specified, then the initial value is set
to the highest value allowed by the pixel type.
For the variant that takes an array of addbandarg (Variant 1), a specific addbandarg’s index value is relative to the raster at the
time when the band described by that addbandarg is being added to the raster. See the Multiple New Bands example below.
For the variant that takes an array of rasters (Variant 5), if torast is NULL then the fromband band of each raster in the array
is accumulated into a new raster.
For the variants that take outdbfile (Variants 6 and 7), the value must include the full path to the raster file. The file must also
be accessible to the postgres server process.
Enhanced: 2.1.0 support for addbandarg added.
Enhanced: 2.1.0 support for new out-db bands added.
-- Add another band of type 8 bit unsigned integer with pixels initialized to 200
UPDATE dummy_rast
SET rast = ST_AddBand(rast,'8BUI'::text,200)
WHERE rid = 1;
-- Create an empty raster 100x100 units, with upper left right at 0, add 2 bands (band 1 ←-
is 0/1 boolean bit switch, band2 allows values 0-15)
-- uses addbandargs
INSERT INTO dummy_rast(rid,rast)
VALUES(10, ST_AddBand(ST_MakeEmptyRaster(100, 100, 0, 0, 1, -1, 0, 0, 0),
ARRAY[
ROW(1, '1BB'::text, 0, NULL),
ROW(2, '4BUI'::text, 0, NULL)
]::addbandarg[]
)
);
0 | 0 | 100 | 100 | 1 | -1 | 0 | 0 | 0 | ←-
2
PostGIS 3.3.2 Manual 562 / 902
SELECT
*
FROM ST_BandMetadata(
ST_AddBand(
ST_MakeEmptyRaster(10, 10, 0, 0, 1, -1, 0, 0, 0),
ARRAY[
ROW(NULL, '8BUI', 255, 0),
ROW(NULL, '16BUI', 1, 2),
ROW(2, '32BUI', 100, 12),
ROW(2, '32BF', 3.14, -1)
]::addbandarg[]
),
ARRAY[]::integer[]
);
-- Aggregate the 1st band of a table of like rasters into a single raster
-- with as many bands as there are test_types and as many rows (new rasters) as there are ←-
mice
-- NOTE: The ORDER BY test_type is only supported in PostgreSQL 9.0+
-- for 8.4 and below it usually works to order your data in a subselect (but not guaranteed ←-
)
-- The resulting raster will have a band for each test_type alphabetical by test_type
-- For mouse lovers: No mice were harmed in this exercise
SELECT
mouse,
ST_AddBand(NULL, array_agg(rast ORDER BY test_type), 1) As rast
FROM mice_studies
GROUP BY mouse;
SELECT
*
FROM ST_BandMetadata(
ST_AddBand(
ST_MakeEmptyRaster(10, 10, 0, 0, 1, -1, 0, 0, 0),
'/home/raster/mytestraster.tif'::text, NULL::int[]
),
ARRAY[]::integer[]
);
See Also
12.3.2 ST_AsRaster
Synopsis
raster ST_AsRaster(geometry geom, raster ref, text pixeltype, double precision value=1, double precision nodataval=0, boolean
touched=false);
raster ST_AsRaster(geometry geom, raster ref, text[] pixeltype=ARRAY[’8BUI’], double precision[] value=ARRAY[1], double
precision[] nodataval=ARRAY[0], boolean touched=false);
raster ST_AsRaster(geometry geom, double precision scalex, double precision scaley, double precision gridx, double preci-
sion gridy, text pixeltype, double precision value=1, double precision nodataval=0, double precision skewx=0, double precision
skewy=0, boolean touched=false);
raster ST_AsRaster(geometry geom, double precision scalex, double precision scaley, double precision gridx=NULL, dou-
ble precision gridy=NULL, text[] pixeltype=ARRAY[’8BUI’], double precision[] value=ARRAY[1], double precision[] no-
dataval=ARRAY[0], double precision skewx=0, double precision skewy=0, boolean touched=false);
raster ST_AsRaster(geometry geom, double precision scalex, double precision scaley, text pixeltype, double precision value=1,
double precision nodataval=0, double precision upperleftx=NULL, double precision upperlefty=NULL, double precision skewx=0,
double precision skewy=0, boolean touched=false);
raster ST_AsRaster(geometry geom, double precision scalex, double precision scaley, text[] pixeltype, double precision[]
value=ARRAY[1], double precision[] nodataval=ARRAY[0], double precision upperleftx=NULL, double precision upperlefty=NULL,
double precision skewx=0, double precision skewy=0, boolean touched=false);
raster ST_AsRaster(geometry geom, integer width, integer height, double precision gridx, double precision gridy, text pixel-
type, double precision value=1, double precision nodataval=0, double precision skewx=0, double precision skewy=0, boolean
touched=false);
raster ST_AsRaster(geometry geom, integer width, integer height, double precision gridx=NULL, double precision gridy=NULL,
text[] pixeltype=ARRAY[’8BUI’], double precision[] value=ARRAY[1], double precision[] nodataval=ARRAY[0], double pre-
cision skewx=0, double precision skewy=0, boolean touched=false);
raster ST_AsRaster(geometry geom, integer width, integer height, text pixeltype, double precision value=1, double precision
nodataval=0, double precision upperleftx=NULL, double precision upperlefty=NULL, double precision skewx=0, double preci-
sion skewy=0, boolean touched=false);
raster ST_AsRaster(geometry geom, integer width, integer height, text[] pixeltype, double precision[] value=ARRAY[1], dou-
ble precision[] nodataval=ARRAY[0], double precision upperleftx=NULL, double precision upperlefty=NULL, double precision
skewx=0, double precision skewy=0, boolean touched=false);
Description
Converts a PostGIS geometry to a PostGIS raster. The many variants offers three groups of possibilities for setting the alignment
and pixelsize of the resulting raster.
The first group, composed of the two first variants, produce a raster having the same alignment (scalex, scaley, gridx and
gridy), pixel type and nodata value as the provided reference raster. You generally pass this reference raster by joining the table
containing the geometry with the table containing the reference raster.
The second group, composed of four variants, let you set the dimensions of the raster by providing the parameters of a pixel size
(scalex & scaley and skewx & skewy). The width & height of the resulting raster will be adjusted to fit the extent
of the geometry. In most cases, you must cast integer scalex & scaley arguments to double precision so that PostgreSQL
choose the right variant.
The third group, composed of four variants, let you fix the dimensions of the raster by providing the dimensions of the raster
(width & height). The parameters of the pixel size (scalex & scaley and skewx & skewy) of the resulting raster will
be adjusted to fit the extent of the geometry.
The two first variants of each of those two last groups let you specify the alignment with an arbitrary corner of the alignment grid
(gridx & gridy) and the two last variants takes the upper left corner (upperleftx & upperlefty).
Each group of variant allows producing a one band raster or a multiple bands raster. To produce a multiple bands raster,
you must provide an array of pixel types (pixeltype[]), an array of initial values (value) and an array of nodata values
(nodataval). If not provided pixeltyped defaults to 8BUI, values to 1 and nodataval to 0.
PostGIS 3.3.2 Manual 564 / 902
The output raster will be in the same spatial reference as the source geometry. The only exception is for variants with a reference
raster. In this case the resulting raster will get the same SRID as the reference raster.
The optional touched parameter defaults to false and maps to the GDAL ALL_TOUCHED rasterization option, which deter-
mines if pixels touched by lines or polygons will be burned. Not just those on the line render path, or whose center point is within
the polygon.
This is particularly useful for rendering jpegs and pngs of geometries directly from the database when using in combination with
ST_AsPNG and other ST_AsGDALRaster family of functions.
Availability: 2.0.0 - requires GDAL >= 1.6.0.
Note
Not yet capable of rendering complex geometry types such as curves, TINS, and PolyhedralSurfaces, but should be
able too once GDAL can.
black circle
-- this will output a black circle taking up 150 x 150 pixels --
SELECT ST_AsPNG(ST_AsRaster(ST_Buffer(ST_Point(1,5),10),150, 150));
See Also
12.3.3 ST_Band
ST_Band — Returns one or more bands of an existing raster as a new raster. Useful for building new rasters from existing rasters.
Synopsis
Description
Returns one or more bands of an existing raster as a new raster. Useful for building new rasters from existing rasters or export of
only selected bands of a raster or rearranging the order of bands in a raster. If no band is specified or any of specified bands does
not exist in the raster, then all bands are returned. Used as a helper function in various functions such as for deleting a band.
Warning
For the nbands as text variant of function, the default delimiter is , which means you can ask for ’1,2,3’ and if
you wanted to use a different delimeter you would do ST_Band(rast, ’1@2@3’, ’@’). For asking for multiple
bands, we strongly suggest you use the array form of this function e.g. ST_Band(rast, ’{1,2,3}’::int[]);
since the text list of bands form may be removed in future versions of PostGIS.
Availability: 2.0.0
Examples
-- Make 2 new rasters: 1 containing band 1 of dummy, second containing band 2 of dummy and ←-
then reclassified as a 2BUI
SELECT ST_NumBands(rast1) As numb1, ST_BandPixelType(rast1) As pix1,
ST_NumBands(rast2) As numb2, ST_BandPixelType(rast2) As pix2
FROM (
SELECT ST_Band(rast) As rast1, ST_Reclass(ST_Band(rast,3), '100-200):1, [200-254:2', '2 ←-
BUI') As rast2
FROM dummy_rast
WHERE rid = 2) As foo;
num_bands
----------
2
--Make a new raster with 2nd band of original and 1st band repeated twice,
and another with just the third band
SELECT rast, ST_Band(rast, ARRAY[2,1,1]) As dupe_band,
ST_Band(rast, 3) As sing_band
FROM samples.than_chunked
WHERE rid=35;
See Also
12.3.4 ST_MakeEmptyCoverage
Synopsis
raster ST_MakeEmptyCoverage(integer tilewidth, integer tileheight, integer width, integer height, double precision upperleftx,
double precision upperlefty, double precision scalex, double precision scaley, double precision skewx, double precision skewy,
integer srid=unknown);
Description
Create a set of raster tiles with ST_MakeEmptyRaster. Grid dimension is width & height. Tile dimension is tilewidth &
tileheight. The covered georeferenced area is from upper left corner (upperleftx, upperlefty) to lower right corner
(upperleftx + width * scalex, upperlefty + height * scaley).
Note
Note that scaley is generally negative for rasters and scalex is generally positive. So lower right corner will have a lower
y value and higher x value than the upper left corner.
Availability: 2.4.0
PostGIS 3.3.2 Manual 567 / 902
Examples Basic
Create 16 tiles in a 4x4 grid to cover the WGS84 area from upper left corner (22, 77) to lower right corner (55, 33).
SELECT (ST_MetaData(tile)).* FROM ST_MakeEmptyCoverage(1, 1, 4, 4, 22, 33, (55 - 22)/(4):: ←-
float, (33 - 77)/(4)::float, 0., 0., 4326) tile;
See Also
ST_MakeEmptyRaster
12.3.5 ST_MakeEmptyRaster
ST_MakeEmptyRaster — Returns an empty raster (having no bands) of given dimensions (width & height), upperleft X and Y,
pixel size and rotation (scalex, scaley, skewx & skewy) and reference system (srid). If a raster is passed in, returns a new raster
with the same size, alignment and SRID. If srid is left out, the spatial ref is set to unknown (0).
Synopsis
Description
Returns an empty raster (having no band) of given dimensions (width & height) and georeferenced in spatial (or world) coor-
dinates with upper left X (upperleftx), upper left Y (upperlefty), pixel size and rotation (scalex, scaley, skewx & skewy) and
reference system (srid).
The last version use a single parameter to specify the pixel size (pixelsize). scalex is set to this argument and scaley is set to the
negative value of this argument. skewx and skewy are set to 0.
If an existing raster is passed in, it returns a new raster with the same meta data settings (without the bands).
If no srid is specified it defaults to 0. After you create an empty raster you probably want to add bands to it and maybe edit it.
Refer to ST_AddBand to define bands and ST_SetValue to set initial pixel values.
Examples
-- output --
rid | upperleftx | upperlefty | width | height | scalex | scaley | skewx | skewy | srid | ←-
numbands
-----+------------+------------+-------+--------+------------+------------+-------+-------+------+---
See Also
12.3.6 ST_Tile
ST_Tile — Returns a set of rasters resulting from the split of the input raster based upon the desired dimensions of the output
rasters.
Synopsis
setof raster ST_Tile(raster rast, int[] nband, integer width, integer height, boolean padwithnodata=FALSE, double precision no-
dataval=NULL);
setof raster ST_Tile(raster rast, integer nband, integer width, integer height, boolean padwithnodata=FALSE, double precision
nodataval=NULL);
setof raster ST_Tile(raster rast, integer width, integer height, boolean padwithnodata=FALSE, double precision nodataval=NULL);
PostGIS 3.3.2 Manual 569 / 902
Description
Returns a set of rasters resulting from the split of the input raster based upon the desired dimensions of the output rasters.
If padwithnodata = FALSE, edge tiles on the right and bottom sides of the raster may have different dimensions than the
rest of the tiles. If padwithnodata = TRUE, all tiles will have the same dimensions with the possibility that edge tiles
being padded with NODATA values. If raster band(s) do not have NODATA value(s) specified, one can be specified by setting
nodataval.
Note
If a specified band of the input raster is out-of-db, the corresponding band in the output rasters will also be out-of-db.
Availability: 2.1.0
Examples
WITH foo AS (
SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0), 1, '8BUI', ←-
1, 0), 2, '8BUI', 10, 0) AS rast UNION ALL
SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 3, 0, 1, -1, 0, 0, 0), 1, '8BUI', ←-
2, 0), 2, '8BUI', 20, 0) AS rast UNION ALL
SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 6, 0, 1, -1, 0, 0, 0), 1, '8BUI', ←-
3, 0), 2, '8BUI', 30, 0) AS rast UNION ALL
st_dumpvalues
------------------------------------------
(1,"{{1,1,1},{1,1,1},{1,1,1}}")
(2,"{{10,10,10},{10,10,10},{10,10,10}}")
(1,"{{2,2,2},{2,2,2},{2,2,2}}")
(2,"{{20,20,20},{20,20,20},{20,20,20}}")
(1,"{{3,3,3},{3,3,3},{3,3,3}}")
(2,"{{30,30,30},{30,30,30},{30,30,30}}")
(1,"{{4,4,4},{4,4,4},{4,4,4}}")
(2,"{{40,40,40},{40,40,40},{40,40,40}}")
(1,"{{5,5,5},{5,5,5},{5,5,5}}")
PostGIS 3.3.2 Manual 570 / 902
(2,"{{50,50,50},{50,50,50},{50,50,50}}")
(1,"{{6,6,6},{6,6,6},{6,6,6}}")
(2,"{{60,60,60},{60,60,60},{60,60,60}}")
(1,"{{7,7,7},{7,7,7},{7,7,7}}")
(2,"{{70,70,70},{70,70,70},{70,70,70}}")
(1,"{{8,8,8},{8,8,8},{8,8,8}}")
(2,"{{80,80,80},{80,80,80},{80,80,80}}")
(1,"{{9,9,9},{9,9,9},{9,9,9}}")
(2,"{{90,90,90},{90,90,90},{90,90,90}}")
(18 rows)
WITH foo AS (
SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0), 1, '8BUI', ←-
1, 0), 2, '8BUI', 10, 0) AS rast UNION ALL
SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 3, 0, 1, -1, 0, 0, 0), 1, '8BUI', ←-
2, 0), 2, '8BUI', 20, 0) AS rast UNION ALL
SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 6, 0, 1, -1, 0, 0, 0), 1, '8BUI', ←-
3, 0), 2, '8BUI', 30, 0) AS rast UNION ALL
st_dumpvalues
------------------------------------------
(1,"{{10,10,10},{10,10,10},{10,10,10}}")
(1,"{{20,20,20},{20,20,20},{20,20,20}}")
(1,"{{30,30,30},{30,30,30},{30,30,30}}")
(1,"{{40,40,40},{40,40,40},{40,40,40}}")
(1,"{{50,50,50},{50,50,50},{50,50,50}}")
(1,"{{60,60,60},{60,60,60},{60,60,60}}")
(1,"{{70,70,70},{70,70,70},{70,70,70}}")
(1,"{{80,80,80},{80,80,80},{80,80,80}}")
(1,"{{90,90,90},{90,90,90},{90,90,90}}")
(9 rows)
See Also
ST_Union, ST_Retile
PostGIS 3.3.2 Manual 571 / 902
12.3.7 ST_Retile
ST_Retile — Return a set of configured tiles from an arbitrarily tiled raster coverage.
Synopsis
setof raster ST_Retile(regclass tab, name col, geometry ext, float8 sfx, float8 sfy, int tw, int th, text algo=’NearestNeighbor’);
Description
Return a set of tiles having the specified scale (sfx, sfy) and max size (tw, th) and covering the specified extent (ext) with
data coming from the specified raster coverage (tab, col).
Algorithm options are: ’NearestNeighbor’, ’Bilinear’, ’Cubic’, ’CubicSpline’, and ’Lanczos’. Refer to: GDAL Warp resampling
methods for more details.
Availability: 2.2.0
See Also
ST_CreateOverview
12.3.8 ST_FromGDALRaster
Synopsis
Description
Returns a raster from a supported GDAL raster file. gdaldata is of type bytea and should be the contents of the GDAL raster
file.
If srid is NULL, the function will try to automatically assign the SRID from the GDAL raster. If srid is provided, the value
provided will override any automatically assigned SRID.
Availability: 2.1.0
Examples
WITH foo AS (
SELECT ST_AsPNG(ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 0, 0.1, ←-
-0.1, 0, 0, 4326), 1, '8BUI', 1, 0), 2, '8BUI', 2, 0), 3, '8BUI', 3, 0)) AS png
),
bar AS (
SELECT 1 AS rid, ST_FromGDALRaster(png) AS rast FROM foo
UNION ALL
SELECT 2 AS rid, ST_FromGDALRaster(png, 3310) AS rast FROM foo
)
SELECT
rid,
ST_Metadata(rast) AS metadata,
ST_SummaryStats(rast, 1) AS stats1,
PostGIS 3.3.2 Manual 572 / 902
ST_SummaryStats(rast, 2) AS stats2,
ST_SummaryStats(rast, 3) AS stats3
FROM bar
ORDER BY rid;
See Also
ST_AsGDALRaster
12.4.1 ST_GeoReference
ST_GeoReference — Returns the georeference meta data in GDAL or ESRI format as commonly seen in a world file. Default is
GDAL.
Synopsis
Description
Returns the georeference meta data including carriage return in GDAL or ESRI format as commonly seen in a world file. Default
is GDAL if no type specified. type is string ’GDAL’ or ’ESRI’.
Difference between format representations is as follows:
GDAL:
scalex
skewy
skewx
scaley
upperleftx
upperlefty
ESRI:
scalex
skewy
skewx
scaley
upperleftx + scalex*0.5
upperlefty + scaley*0.5
PostGIS 3.3.2 Manual 573 / 902
Examples
esri_ref | gdal_ref
--------------+--------------
2.0000000000 | 2.0000000000
0.0000000000 : 0.0000000000
0.0000000000 : 0.0000000000
3.0000000000 : 3.0000000000
1.5000000000 : 0.5000000000
2.0000000000 : 0.5000000000
See Also
12.4.2 ST_Height
Synopsis
Description
Examples
rid | rastheight
-----+------------
1 | 20
2 | 5
See Also
ST_Width
12.4.3 ST_IsEmpty
ST_IsEmpty — Returns true if the raster is empty (width = 0 and height = 0). Otherwise, returns false.
Synopsis
Description
Returns true if the raster is empty (width = 0 and height = 0). Otherwise, returns false.
Availability: 2.0.0
Examples
See Also
ST_HasNoBand
12.4.4 ST_MemSize
ST_MemSize — Returns the amount of space (in bytes) the raster takes.
Synopsis
Description
Note
pg_relation_size which gives the byte size of a table may return byte size lower than ST_MemSize. This is be-
cause pg_relation_size does not add toasted table contribution and large geometries are stored in TOAST tables.
pg_column_size might return lower because it returns the compressed size.
pg_total_relation_size - includes, the table, the toasted tables, and the indexes.
Availability: 2.2.0
Examples
rast_mem
--------
22568
PostGIS 3.3.2 Manual 575 / 902
See Also
12.4.5 ST_MetaData
ST_MetaData — Returns basic meta data about a raster object such as pixel size, rotation (skew), upper, lower left, etc.
Synopsis
Description
Returns basic meta data about a raster object such as pixel size, rotation (skew), upper, lower left, etc. Columns returned:
upperleftx | upperlefty | width | height | scalex | scaley | skewx | skewy | srid | numbands
Examples
rid | upperleftx | upperlefty | width | height | scalex | scaley | skewx | skewy | srid | ←-
numbands
----+------------+------------+-------+--------+--------+-----------+-------+-------+------+-------
1 | 0.5 | 0.5 | 10 | 20 | 2 | 3 | 0 | 0 | 0 | ←-
0
2 | 3427927.75 | 5793244 | 5 | 5 | 0.05 | -0.05 | 0 | 0 | 0 | ←-
3
See Also
ST_BandMetaData, ST_NumBands
12.4.6 ST_NumBands
Synopsis
Description
Examples
rid | numbands
----+----------
1 | 0
2 | 3
See Also
ST_Value
12.4.7 ST_PixelHeight
ST_PixelHeight — Returns the pixel height in geometric units of the spatial reference system.
Synopsis
Description
Returns the height of a pixel in geometric units of the spatial reference system. In the common case where there is no skew, the
pixel height is just the scale ratio between geometric coordinates and raster pixels.
Refer to ST_PixelWidth for a diagrammatic visualization of the relationship.
See Also
12.4.8 ST_PixelWidth
ST_PixelWidth — Returns the pixel width in geometric units of the spatial reference system.
Synopsis
Description
Returns the width of a pixel in geometric units of the spatial reference system. In the common case where there is no skew, the
pixel width is just the scale ratio between geometric coordinates and raster pixels.
The following diagram demonstrates the relationship:
See Also
12.4.9 ST_ScaleX
ST_ScaleX — Returns the X component of the pixel width in units of coordinate reference system.
Synopsis
Description
Returns the X component of the pixel width in units of coordinate reference system. Refer to World File for more details.
Changed: 2.0.0. In WKTRaster versions this was called ST_PixelSizeX.
Examples
rid | rastpixwidth
-----+--------------
1 | 2
2 | 0.05
See Also
ST_Width
12.4.10 ST_ScaleY
ST_ScaleY — Returns the Y component of the pixel height in units of coordinate reference system.
Synopsis
Description
Returns the Y component of the pixel height in units of coordinate reference system. May be negative. Refer to World File for
more details.
Changed: 2.0.0. In WKTRaster versions this was called ST_PixelSizeY.
Examples
rid | rastpixheight
-----+---------------
1 | 3
2 | -0.05
See Also
ST_Height
12.4.11 ST_RasterToWorldCoord
ST_RasterToWorldCoord — Returns the raster’s upper left corner as geometric X and Y (longitude and latitude) given a column
and row. Column and row starts at 1.
Synopsis
Description
Returns the upper left corner as geometric X and Y (longitude and latitude) given a column and row. Returned X and Y are in
geometric units of the georeferenced raster. Numbering of column and row starts at 1 but if either parameter is passed a zero, a
negative number or a number greater than the respective dimension of the raster, it will return coordinates outside of the raster
assuming the raster’s grid is applicable outside the raster’s bounds.
Availability: 2.1.0
Examples
-- non-skewed raster
SELECT
rid,
(ST_RasterToWorldCoord(rast,1, 1)).*,
(ST_RasterToWorldCoord(rast,2, 2)).*
FROM dummy_rast
-- skewed raster
SELECT
rid,
(ST_RasterToWorldCoord(rast, 1, 1)).*,
(ST_RasterToWorldCoord(rast, 2, 3)).*
FROM (
SELECT
rid,
ST_SetSkew(rast, 100.5, 0) As rast
FROM dummy_rast
) As foo
See Also
12.4.12 ST_RasterToWorldCoordX
ST_RasterToWorldCoordX — Returns the geometric X coordinate upper left of a raster, column and row. Numbering of columns
and rows starts at 1.
Synopsis
Description
Returns the upper left X coordinate of a raster column row in geometric units of the georeferenced raster. Numbering of columns
and rows starts at 1 but if you pass in a negative number or number higher than number of columns in raster, it will give you
coordinates outside of the raster file to left or right with the assumption that the skew and pixel sizes are same as selected raster.
Note
For non-skewed rasters, providing the X column is sufficient. For skewed rasters, the georeferenced coordinate is a
function of the ST_ScaleX and ST_SkewX and row and column. An error will be raised if you give just the X column for
a skewed raster.
Examples
See Also
12.4.13 ST_RasterToWorldCoordY
ST_RasterToWorldCoordY — Returns the geometric Y coordinate upper left corner of a raster, column and row. Numbering of
columns and rows starts at 1.
Synopsis
Description
Returns the upper left Y coordinate of a raster column row in geometric units of the georeferenced raster. Numbering of columns
and rows starts at 1 but if you pass in a negative number or number higher than number of columns/rows in raster, it will give
you coordinates outside of the raster file to left or right with the assumption that the skew and pixel sizes are same as selected
raster tile.
Note
For non-skewed rasters, providing the Y column is sufficient. For skewed rasters, the georeferenced coordinate is a
function of the ST_ScaleY and ST_SkewY and row and column. An error will be raised if you give just the Y row for a
skewed raster.
Examples
See Also
12.4.14 ST_Rotation
Synopsis
Description
Returns the uniform rotation of the raster in radian. If a raster does not have uniform rotation, NaN is returned. Refer to World
File for more details.
Examples
rid | rot
-----+-------------------
1 | 0.785398163397448
2 | 0.785398163397448
See Also
12.4.15 ST_SkewX
Synopsis
Description
Returns the georeference X skew (or rotation parameter). Refer to World File for more details.
Examples
See Also
12.4.16 ST_SkewY
Synopsis
Description
Returns the georeference Y skew (or rotation parameter). Refer to World File for more details.
Examples
-----+-------+-------+--------------------
1 | 0 | 0 | 2.0000000000
: 0.0000000000
: 0.0000000000
: 3.0000000000
: 0.5000000000
: 0.5000000000
:
2 | 0 | 0 | 0.0500000000
: 0.0000000000
: 0.0000000000
: -0.0500000000
: 3427927.7500000000
: 5793244.0000000000
See Also
12.4.17 ST_SRID
ST_SRID — Returns the spatial reference identifier of the raster as defined in spatial_ref_sys table.
Synopsis
Description
Returns the spatial reference identifier of the raster object as defined in the spatial_ref_sys table.
Note
From PostGIS 2.0+ the srid of a non-georeferenced raster/geometry is 0 instead of the prior -1.
Examples
srid
----------------
0
See Also
12.4.18 ST_Summary
Synopsis
Description
Examples
SELECT ST_Summary(
ST_AddBand(
ST_AddBand(
ST_AddBand(
ST_MakeEmptyRaster(10, 10, 0, 0, 1, -1, 0, 0, 0)
, 1, '8BUI', 1, 0
)
, 2, '32BF', 0, -9999
)
, 3, '16BSI', 0, NULL
)
);
st_summary
------------------------------------------------------------------
Raster of 10x10 pixels has 3 bands and extent of BOX(0 -10,10 0)+
band 1 of pixtype 8BUI is in-db with NODATA value of 0 +
band 2 of pixtype 32BF is in-db with NODATA value of -9999 +
band 3 of pixtype 16BSI is in-db with no NODATA value
(1 row)
See Also
12.4.19 ST_UpperLeftX
ST_UpperLeftX — Returns the upper left X coordinate of raster in projected spatial ref.
Synopsis
Description
Examples
rid | ulx
-----+------------
1 | 0.5
2 | 3427927.75
See Also
12.4.20 ST_UpperLeftY
ST_UpperLeftY — Returns the upper left Y coordinate of raster in projected spatial ref.
Synopsis
Description
Examples
rid | uly
-----+---------
1 | 0.5
2 | 5793244
See Also
12.4.21 ST_Width
Synopsis
Description
Examples
rastwidth
----------------
10
See Also
ST_Height
12.4.22 ST_WorldToRasterCoord
ST_WorldToRasterCoord — Returns the upper left corner as column and row given geometric X and Y (longitude and latitude)
or a point geometry expressed in the spatial reference coordinate system of the raster.
Synopsis
Description
Returns the upper left corner as column and row given geometric X and Y (longitude and latitude) or a point geometry. This
function works regardless of whether or not the geometric X and Y or point geometry is outside the extent of the raster. Geometric
X and Y must be expressed in the spatial reference coordinate system of the raster.
Availability: 2.1.0
Examples
SELECT
rid,
(ST_WorldToRasterCoord(rast,3427927.8,20.5)).*,
(ST_WorldToRasterCoord(rast,ST_GeomFromText('POINT(3427927.8 20.5)',ST_SRID(rast)))).*
FROM dummy_rast;
See Also
12.4.23 ST_WorldToRasterCoordX
ST_WorldToRasterCoordX — Returns the column in the raster of the point geometry (pt) or a X and Y world coordinate (xw,
yw) represented in world spatial reference system of raster.
PostGIS 3.3.2 Manual 588 / 902
Synopsis
Description
Returns the column in the raster of the point geometry (pt) or a X and Y world coordinate (xw, yw). A point, or (both xw and yw
world coordinates are required if a raster is skewed). If a raster is not skewed then xw is sufficient. World coordinates are in the
spatial reference coordinate system of the raster.
Changed: 2.1.0 In prior versions, this was called ST_World2RasterCoordX
Examples
See Also
12.4.24 ST_WorldToRasterCoordY
ST_WorldToRasterCoordY — Returns the row in the raster of the point geometry (pt) or a X and Y world coordinate (xw, yw)
represented in world spatial reference system of raster.
Synopsis
Description
Returns the row in the raster of the point geometry (pt) or a X and Y world coordinate (xw, yw). A point, or (both xw and yw
world coordinates are required if a raster is skewed). If a raster is not skewed then xw is sufficient. World coordinates are in the
spatial reference coordinate system of the raster.
Changed: 2.1.0 In prior versions, this was called ST_World2RasterCoordY
PostGIS 3.3.2 Manual 589 / 902
Examples
See Also
12.5.1 ST_BandMetaData
ST_BandMetaData — Returns basic meta data for a specific raster band. band num 1 is assumed if none-specified.
Synopsis
Description
Returns basic meta data about a raster band. Columns returned: pixeltype, nodatavalue, isoutdb, path, outdbbandnum, filesize,
filetimestamp.
Note
If raster contains no bands then an error is thrown.
Note
If band has no NODATA value, nodatavalue are NULL.
Note
If isoutdb is False, path, outdbbandnum, filesize and filetimestamp are NULL. If outdb access is disabled, filesize and
filetimestamp will also be NULL.
Enhanced: 2.5.0 to include outdbbandnum, filesize and filetimestamp for outdb rasters.
PostGIS 3.3.2 Manual 590 / 902
Examples: Variant 1
SELECT
rid,
(foo.md).*
FROM (
SELECT
rid,
ST_BandMetaData(rast, 1) AS md
FROM dummy_rast
WHERE rid=2
) As foo;
Examples: Variant 2
WITH foo AS (
SELECT
ST_AddBand(NULL::raster, '/home/pele/devel/geo/postgis-git/raster/test/regress/ ←-
loader/Projected.tif', NULL::int[]) AS rast
)
SELECT
*
FROM ST_BandMetadata(
(SELECT rast FROM foo),
ARRAY[1,3,2]::int[]
);
1 | 8BUI | | t | /home/pele/devel/geo/postgis-git/raster/test ←-
/regress/loader/Projected.tif | 1 | 12345 | 1521807257 |
3 | 8BUI | | t | /home/pele/devel/geo/postgis-git/raster/test ←-
/regress/loader/Projected.tif | 3 | 12345 | 1521807257 |
2 | 8BUI | | t | /home/pele/devel/geo/postgis-git/raster/test ←-
/regress/loader/Projected.tif | 2 | 12345 | 1521807257 |
See Also
ST_MetaData, ST_BandPixelType
12.5.2 ST_BandNoDataValue
ST_BandNoDataValue — Returns the value in a given band that represents no data. If no band num 1 is assumed.
Synopsis
Description
Examples
See Also
ST_NumBands
12.5.3 ST_BandIsNoData
ST_BandIsNoData — Returns true if the band is filled with only nodata values.
Synopsis
Description
Returns true if the band is filled with only nodata values. Band 1 is assumed if not specified. If the last argument is TRUE, the
entire band is checked pixel by pixel. Otherwise, the function simply returns the value of the isnodata flag for the band. The
default value for this parameter is FALSE, if not specified.
Availability: 2.0.0
Note
If the flag is dirty (this is, the result is different using TRUE as last parameter and not using it) you should update
the raster to set this flag to true, by using ST_SetBandIsNodata(), or ST_SetBandNodataValue() with TRUE as last
argument. See ST_SetBandIsNoData.
Examples
-- Add raster with two bands, one pixel/band. In the first band, nodatavalue = pixel value ←-
= 3.
-- In the second band, nodatavalue = 13, pixel value = 4
insert into dummy_rast values(1,
(
'01' -- little endian (uint8 ndr)
PostGIS 3.3.2 Manual 592 / 902
||
'0000' -- version (uint16 0)
||
'0200' -- nBands (uint16 0)
||
'17263529ED684A3F' -- scaleX (float64 0.000805965234044584)
||
'F9253529ED684ABF' -- scaleY (float64 -0.00080596523404458)
||
'1C9F33CE69E352C0' -- ipX (float64 -75.5533328537098)
||
'718F0E9A27A44840' -- ipY (float64 49.2824585505576)
||
'ED50EB853EC32B3F' -- skewX (float64 0.000211812383858707)
||
'7550EB853EC32B3F' -- skewY (float64 0.000211812383858704)
||
'E6100000' -- SRID (int32 4326)
||
'0100' -- width (uint16 1)
||
'0100' -- height (uint16 1)
||
'6' -- hasnodatavalue and isnodata value set to true.
||
'2' -- first band type (4BUI)
||
'03' -- novalue==3
||
'03' -- pixel(0,0)==3 (same that nodata)
||
'0' -- hasnodatavalue set to false
||
'5' -- second band type (16BSI)
||
'0D00' -- novalue==13
||
'0400' -- pixel(0,0)==4
)::raster
);
See Also
12.5.4 ST_BandPath
ST_BandPath — Returns system file path to a band stored in file system. If no bandnum specified, 1 is assumed.
Synopsis
Description
Returns system file path to a band. Throws an error if called with an in db band.
Examples
See Also
12.5.5 ST_BandFileSize
ST_BandFileSize — Returns the file size of a band stored in file system. If no bandnum specified, 1 is assumed.
Synopsis
Description
Returns the file size of a band stored in file system. Throws an error if called with an in db band, or if outdb access is not enabled.
This function is typically used in conjunction with ST_BandPath() and ST_BandFileTimestamp() so a client can determine if the
filename of a outdb raster as seen by it is the same as the one seen by the server.
Availability: 2.5.0
Examples
st_bandfilesize
-----------------
240574
12.5.6 ST_BandFileTimestamp
ST_BandFileTimestamp — Returns the file timestamp of a band stored in file system. If no bandnum specified, 1 is assumed.
Synopsis
Description
Returns the file timestamp (number of seconds since Jan 1st 1970 00:00:00 UTC) of a band stored in file system. Throws an
error if called with an in db band, or if outdb access is not enabled.
This function is typically used in conjunction with ST_BandPath() and ST_BandFileSize() so a client can determine if the
filename of a outdb raster as seen by it is the same as the one seen by the server.
Availability: 2.5.0
PostGIS 3.3.2 Manual 594 / 902
Examples
st_bandfiletimestamp
----------------------
1521807257
12.5.7 ST_BandPixelType
ST_BandPixelType — Returns the type of pixel for given band. If no bandnum specified, 1 is assumed.
Synopsis
Description
Returns name describing data type and size of values stored in each cell of given band.
There are 11 pixel types. Pixel Types supported are as follows:
Examples
See Also
ST_NumBands
PostGIS 3.3.2 Manual 595 / 902
12.5.8 ST_MinPossibleValue
Synopsis
Description
Examples
SELECT ST_MinPossibleValue('16BSI');
st_minpossiblevalue
---------------------
-32768
SELECT ST_MinPossibleValue('8BUI');
st_minpossiblevalue
---------------------
0
See Also
ST_BandPixelType
12.5.9 ST_HasNoBand
ST_HasNoBand — Returns true if there is no band with given band number. If no band number is specified, then band number
1 is assumed.
Synopsis
Description
Returns true if there is no band with given band number. If no band number is specified, then band number 1 is assumed.
Availability: 2.0.0
PostGIS 3.3.2 Manual 596 / 902
Examples
See Also
ST_NumBands
12.6.1 ST_PixelAsPolygon
ST_PixelAsPolygon — Returns the polygon geometry that bounds the pixel for a particular row and column.
Synopsis
Description
Returns the polygon geometry that bounds the pixel for a particular row and column.
Availability: 2.0.0
Examples
i | j | b1pgeom
---+---+-----------------------------------------------------------------------------
1 | 1 | POLYGON((3427927.75 5793244,3427927.8 5793244,3427927.8 5793243.95,...
2 | 1 | POLYGON((3427927.8 5793244,3427927.85 5793244,3427927.85 5793243.95, ..
See Also
12.6.2 ST_PixelAsPolygons
ST_PixelAsPolygons — Returns the polygon geometry that bounds every pixel of a raster band along with the value, the X and
the Y raster coordinates of each pixel.
Synopsis
Description
Returns the polygon geometry that bounds every pixel of a raster band along with the value (double precision), the X and the Y
raster coordinates (integers) of each pixel.
Return record format: geom geometry, val double precision, x integer, y integers.
Note
When exclude_nodata_value = TRUE, only those pixels whose values are not NODATA are returned as points.
Note
ST_PixelAsPolygons returns one polygon geometry for every pixel. This is different than ST_DumpAsPolygons where
each geometry represents one or more pixels with the same pixel value.
Availability: 2.0.0
Enhanced: 2.1.0 exclude_nodata_value optional argument was added.
Changed: 2.1.1 Changed behavior of exclude_nodata_value.
Examples
x | y | val | geom
---+---+-----------------------------------------------------------------------------
1 | 1 | | POLYGON((0 0,0.001 0.001,0.002 0,0.001 -0.001,0 0))
1 | 2 | 1 | POLYGON((0.001 -0.001,0.002 0,0.003 -0.001,0.002 -0.002,0.001 -0.001))
2 | 1 | 1 | POLYGON((0.001 0.001,0.002 0.002,0.003 0.001,0.002 0,0.001 0.001))
2 | 2 | 10 | POLYGON((0.002 0,0.003 0.001,0.004 0,0.003 -0.001,0.002 0))
See Also
12.6.3 ST_PixelAsPoint
Synopsis
Description
Examples
st_astext
----------------
POINT(0.5 0.5)
See Also
12.6.4 ST_PixelAsPoints
ST_PixelAsPoints — Returns a point geometry for each pixel of a raster band along with the value, the X and the Y raster
coordinates of each pixel. The coordinates of the point geometry are of the pixel’s upper-left corner.
Synopsis
Description
Returns a point geometry for each pixel of a raster band along with the value, the X and the Y raster coordinates of each pixel.
The coordinates of the point geometry are of the pixel’s upper-left corner.
Return record format: geom geometry, val double precision, x integer, y integers.
Note
When exclude_nodata_value = TRUE, only those pixels whose values are not NODATA are returned as points.
Availability: 2.1.0
Changed: 2.1.1 Changed behavior of exclude_nodata_value.
PostGIS 3.3.2 Manual 599 / 902
Examples
x | y | val | st_astext
---+---+-----+------------------------------
1 | 1 | 253 | POINT(3427927.75 5793244)
2 | 1 | 254 | POINT(3427927.8 5793244)
3 | 1 | 253 | POINT(3427927.85 5793244)
4 | 1 | 254 | POINT(3427927.9 5793244)
5 | 1 | 254 | POINT(3427927.95 5793244)
1 | 2 | 253 | POINT(3427927.75 5793243.95)
2 | 2 | 254 | POINT(3427927.8 5793243.95)
3 | 2 | 254 | POINT(3427927.85 5793243.95)
4 | 2 | 253 | POINT(3427927.9 5793243.95)
5 | 2 | 249 | POINT(3427927.95 5793243.95)
1 | 3 | 250 | POINT(3427927.75 5793243.9)
2 | 3 | 254 | POINT(3427927.8 5793243.9)
3 | 3 | 254 | POINT(3427927.85 5793243.9)
4 | 3 | 252 | POINT(3427927.9 5793243.9)
5 | 3 | 249 | POINT(3427927.95 5793243.9)
1 | 4 | 251 | POINT(3427927.75 5793243.85)
2 | 4 | 253 | POINT(3427927.8 5793243.85)
3 | 4 | 254 | POINT(3427927.85 5793243.85)
4 | 4 | 254 | POINT(3427927.9 5793243.85)
5 | 4 | 253 | POINT(3427927.95 5793243.85)
1 | 5 | 252 | POINT(3427927.75 5793243.8)
2 | 5 | 250 | POINT(3427927.8 5793243.8)
3 | 5 | 254 | POINT(3427927.85 5793243.8)
4 | 5 | 254 | POINT(3427927.9 5793243.8)
5 | 5 | 254 | POINT(3427927.95 5793243.8)
See Also
12.6.5 ST_PixelAsCentroid
ST_PixelAsCentroid — Returns the centroid (point geometry) of the area represented by a pixel.
Synopsis
Description
Examples
st_astext
--------------
POINT(1.5 2)
See Also
12.6.6 ST_PixelAsCentroids
ST_PixelAsCentroids — Returns the centroid (point geometry) for each pixel of a raster band along with the value, the X and
the Y raster coordinates of each pixel. The point geometry is the centroid of the area represented by a pixel.
Synopsis
Description
Returns the centroid (point geometry) for each pixel of a raster band along with the value, the X and the Y raster coordinates of
each pixel. The point geometry is the centroid of the area represented by a pixel.
Return record format: geom geometry, val double precision, x integer, y integers.
Note
When exclude_nodata_value = TRUE, only those pixels whose values are not NODATA are returned as points.
Examples
See Also
12.6.7 ST_Value
ST_Value — Returns the value of a given band in a given columnx, rowy pixel or at a particular geometric point. Band numbers
start at 1 and assumed to be 1 if not specified. If exclude_nodata_value is set to false, then all pixels include nodata
pixels are considered to intersect and return value. If exclude_nodata_value is not passed in then reads it from metadata
of raster.
Synopsis
Description
Returns the value of a given band in a given columnx, rowy pixel or at a given geometry point. Band numbers start at 1 and band
is assumed to be 1 if not specified.
If exclude_nodata_value is set to true, then only non nodata pixels are considered. If exclude_nodata_value is
set to false, then all pixels are considered.
The allowed values of the resample parameter are "nearest" which performs the default nearest-neighbor resampling, and
"bilinear" which performs a bilinear interpolation to estimate the value between pixel centers.
Enhanced: 3.2.0 resample optional argument was added.
Enhanced: 2.0.0 exclude_nodata_value optional argument was added.
Examples
PostGIS 3.3.2 Manual 602 / 902
--- Get all values in bands 1,2,3 of each pixel same as above but returning the upper left ←-
point point of each pixel --
SELECT ST_AsText(ST_SetSRID(
ST_Point(ST_UpperLeftX(rast) + ST_ScaleX(rast)*x,
ST_UpperLeftY(rast) + ST_ScaleY(rast)*y),
ST_SRID(rast))) As uplpt
, ST_Value(rast, 1, x, y) As b1val,
ST_Value(rast, 2, x, y) As b2val, ST_Value(rast, 3, x, y) As b3val
FROM dummy_rast CROSS JOIN
generate_series(1,1000) As x CROSS JOIN generate_series(1,1000) As y
WHERE rid = 2 AND x <= ST_Width(rast) AND y <= ST_Height(rast);
shadow
------------------------------------------------------------------------------------
MULTIPOLYGON(((3427928 5793243.9,3427928 5793243.85,3427927.95 5793243.85,3427927.95 ←-
5793243.9,
3427927.95 5793243.95,3427928 5793243.95,3427928.05 5793243.95,3427928.05 ←-
5793243.9,3427928 5793243.9)),((3427927.95 5793243.9,3427927.95 579324
3.85,3427927.9 5793243.85,3427927.85 5793243.85,3427927.85 5793243.9,3427927.9 ←-
5793243.9,3427927.9 5793243.95,
3427927.95 5793243.95,3427927.95 5793243.9)),((3427927.85 5793243.75,3427927.85 ←-
5793243.7,3427927.8 5793243.7,3427927.8 5793243.75
,3427927.8 5793243.8,3427927.8 5793243.85,3427927.85 5793243.85,3427927.85 ←-
5793243.8,3427927.85 5793243.75)),
((3427928.05 5793243.75,3427928.05 5793243.7,3427928 5793243.7,3427927.95 ←-
5793243.7,3427927.95 5793243.75,3427927.95 5793243.8,3427
927.95 5793243.85,3427928 5793243.85,3427928 5793243.8,3427928.05 5793243.8,
3427928.05 5793243.75)),((3427927.95 5793243.75,3427927.95 5793243.7,3427927.9 ←-
5793243.7,3427927.85 5793243.7,
3427927.85 5793243.75,3427927.85 5793243.8,3427927.85 5793243.85,3427927.9 5793243.85,
3427927.95 5793243.85,3427927.95 5793243.8,3427927.95 5793243.75)))
--- Checking all the pixels of a large raster tile can take a long time.
--- You can dramatically improve speed at some lose of precision by orders of magnitude
-- by sampling pixels using the step optional parameter of generate_series.
-- This next example does the same as previous but by checking 1 for every 4 (2x2) pixels ←-
and putting in the last checked
-- putting in the checked pixel as the value for subsequent 4
WHERE rid = 2
AND x <= ST_Width(rast) AND y <= ST_Height(rast) ) As foo
WHERE
ST_Intersects(
pixpolyg,
ST_GeomFromText('POLYGON((3427928 5793244,3427927.75 5793243.75,3427928 ←-
5793243.75,3427928 5793244))',0)
) AND b2val != 254;
shadow
------------------------------------------------------------------------------------
MULTIPOLYGON(((3427927.9 5793243.85,3427927.8 5793243.85,3427927.8 5793243.95,
3427927.9 5793243.95,3427928 5793243.95,3427928.1 5793243.95,3427928.1 5793243.85,3427928 ←-
5793243.85,3427927.9 5793243.85)),
((3427927.9 5793243.65,3427927.8 5793243.65,3427927.8 5793243.75,3427927.8 ←-
5793243.85,3427927.9 5793243.85,
3427928 5793243.85,3427928 5793243.75,3427928.1 5793243.75,3427928.1 5793243.65,3427928 ←-
5793243.65,3427927.9 5793243.65)))
See Also
12.6.8 ST_NearestValue
ST_NearestValue — Returns the nearest non-NODATA value of a given band’s pixel specified by a columnx and rowy or a
geometric point expressed in the same spatial reference coordinate system as the raster.
Synopsis
double precision ST_NearestValue(raster rast, integer bandnum, geometry pt, boolean exclude_nodata_value=true);
double precision ST_NearestValue(raster rast, geometry pt, boolean exclude_nodata_value=true);
double precision ST_NearestValue(raster rast, integer bandnum, integer columnx, integer rowy, boolean exclude_nodata_value=true);
double precision ST_NearestValue(raster rast, integer columnx, integer rowy, boolean exclude_nodata_value=true);
Description
Returns the nearest non-NODATA value of a given band in a given columnx, rowy pixel or at a specific geometric point. If
the columnx, rowy pixel or the pixel at the specified geometric point is NODATA, the function will find the nearest pixel to the
columnx, rowy pixel or geometric point whose value is not NODATA.
Band numbers start at 1 and bandnum is assumed to be 1 if not specified. If exclude_nodata_value is set to false, then
all pixels include nodata pixels are considered to intersect and return value. If exclude_nodata_value is not passed in
then reads it from metadata of raster.
Availability: 2.1.0
Note
ST_NearestValue is a drop-in replacement for ST_Value.
PostGIS 3.3.2 Manual 605 / 902
Examples
value | nearestvalue
-------+--------------
1 | 1
value | nearestvalue
PostGIS 3.3.2 Manual 606 / 902
-------+--------------
| 1
See Also
ST_Neighborhood, ST_Value
12.6.9 ST_SetZ
ST_SetZ — Returns a geometry with the same X/Y coordinates as the input geometry, and values from the raster copied into the
Z dimension using the requested resample algorithm.
Synopsis
Description
Returns a geometry with the same X/Y coordinates as the input geometry, and values from the raster copied into the Z dimensions
using the requested resample algorithm.
The resample parameter can be set to "nearest" to copy the values from the cell each vertex falls within, or "bilinear" to use
bilinear interpolation to calculate a value that takes neighboring cells into account also.
Availability: 3.2.0
Examples
--
-- 2x2 test raster with values
--
-- 10 50
-- 40 20
--
WITH test_raster AS (
SELECT
ST_SetValues(
ST_AddBand(
ST_MakeEmptyRaster(width => 2, height => 2,
upperleftx => 0, upperlefty => 2,
scalex => 1.0, scaley => -1.0,
skewx => 0, skewy => 0, srid => 4326),
index => 1, pixeltype => '16BSI',
initialvalue => 0,
nodataval => -999),
1,1,1,
newvalueset =>ARRAY[ARRAY[10.0::float8, 50.0::float8], ARRAY[40.0::float8, 20.0::float8 ←-
]]) AS rast
)
SELECT
ST_AsText(
ST_SetZ(
rast,
band => 1,
geom => 'SRID=4326;LINESTRING(1.0 1.9, 1.0 0.2)'::geometry,
resample => 'bilinear'
PostGIS 3.3.2 Manual 607 / 902
))
FROM test_raster
st_astext
----------------------------------
LINESTRING Z (1 1.9 38,1 0.2 27)
See Also
ST_Value, ST_SetM
12.6.10 ST_SetM
ST_SetM — Returns a geometry with the same X/Y coordinates as the input geometry, and values from the raster copied into
the Z dimension using the requested resample algorithm.
Synopsis
Description
Returns a geometry with the same X/Y coordinates as the input geometry, and values from the raster copied into the Z dimensions
using the requested resample algorithm.
The resample parameter can be set to "nearest" to copy the values from the cell each vertex falls within, or "bilinear" to use
bilinear interpolation to calculate a value that takes neighboring cells into account also.
Availability: 3.2.0
Examples
--
-- 2x2 test raster with values
--
-- 10 50
-- 40 20
--
WITH test_raster AS (
SELECT
ST_SetValues(
ST_AddBand(
ST_MakeEmptyRaster(width => 2, height => 2,
upperleftx => 0, upperlefty => 2,
scalex => 1.0, scaley => -1.0,
skewx => 0, skewy => 0, srid => 4326),
index => 1, pixeltype => '16BSI',
initialvalue => 0,
nodataval => -999),
1,1,1,
newvalueset =>ARRAY[ARRAY[10.0::float8, 50.0::float8], ARRAY[40.0::float8, 20.0::float8 ←-
]]) AS rast
)
SELECT
ST_AsText(
ST_SetM(
PostGIS 3.3.2 Manual 608 / 902
rast,
band => 1,
geom => 'SRID=4326;LINESTRING(1.0 1.9, 1.0 0.2)'::geometry,
resample => 'bilinear'
))
FROM test_raster
st_astext
----------------------------------
LINESTRING M (1 1.9 38,1 0.2 27)
See Also
ST_Value, ST_SetZ
12.6.11 ST_Neighborhood
ST_Neighborhood — Returns a 2-D double precision array of the non-NODATA values around a given band’s pixel specified by
either a columnX and rowY or a geometric point expressed in the same spatial reference coordinate system as the raster.
Synopsis
double precision[][] ST_Neighborhood(raster rast, integer bandnum, integer columnX, integer rowY, integer distanceX, integer
distanceY, boolean exclude_nodata_value=true);
double precision[][] ST_Neighborhood(raster rast, integer columnX, integer rowY, integer distanceX, integer distanceY, boolean
exclude_nodata_value=true);
double precision[][] ST_Neighborhood(raster rast, integer bandnum, geometry pt, integer distanceX, integer distanceY, boolean
exclude_nodata_value=true);
double precision[][] ST_Neighborhood(raster rast, geometry pt, integer distanceX, integer distanceY, boolean exclude_nodata_value=tru
Description
Returns a 2-D double precision array of the non-NODATA values around a given band’s pixel specified by either a columnX
and rowY or a geometric point expressed in the same spatial reference coordinate system as the raster. The distanceX and
distanceY parameters define the number of pixels around the specified pixel in the X and Y axes, e.g. I want all values within
3 pixel distance along the X axis and 2 pixel distance along the Y axis around my pixel of interest. The center value of the 2-D
array will be the value at the pixel specified by the columnX and rowY or the geometric point.
Band numbers start at 1 and bandnum is assumed to be 1 if not specified. If exclude_nodata_value is set to false, then
all pixels include nodata pixels are considered to intersect and return value. If exclude_nodata_value is not passed in
then reads it from metadata of raster.
Note
The number of elements along each axis of the returning 2-D array is 2 * (distanceX|distanceY) + 1. So for a
distanceX and distanceY of 1, the returning array will be 3x3.
Note
The 2-D array output can be passed to any of the raster processing builtin functions, e.g. ST_Min4ma, ST_Sum4ma,
ST_Mean4ma.
Availability: 2.1.0
PostGIS 3.3.2 Manual 609 / 902
Examples
st_neighborhood
---------------------------------
{{NULL,1,1},{1,1,1},{1,NULL,1}}
st_neighborhood
------------------------------
{{1,1,1},{1,NULL,1},{1,1,1}}
1, 1, 1, ARRAY[
[0, 1, 1, 1, 1],
[1, 1, 1, 0, 1],
[1, 0, 1, 1, 1],
[1, 1, 1, 1, 0],
[1, 1, 0, 1, 1]
]::double precision[],
1
) AS rast
st_neighborhood
---------------------------
{{1,1,0},{0,1,1},{1,1,1}}
See Also
12.6.12 ST_SetValue
ST_SetValue — Returns modified raster resulting from setting the value of a given band in a given columnx, rowy pixel or the
pixels that intersect a particular geometry. Band numbers start at 1 and assumed to be 1 if not specified.
Synopsis
raster ST_SetValue(raster rast, integer bandnum, geometry geom, double precision newvalue);
raster ST_SetValue(raster rast, geometry geom, double precision newvalue);
raster ST_SetValue(raster rast, integer bandnum, integer columnx, integer rowy, double precision newvalue);
raster ST_SetValue(raster rast, integer columnx, integer rowy, double precision newvalue);
Description
Returns modified raster resulting from setting the specified pixels’ values to new value for the designated band given the raster’s
row and column or a geometry. If no band is specified, then band 1 is assumed.
Enhanced: 2.1.0 Geometry variant of ST_SetValue() now supports any geometry type, not just point. The geometry variant is a
wrapper around the geomval[] variant of ST_SetValues()
Examples
-- Geometry example
SELECT (foo.geomval).val, ST_AsText(ST_Union((foo.geomval).geom))
FROM (SELECT ST_DumpAsPolygons(
ST_SetValue(rast,1,
ST_Point(3427927.75, 5793243.95),
50)
) As geomval
FROM dummy_rast
where rid = 2) As foo
WHERE (foo.geomval).val < 250
GROUP BY (foo.geomval).val;
val | st_astext
-----+-------------------------------------------------------------------
50 | POLYGON((3427927.75 5793244,3427927.75 5793243.95,3427927.8 579324 ...
249 | POLYGON((3427927.95 5793243.95,3427927.95 5793243.85,3427928 57932 ...
PostGIS 3.3.2 Manual 611 / 902
See Also
ST_Value, ST_DumpAsPolygons
12.6.13 ST_SetValues
ST_SetValues — Returns modified raster resulting from setting the values of a given band.
Synopsis
raster ST_SetValues(raster rast, integer nband, integer columnx, integer rowy, double precision[][] newvalueset, boolean[][]
noset=NULL, boolean keepnodata=FALSE);
raster ST_SetValues(raster rast, integer nband, integer columnx, integer rowy, double precision[][] newvalueset, double precision
nosetvalue, boolean keepnodata=FALSE);
raster ST_SetValues(raster rast, integer nband, integer columnx, integer rowy, integer width, integer height, double precision
newvalue, boolean keepnodata=FALSE);
raster ST_SetValues(raster rast, integer columnx, integer rowy, integer width, integer height, double precision newvalue, boolean
keepnodata=FALSE);
raster ST_SetValues(raster rast, integer nband, geomval[] geomvalset, boolean keepnodata=FALSE);
Description
Returns modified raster resulting from setting specified pixels to new value(s) for the designated band. columnx and rowy are
1-indexed.
If keepnodata is TRUE, those pixels whose values are NODATA will not be set with the corresponding value in newvalueset.
For Variant 1, the specific pixels to be set are determined by the columnx, rowy pixel coordinates and the dimensions of the
newvalueset array. noset can be used to prevent pixels with values present in newvalueset from being set (due to
PostgreSQL not permitting ragged/jagged arrays). See example Variant 1.
Variant 2 is like Variant 1 but with a simple double precision nosetvalue instead of a boolean noset array. Elements in
newvalueset with the nosetvalue value with be skipped. See example Variant 2.
For Variant 3, the specific pixels to be set are determined by the columnx, rowy pixel coordinates, width and height. See
example Variant 3.
Variant 4 is the same as Variant 3 with the exception that it assumes that the first band’s pixels of rast will be set.
For Variant 5, an array of geomval is used to determine the specific pixels to be set. If all the geometries in the array are of
type POINT or MULTIPOINT, the function uses a shortcut where the longitude and latitude of each point is used to set a pixel
directly. Otherwise, the geometries are converted to rasters and then iterated through in one pass. See example Variant 5.
Availability: 2.1.0
Examples: Variant 1
PostGIS 3.3.2 Manual 612 / 902
/*
The ST_SetValues() does the following...
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 1 | 1 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | => | 1 | 9 | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 9 | 9 |
+ - + - + - + + - + - + - +
*/
SELECT
(poly).x,
(poly).y,
(poly).val
FROM (
SELECT
ST_PixelAsPolygons(
ST_SetValues(
ST_AddBand(
ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0),
1, '8BUI', 1, 0
),
1, 2, 2, ARRAY[[9, 9], [9, 9]]::double precision[][]
)
) AS poly
) foo
ORDER BY 1, 2;
x | y | val
---+---+-----
1 | 1 | 1
1 | 2 | 1
1 | 3 | 1
2 | 1 | 1
2 | 2 | 9
2 | 3 | 9
3 | 1 | 1
3 | 2 | 9
3 | 3 | 9
/*
The ST_SetValues() does the following...
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 9 | 9 | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | => | 9 | | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 9 | 9 | 9 |
+ - + - + - + + - + - + - +
*/
SELECT
(poly).x,
(poly).y,
(poly).val
FROM (
SELECT
ST_PixelAsPolygons(
ST_SetValues(
ST_AddBand(
PostGIS 3.3.2 Manual 613 / 902
x | y | val
---+---+-----
1 | 1 | 9
1 | 2 | 9
1 | 3 | 9
2 | 1 | 9
2 | 2 |
2 | 3 | 9
3 | 1 | 9
3 | 2 | 9
3 | 3 | 9
/*
The ST_SetValues() does the following...
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 9 | 9 | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | => | 1 | | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 9 | 9 | 9 |
+ - + - + - + + - + - + - +
*/
SELECT
(poly).x,
(poly).y,
(poly).val
FROM (
SELECT
ST_PixelAsPolygons(
ST_SetValues(
ST_AddBand(
ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0),
1, '8BUI', 1, 0
),
1, 1, 1,
ARRAY[[9, 9, 9], [9, NULL, 9], [9, 9, 9]]::double precision[][],
ARRAY[[false], [true]]::boolean[][]
)
) AS poly
) foo
ORDER BY 1, 2;
x | y | val
---+---+-----
1 | 1 | 9
1 | 2 | 1
1 | 3 | 9
2 | 1 | 9
2 | 2 |
2 | 3 | 9
3 | 1 | 9
3 | 2 | 9
PostGIS 3.3.2 Manual 614 / 902
3 | 3 | 9
/*
The ST_SetValues() does the following...
+ - + - + - + + - + - + - +
| | 1 | 1 | | | 9 | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | => | 1 | | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 9 | 9 | 9 |
+ - + - + - + + - + - + - +
*/
SELECT
(poly).x,
(poly).y,
(poly).val
FROM (
SELECT
ST_PixelAsPolygons(
ST_SetValues(
ST_SetValue(
ST_AddBand(
ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0),
1, '8BUI', 1, 0
),
1, 1, 1, NULL
),
1, 1, 1,
ARRAY[[9, 9, 9], [9, NULL, 9], [9, 9, 9]]::double precision[][],
ARRAY[[false], [true]]::boolean[][],
TRUE
)
) AS poly
) foo
ORDER BY 1, 2;
x | y | val
---+---+-----
1 | 1 |
1 | 2 | 1
1 | 3 | 9
2 | 1 | 9
2 | 2 |
2 | 3 | 9
3 | 1 | 9
3 | 2 | 9
3 | 3 | 9
Examples: Variant 2
/*
The ST_SetValues() does the following...
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 1 | 1 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | => | 1 | 9 | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 9 | 9 |
PostGIS 3.3.2 Manual 615 / 902
+ - + - + - + + - + - + - +
*/
SELECT
(poly).x,
(poly).y,
(poly).val
FROM (
SELECT
ST_PixelAsPolygons(
ST_SetValues(
ST_AddBand(
ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0),
1, '8BUI', 1, 0
),
1, 1, 1, ARRAY[[-1, -1, -1], [-1, 9, 9], [-1, 9, 9]]::double precision[][], -1
)
) AS poly
) foo
ORDER BY 1, 2;
x | y | val
---+---+-----
1 | 1 | 1
1 | 2 | 1
1 | 3 | 1
2 | 1 | 1
2 | 2 | 9
2 | 3 | 9
3 | 1 | 1
3 | 2 | 9
3 | 3 | 9
/*
This example is like the previous one. Instead of nosetvalue = -1, nosetvalue = NULL
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 1 | 1 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | => | 1 | 9 | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 9 | 9 |
+ - + - + - + + - + - + - +
*/
SELECT
(poly).x,
(poly).y,
(poly).val
FROM (
SELECT
ST_PixelAsPolygons(
ST_SetValues(
ST_AddBand(
ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0),
1, '8BUI', 1, 0
),
1, 1, 1, ARRAY[[NULL, NULL, NULL], [NULL, 9, 9], [NULL, 9, 9]]::double ←-
precision[][], NULL::double precision
)
) AS poly
) foo
PostGIS 3.3.2 Manual 616 / 902
ORDER BY 1, 2;
x | y | val
---+---+-----
1 | 1 | 1
1 | 2 | 1
1 | 3 | 1
2 | 1 | 1
2 | 2 | 9
2 | 3 | 9
3 | 1 | 1
3 | 2 | 9
3 | 3 | 9
Examples: Variant 3
/*
The ST_SetValues() does the following...
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 1 | 1 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | => | 1 | 9 | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 9 | 9 |
+ - + - + - + + - + - + - +
* /
SELECT
(poly).x,
(poly).y,
(poly).val
FROM (
SELECT
ST_PixelAsPolygons(
ST_SetValues(
ST_AddBand(
ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0),
1, '8BUI', 1, 0
),
1, 2, 2, 2, 2, 9
)
) AS poly
) foo
ORDER BY 1, 2;
x | y | val
---+---+-----
1 | 1 | 1
1 | 2 | 1
1 | 3 | 1
2 | 1 | 1
2 | 2 | 9
2 | 3 | 9
3 | 1 | 1
3 | 2 | 9
3 | 3 | 9
/*
The ST_SetValues() does the following...
PostGIS 3.3.2 Manual 617 / 902
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 1 | 1 |
+ - + - + - + + - + - + - +
| 1 | | 1 | => | 1 | | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 9 | 9 |
+ - + - + - + + - + - + - +
* /
SELECT
(poly).x,
(poly).y,
(poly).val
FROM (
SELECT
ST_PixelAsPolygons(
ST_SetValues(
ST_SetValue(
ST_AddBand(
ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0),
1, '8BUI', 1, 0
),
1, 2, 2, NULL
),
1, 2, 2, 2, 2, 9, TRUE
)
) AS poly
) foo
ORDER BY 1, 2;
x | y | val
---+---+-----
1 | 1 | 1
1 | 2 | 1
1 | 3 | 1
2 | 1 | 1
2 | 2 |
2 | 3 | 9
3 | 1 | 1
3 | 2 | 9
3 | 3 | 9
Examples: Variant 5
WITH foo AS (
SELECT 1 AS rid, ST_AddBand(ST_MakeEmptyRaster(5, 5, 0, 0, 1, -1, 0, 0, 0), 1, '8BUI', ←-
0, 0) AS rast
), bar AS (
SELECT 1 AS gid, 'SRID=0;POINT(2.5 -2.5)'::geometry geom UNION ALL
SELECT 2 AS gid, 'SRID=0;POLYGON((1 -1, 4 -1, 4 -4, 1 -4, 1 -1))'::geometry geom UNION ←-
ALL
SELECT 3 AS gid, 'SRID=0;POLYGON((0 0, 5 0, 5 -1, 1 -1, 1 -4, 0 -4, 0 0))'::geometry ←-
geom UNION ALL
SELECT 4 AS gid, 'SRID=0;MULTIPOINT(0 0, 4 4, 4 -4)'::geometry
)
SELECT
rid, gid, ST_DumpValues(ST_SetValue(rast, 1, geom, gid))
FROM foo t1
CROSS JOIN bar t2
ORDER BY rid, gid;
PostGIS 3.3.2 Manual 618 / 902
1 | 1 | (1,"{{NULL,NULL,NULL,NULL,NULL},{NULL,NULL,NULL,NULL,NULL},{NULL,NULL,1,NULL, ←-
NULL},{NULL,NULL,NULL,NULL,NULL},{NULL,NULL,NULL,NULL,NULL}}")
1 | 2 | (1,"{{NULL,NULL,NULL,NULL,NULL},{NULL,2,2,2,NULL},{NULL,2,2,2,NULL},{NULL ←-
,2,2,2,NULL},{NULL,NULL,NULL,NULL,NULL}}")
1 | 3 | (1,"{{3,3,3,3,3},{3,NULL,NULL,NULL,NULL},{3,NULL,NULL,NULL,NULL},{3,NULL,NULL, ←-
NULL,NULL},{NULL,NULL,NULL,NULL,NULL}}")
1 | 4 | (1,"{{4,NULL,NULL,NULL,NULL},{NULL,NULL,NULL,NULL,NULL},{NULL,NULL,NULL,NULL, ←-
NULL},{NULL,NULL,NULL,NULL,NULL},{NULL,NULL,NULL,NULL,4}}")
(4 rows)
The following shows that geomvals later in the array can overwrite prior geomvals
WITH foo AS (
SELECT 1 AS rid, ST_AddBand(ST_MakeEmptyRaster(5, 5, 0, 0, 1, -1, 0, 0, 0), 1, '8BUI', ←-
0, 0) AS rast
), bar AS (
SELECT 1 AS gid, 'SRID=0;POINT(2.5 -2.5)'::geometry geom UNION ALL
SELECT 2 AS gid, 'SRID=0;POLYGON((1 -1, 4 -1, 4 -4, 1 -4, 1 -1))'::geometry geom UNION ←-
ALL
SELECT 3 AS gid, 'SRID=0;POLYGON((0 0, 5 0, 5 -1, 1 -1, 1 -4, 0 -4, 0 0))'::geometry ←-
geom UNION ALL
SELECT 4 AS gid, 'SRID=0;MULTIPOINT(0 0, 4 4, 4 -4)'::geometry
)
SELECT
t1.rid, t2.gid, t3.gid, ST_DumpValues(ST_SetValues(rast, 1, ARRAY[ROW(t2.geom, t2.gid), ←-
ROW(t3.geom, t3.gid)]::geomval[]))
FROM foo t1
CROSS JOIN bar t2
CROSS JOIN bar t3
WHERE t2.gid = 1
AND t3.gid = 2
ORDER BY t1.rid, t2.gid, t3.gid;
1 | 1 | 2 | (1,"{{NULL,NULL,NULL,NULL,NULL},{NULL,2,2,2,NULL},{NULL,2,2,2,NULL},{ ←-
NULL,2,2,2,NULL},{NULL,NULL,NULL,NULL,NULL}}")
(1 row)
WHERE t2.gid = 2
AND t3.gid = 1
ORDER BY t1.rid, t2.gid, t3.gid;
1 | 2 | 1 | (1,"{{NULL,NULL,NULL,NULL,NULL},{NULL,2,2,2,NULL},{NULL,2,1,2,NULL},{ ←-
NULL,2,2,2,NULL},{NULL,NULL,NULL,NULL,NULL}}")
(1 row)
See Also
12.6.14 ST_DumpValues
Synopsis
Description
Get the values of the specified band as a 2-dimension array (first index is row, second is column). If nband is NULL or not
provided, all raster bands are processed.
Availability: 2.1.0
Examples
WITH foo AS (
SELECT ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0), ←-
1, '8BUI'::text, 1, 0), 2, '32BF'::text, 3, -9999), 3, '16BSI', 0, 0) AS rast
)
SELECT
(ST_DumpValues(rast)).*
FROM foo;
nband | valarray
-------+------------------------------------------------------
1 | {{1,1,1},{1,1,1},{1,1,1}}
2 | {{3,3,3},{3,3,3},{3,3,3}}
3 | {{NULL,NULL,NULL},{NULL,NULL,NULL},{NULL,NULL,NULL}}
(3 rows)
WITH foo AS (
SELECT ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0), ←-
1, '8BUI'::text, 1, 0), 2, '32BF'::text, 3, -9999), 3, '16BSI', 0, 0) AS rast
)
SELECT
(ST_DumpValues(rast, ARRAY[3, 1])).*
FROM foo;
PostGIS 3.3.2 Manual 620 / 902
nband | valarray
-------+------------------------------------------------------
3 | {{NULL,NULL,NULL},{NULL,NULL,NULL},{NULL,NULL,NULL}}
1 | {{1,1,1},{1,1,1},{1,1,1}}
(2 rows)
WITH foo AS (
SELECT ST_SetValue(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0), 1, '8BUI ←-
', 1, 0), 1, 2, 5) AS rast
)
SELECT
(ST_DumpValues(rast, 1))[2][1]
FROM foo;
st_dumpvalues
---------------
5
(1 row)
See Also
12.6.15 ST_PixelOfValue
ST_PixelOfValue — Get the columnx, rowy coordinates of the pixel whose value equals the search value.
Synopsis
setof record ST_PixelOfValue( raster rast , integer nband , double precision[] search , boolean exclude_nodata_value=true );
setof record ST_PixelOfValue( raster rast , double precision[] search , boolean exclude_nodata_value=true );
setof record ST_PixelOfValue( raster rast , integer nband , double precision search , boolean exclude_nodata_value=true );
setof record ST_PixelOfValue( raster rast , double precision search , boolean exclude_nodata_value=true );
Description
Get the columnx, rowy coordinates of the pixel whose value equals the search value. If no band is specified, then band 1 is
assumed.
Availability: 2.1.0
Examples
SELECT
(pixels).*
FROM (
SELECT
ST_PixelOfValue(
ST_SetValue(
ST_SetValue(
ST_SetValue(
ST_SetValue(
ST_SetValue(
ST_AddBand(
PostGIS 3.3.2 Manual 621 / 902
val | x | y
-----+---+---
1 | 1 | 2
1 | 1 | 3
1 | 1 | 4
1 | 1 | 5
1 | 2 | 1
1 | 2 | 2
1 | 2 | 4
1 | 2 | 5
1 | 3 | 1
1 | 3 | 2
1 | 3 | 3
1 | 3 | 4
1 | 4 | 1
1 | 4 | 3
1 | 4 | 4
1 | 4 | 5
1 | 5 | 1
1 | 5 | 2
1 | 5 | 3
255 | 5 | 4
1 | 5 | 5
12.7.1 ST_SetGeoReference
ST_SetGeoReference — Set Georeference 6 georeference parameters in a single call. Numbers should be separated by white
space. Accepts inputs in GDAL or ESRI format. Default is GDAL.
Synopsis
Description
Set Georeference 6 georeference parameters in a single call. Accepts inputs in ’GDAL’ or ’ESRI’ format. Default is GDAL. If 6
coordinates are not provided will return null.
PostGIS 3.3.2 Manual 622 / 902
ESRI:
scalex skewy skewx scaley upperleftx + scalex*0.5 upperlefty + scaley*0.5
Note
If the raster has out-db bands, changing the georeference may result in incorrect access of the band’s externally stored
data.
Examples
WITH foo AS (
SELECT ST_MakeEmptyRaster(5, 5, 0, 0, 1, -1, 0, 0, 0) AS rast
)
SELECT
0 AS rid, (ST_Metadata(rast)).*
FROM foo
UNION ALL
SELECT
1, (ST_Metadata(ST_SetGeoReference(rast, '10 0 0 -10 0.1 0.1', 'GDAL'))).*
FROM foo
UNION ALL
SELECT
2, (ST_Metadata(ST_SetGeoReference(rast, '10 0 0 -10 5.1 -4.9', 'ESRI'))).*
FROM foo
UNION ALL
SELECT
3, (ST_Metadata(ST_SetGeoReference(rast, 1, 1, 10, -10, 0.001, 0.001))).*
FROM foo
0 | 0 | 0 | 5 | 5 | 1 | -1 | 0 | ←-
0 | 0 | 0
1 | 0.1 | 0.1 | 5 | 5 | 10 | -10 | 0 | ←-
0 | 0 | 0
2 | 0.0999999999999996 | 0.0999999999999996 | 5 | 5 | 10 | -10 | 0 | ←-
0 | 0 | 0
3 | 1 | 1 | 5 | 5 | 10 | -10 | 0.001 | ←-
0.001 | 0 | 0
See Also
12.7.2 ST_SetRotation
Synopsis
Description
Uniformly rotate the raster. Rotation is in radian. Refer to World File for more details.
Examples
SELECT
ST_ScaleX(rast1), ST_ScaleY(rast1), ST_SkewX(rast1), ST_SkewY(rast1),
ST_ScaleX(rast2), ST_ScaleY(rast2), ST_SkewX(rast2), ST_SkewY(rast2)
FROM (
SELECT ST_SetRotation(rast, 15) AS rast1, rast as rast2 FROM dummy_rast
) AS foo;
st_scalex | st_scaley | st_skewx | st_skewy | ←-
st_scalex | st_scaley | st_skewx | st_skewy
---------------------+---------------------+--------------------+--------------------+-----------+---
See Also
12.7.3 ST_SetScale
ST_SetScale — Sets the X and Y size of pixels in units of coordinate reference system. Number units/pixel width/height.
Synopsis
Description
Sets the X and Y size of pixels in units of coordinate reference system. Number units/pixel width/height. If only one unit passed
in, assumed X and Y are the same number.
Note
ST_SetScale is different from ST_Rescale in that ST_SetScale do not resample the raster to match the raster extent. It
only changes the metadata (or georeference) of the raster to correct an originally mis-specified scaling. ST_Rescale re-
sults in a raster having different width and height computed to fit the geographic extent of the input raster. ST_SetScale
do not modify the width, nor the height of the raster.
Changed: 2.0.0 In WKTRaster versions this was called ST_SetPixelSize. This was changed in 2.0.0.
PostGIS 3.3.2 Manual 624 / 902
Examples
UPDATE dummy_rast
SET rast = ST_SetScale(rast, 1.5)
WHERE rid = 2;
UPDATE dummy_rast
SET rast = ST_SetScale(rast, 1.5, 0.55)
WHERE rid = 2;
See Also
12.7.4 ST_SetSkew
ST_SetSkew — Sets the georeference X and Y skew (or rotation parameter). If only one is passed in, sets X and Y to the same
value.
Synopsis
Description
Sets the georeference X and Y skew (or rotation parameter). If only one is passed in, sets X and Y to the same value. Refer to
World File for more details.
Examples
-- Example 1
UPDATE dummy_rast SET rast = ST_SetSkew(rast,1,2) WHERE rid = 1;
SELECT rid, ST_SkewX(rast) As skewx, ST_SkewY(rast) As skewy,
ST_GeoReference(rast) as georef
FROM dummy_rast WHERE rid = 1;
1 | 1 | 2 | 2.0000000000
: 2.0000000000
: 1.0000000000
: 3.0000000000
: 0.5000000000
: 0.5000000000
See Also
12.7.5 ST_SetSRID
ST_SetSRID — Sets the SRID of a raster to a particular integer srid defined in the spatial_ref_sys table.
Synopsis
Description
Note
This function does not transform the raster in any way - it simply sets meta data defining the spatial ref of the coordinate
reference system that it’s currently in. Useful for transformations later.
See Also
12.7.6 ST_SetUpperLeft
ST_SetUpperLeft — Sets the value of the upper left corner of the pixel of the raster to projected X and Y coordinates.
PostGIS 3.3.2 Manual 626 / 902
Synopsis
Description
Set the value of the upper left corner of raster to the projected X and Y coordinates
Examples
SELECT ST_SetUpperLeft(rast,-71.01,42.37)
FROM dummy_rast
WHERE rid = 2;
See Also
ST_UpperLeftX, ST_UpperLeftY
12.7.7 ST_Resample
ST_Resample — Resample a raster using a specified resampling algorithm, new dimensions, an arbitrary grid corner and a set
of raster georeferencing attributes defined or borrowed from another raster.
Synopsis
raster ST_Resample(raster rast, integer width, integer height, double precision gridx=NULL, double precision gridy=NULL,
double precision skewx=0, double precision skewy=0, text algorithm=NearestNeighbor, double precision maxerr=0.125);
raster ST_Resample(raster rast, double precision scalex=0, double precision scaley=0, double precision gridx=NULL, double
precision gridy=NULL, double precision skewx=0, double precision skewy=0, text algorithm=NearestNeighbor, double preci-
sion maxerr=0.125);
raster ST_Resample(raster rast, raster ref, text algorithm=NearestNeighbor, double precision maxerr=0.125, boolean usescale=true);
raster ST_Resample(raster rast, raster ref, boolean usescale, text algorithm=NearestNeighbor, double precision maxerr=0.125);
Description
Resample a raster using a specified resampling algorithm, new dimensions (width & height), a grid corner (gridx & gridy) and
a set of raster georeferencing attributes (scalex, scaley, skewx & skewy) defined or borrowed from another raster. If using a
reference raster, the two rasters must have the same SRID.
New pixel values are computed using the NearestNeighbor (English or American spelling), Bilinear, Cubic, CubicSpline or
Lanczos resampling algorithm. Default is NearestNeighbor which is the fastest but produce the worst interpolation.
A maxerror percent of 0.125 is used if no maxerr is specified.
Note
Refer to: GDAL Warp resampling methods for more details.
Examples
SELECT
ST_Width(orig) AS orig_width,
ST_Width(reduce_100) AS new_width
FROM (
SELECT
rast AS orig,
ST_Resample(rast,100,100) AS reduce_100
FROM aerials.boston
WHERE ST_Intersects(rast,
ST_Transform(
ST_MakeEnvelope(-71.128, 42.2392,-71.1277, 42.2397, 4326),26986)
)
LIMIT 1
) AS foo;
orig_width | new_width
------------+-------------
200 | 100
See Also
12.7.8 ST_Rescale
ST_Rescale — Resample a raster by adjusting only its scale (or pixel size). New pixel values are computed using the Near-
estNeighbor (english or american spelling), Bilinear, Cubic, CubicSpline or Lanczos resampling algorithm. Default is Nearest-
Neighbor.
Synopsis
raster ST_Rescale(raster rast, double precision scalexy, text algorithm=NearestNeighbor, double precision maxerr=0.125);
raster ST_Rescale(raster rast, double precision scalex, double precision scaley, text algorithm=NearestNeighbor, double preci-
sion maxerr=0.125);
Description
Resample a raster by adjusting only its scale (or pixel size). New pixel values are computed using the NearestNeighbor (english
or american spelling), Bilinear, Cubic, CubicSpline or Lanczos resampling algorithm. The default is NearestNeighbor which is
the fastest but results in the worst interpolation.
scalex and scaley define the new pixel size. scaley must often be negative to get well oriented raster.
When the new scalex or scaley is not a divisor of the raster width or height, the extent of the resulting raster is expanded to
encompass the extent of the provided raster. If you want to be sure to retain exact input extent see ST_Resize
maxerr is the threshold for transformation approximation by the resampling algorithm (in pixel units). A default of 0.125 is
used if no maxerr is specified, which is the same value used in GDAL gdalwarp utility. If set to zero, no approximation takes
place.
Note
Refer to: GDAL Warp resampling methods for more details.
PostGIS 3.3.2 Manual 628 / 902
Note
ST_Rescale is different from ST_SetScale in that ST_SetScale do not resample the raster to match the raster extent.
ST_SetScale only changes the metadata (or georeference) of the raster to correct an originally mis-specified scaling.
ST_Rescale results in a raster having different width and height computed to fit the geographic extent of the input raster.
ST_SetScale do not modify the width, nor the height of the raster.
Examples
A simple example rescaling a raster from a pixel size of 0.001 degree to a pixel size of 0.0015 degree.
-- the original raster pixel size
SELECT ST_PixelWidth(ST_AddBand(ST_MakeEmptyRaster(100, 100, 0, 0, 0.001, -0.001, 0, 0, ←-
4269), '8BUI'::text, 1, 0)) width
width
----------
0.001
width
----------
0.0015
See Also
12.7.9 ST_Reskew
ST_Reskew — Resample a raster by adjusting only its skew (or rotation parameters). New pixel values are computed using
the NearestNeighbor (english or american spelling), Bilinear, Cubic, CubicSpline or Lanczos resampling algorithm. Default is
NearestNeighbor.
Synopsis
raster ST_Reskew(raster rast, double precision skewxy, text algorithm=NearestNeighbor, double precision maxerr=0.125);
raster ST_Reskew(raster rast, double precision skewx, double precision skewy, text algorithm=NearestNeighbor, double preci-
sion maxerr=0.125);
Description
Resample a raster by adjusting only its skew (or rotation parameters). New pixel values are computed using the NearestNeighbor
(english or american spelling), Bilinear, Cubic, CubicSpline or Lanczos resampling algorithm. The default is NearestNeighbor
which is the fastest but results in the worst interpolation.
skewx and skewy define the new skew.
The extent of the new raster will encompass the extent of the provided raster.
A maxerror percent of 0.125 if no maxerr is specified.
PostGIS 3.3.2 Manual 629 / 902
Note
Refer to: GDAL Warp resampling methods for more details.
Note
ST_Reskew is different from ST_SetSkew in that ST_SetSkew do not resample the raster to match the raster extent.
ST_SetSkew only changes the metadata (or georeference) of the raster to correct an originally mis-specified skew.
ST_Reskew results in a raster having different width and height computed to fit the geographic extent of the input
raster. ST_SetSkew do not modify the width, nor the height of the raster.
Examples
-- result
0
-- result
-0.982793723247329
See Also
12.7.10 ST_SnapToGrid
ST_SnapToGrid — Resample a raster by snapping it to a grid. New pixel values are computed using the NearestNeighbor
(english or american spelling), Bilinear, Cubic, CubicSpline or Lanczos resampling algorithm. Default is NearestNeighbor.
Synopsis
raster ST_SnapToGrid(raster rast, double precision gridx, double precision gridy, text algorithm=NearestNeighbor, double pre-
cision maxerr=0.125, double precision scalex=DEFAULT 0, double precision scaley=DEFAULT 0);
raster ST_SnapToGrid(raster rast, double precision gridx, double precision gridy, double precision scalex, double precision
scaley, text algorithm=NearestNeighbor, double precision maxerr=0.125);
raster ST_SnapToGrid(raster rast, double precision gridx, double precision gridy, double precision scalexy, text algorithm=NearestNeigh
double precision maxerr=0.125);
PostGIS 3.3.2 Manual 630 / 902
Description
Resample a raster by snapping it to a grid defined by an arbitrary pixel corner (gridx & gridy) and optionally a pixel size (scalex &
scaley). New pixel values are computed using the NearestNeighbor (english or american spelling), Bilinear, Cubic, CubicSpline
or Lanczos resampling algorithm. The default is NearestNeighbor which is the fastest but results in the worst interpolation.
gridx and gridy define any arbitrary pixel corner of the new grid. This is not necessarily the upper left corner of the new
raster and it does not have to be inside or on the edge of the new raster extent.
You can optionally define the pixel size of the new grid with scalex and scaley.
The extent of the new raster will encompass the extent of the provided raster.
A maxerror percent of 0.125 if no maxerr is specified.
Note
Refer to: GDAL Warp resampling methods for more details.
Note
Use ST_Resample if you need more control over the grid parameters.
Examples
--result
-0.0008
See Also
12.7.11 ST_Resize
Synopsis
raster ST_Resize(raster rast, integer width, integer height, text algorithm=NearestNeighbor, double precision maxerr=0.125);
raster ST_Resize(raster rast, double precision percentwidth, double precision percentheight, text algorithm=NearestNeighbor,
double precision maxerr=0.125);
raster ST_Resize(raster rast, text width, text height, text algorithm=NearestNeighbor, double precision maxerr=0.125);
Description
Resize a raster to a new width/height. The new width/height can be specified in exact number of pixels or a percentage of the
raster’s width/height. The extent of the the new raster will be the same as the extent of the provided raster.
New pixel values are computed using the NearestNeighbor (english or american spelling), Bilinear, Cubic, CubicSpline or Lanc-
zos resampling algorithm. The default is NearestNeighbor which is the fastest but results in the worst interpolation.
Variant 1 expects the actual width/height of the output raster.
Variant 2 expects decimal values between zero (0) and one (1) indicating the percentage of the input raster’s width/height.
Variant 3 takes either the actual width/height of the output raster or a textual percentage ("20%") indicating the percentage of the
input raster’s width/height.
Availability: 2.1.0 Requires GDAL 1.6.1+
Examples
rid | upperleftx | upperlefty | width | height | scalex | scaley | skewx | skewy | srid | ←-
numbands
PostGIS 3.3.2 Manual 632 / 902
-----+------------+------------+-------+--------+--------+--------+-------+-------+------+----------
1 | 0 | 0 | 500 | 500 | 1 | -1 | 0 | 0 | 0 | ←-
1
2 | 0 | 0 | 500 | 100 | 1 | -1 | 0 | 0 | 0 | ←-
1
3 | 0 | 0 | 250 | 900 | 1 | -1 | 0 | 0 | 0 | ←-
1
(3 rows)
See Also
12.7.12 ST_Transform
ST_Transform — Reprojects a raster in a known spatial reference system to another known spatial reference system using spec-
ified resampling algorithm. Options are NearestNeighbor, Bilinear, Cubic, CubicSpline, Lanczos defaulting to NearestNeighbor.
Synopsis
raster ST_Transform(raster rast, integer srid, text algorithm=NearestNeighbor, double precision maxerr=0.125, double precision
scalex, double precision scaley);
raster ST_Transform(raster rast, integer srid, double precision scalex, double precision scaley, text algorithm=NearestNeighbor,
double precision maxerr=0.125);
raster ST_Transform(raster rast, raster alignto, text algorithm=NearestNeighbor, double precision maxerr=0.125);
Description
Reprojects a raster in a known spatial reference system to another known spatial reference system using specified pixel warping
algorithm. Uses ’NearestNeighbor’ if no algorithm is specified and maxerror percent of 0.125 if no maxerr is specified.
Algorithm options are: ’NearestNeighbor’, ’Bilinear’, ’Cubic’, ’CubicSpline’, and ’Lanczos’. Refer to: GDAL Warp resampling
methods for more details.
ST_Transform is often confused with ST_SetSRID(). ST_Transform actually changes the coordinates of a raster (and resamples
the pixel values) from one spatial reference system to another, while ST_SetSRID() simply changes the SRID identifier of the
raster.
Unlike the other variants, Variant 3 requires a reference raster as alignto. The transformed raster will be transformed to the
spatial reference system (SRID) of the reference raster and be aligned (ST_SameAlignment = TRUE) to the reference raster.
Note
If you find your transformation support is not working right, you may need to set the environment variable PROJSO to
the .so or .dll projection library your PostGIS is using. This just needs to have the name of the file. So for example on
windows, you would in Control Panel -> System -> Environment Variables add a system variable called PROJSO and
set it to libproj.dll (if you are using proj 4.6.1). You’ll have to restart your PostgreSQL service/daemon after this
change.
Warning
When transforming a coverage of tiles, you almost always want to use a reference raster to insure same alignment and
no gaps in your tiles as demonstrated in example: Variant 3.
PostGIS 3.3.2 Manual 633 / 902
Examples
Examples: Variant 3
The following shows the difference between using ST_Transform(raster, srid) and ST_Transform(raster, alignto)
WITH foo AS (
SELECT 0 AS rid, ST_AddBand(ST_MakeEmptyRaster(2, 2, -500000, 600000, 100, -100, 0, 0, ←-
2163), 1, '16BUI', 1, 0) AS rast UNION ALL
SELECT 1, ST_AddBand(ST_MakeEmptyRaster(2, 2, -499800, 600000, 100, -100, 0, 0, 2163), ←-
1, '16BUI', 2, 0) AS rast UNION ALL
SELECT 2, ST_AddBand(ST_MakeEmptyRaster(2, 2, -499600, 600000, 100, -100, 0, 0, 2163), ←-
1, '16BUI', 3, 0) AS rast UNION ALL
aligned
not_aligned
See Also
ST_Transform, ST_SetSRID
PostGIS 3.3.2 Manual 635 / 902
12.8.1 ST_SetBandNoDataValue
ST_SetBandNoDataValue — Sets the value for the given band that represents no data. Band 1 is assumed if no band is specified.
To mark a band as having no nodata value, set the nodata value = NULL.
Synopsis
Description
Sets the value that represents no data for the band. Band 1 is assumed if not specified. This will affect results from ST_Polygon,
ST_DumpAsPolygons, and the ST_PixelAs...() functions.
Examples
-- wipe out the nodata value this will ensure all pixels are considered for all processing ←-
functions
UPDATE dummy_rast
SET rast = ST_SetBandNoDataValue(rast,1, NULL)
WHERE rid = 2;
See Also
ST_BandNoDataValue, ST_NumBands
12.8.2 ST_SetBandIsNoData
Synopsis
Description
Sets the isnodata flag for the band to true. Band 1 is assumed if not specified. This function should be called only when the flag is
considered dirty. That is, when the result calling ST_BandIsNoData is different using TRUE as last argument and without using
it
Availability: 2.0.0
Examples
-- Add raster with two bands, one pixel/band. In the first band, nodatavalue = pixel value ←-
= 3.
-- In the second band, nodatavalue = 13, pixel value = 4
insert into dummy_rast values(1,
(
'01' -- little endian (uint8 ndr)
||
'0000' -- version (uint16 0)
||
'0200' -- nBands (uint16 0)
||
'17263529ED684A3F' -- scaleX (float64 0.000805965234044584)
||
'F9253529ED684ABF' -- scaleY (float64 -0.00080596523404458)
||
'1C9F33CE69E352C0' -- ipX (float64 -75.5533328537098)
||
'718F0E9A27A44840' -- ipY (float64 49.2824585505576)
||
'ED50EB853EC32B3F' -- skewX (float64 0.000211812383858707)
||
'7550EB853EC32B3F' -- skewY (float64 0.000211812383858704)
||
'E6100000' -- SRID (int32 4326)
||
'0100' -- width (uint16 1)
||
'0100' -- height (uint16 1)
||
'4' -- hasnodatavalue set to true, isnodata value set to false (when it should be true)
||
'2' -- first band type (4BUI)
||
'03' -- novalue==3
||
'03' -- pixel(0,0)==3 (same that nodata)
||
'0' -- hasnodatavalue set to false
||
'5' -- second band type (16BSI)
||
'0D00' -- novalue==13
||
'0400' -- pixel(0,0)==4
)::raster
);
See Also
12.8.3 ST_SetBandPath
ST_SetBandPath — Update the external path and band number of an out-db band
Synopsis
raster ST_SetBandPath(raster rast, integer band, text outdbpath, integer outdbindex, boolean force=false);
Description
Updates an out-db band’s external raster file path and external band number.
Note
If force is set to true, no tests are done to ensure compatibility (e.g. alignment, pixel support) between the external
raster file and the PostGIS raster. This mode is intended for file system changes where the external raster resides.
Note
Internally, this method replaces the PostGIS raster’s band at index band with a new band instead of updating the
existing path information.
Availability: 2.5.0
Examples
WITH foo AS (
SELECT
ST_AddBand(NULL::raster, '/home/pele/devel/geo/postgis-git/raster/test/regress/ ←-
loader/Projected.tif', NULL::int[]) AS rast
)
SELECT
1 AS query,
*
FROM ST_BandMetadata(
(SELECT rast FROM foo),
ARRAY[1,3,2]::int[]
)
UNION ALL
PostGIS 3.3.2 Manual 638 / 902
SELECT
2,
*
FROM ST_BandMetadata(
(
SELECT
ST_SetBandPath(
rast,
2,
'/home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected2.tif ←-
',
1
) AS rast
FROM foo
),
ARRAY[1,3,2]::int[]
)
ORDER BY 1, 2;
1 | 1 | 8BUI | | t | /home/pele/devel/geo/postgis-git/ ←-
raster/test/regress/loader/Projected.tif | 1
1 | 2 | 8BUI | | t | /home/pele/devel/geo/postgis-git/ ←-
raster/test/regress/loader/Projected.tif | 2
1 | 3 | 8BUI | | t | /home/pele/devel/geo/postgis-git/ ←-
raster/test/regress/loader/Projected.tif | 3
2 | 1 | 8BUI | | t | /home/pele/devel/geo/postgis-git/ ←-
raster/test/regress/loader/Projected.tif | 1
2 | 2 | 8BUI | | t | /home/pele/devel/geo/postgis-git/ ←-
raster/test/regress/loader/Projected2.tif | 1
2 | 3 | 8BUI | | t | /home/pele/devel/geo/postgis-git/ ←-
raster/test/regress/loader/Projected.tif | 3
See Also
ST_BandMetaData, ST_SetBandIndex
12.8.4 ST_SetBandIndex
Synopsis
Description
Updates an out-db band’s external band number. This does not touch the external raster file associated with the out-db band
Note
If force is set to true, no tests are done to ensure compatibility (e.g. alignment, pixel support) between the external
raster file and the PostGIS raster. This mode is intended for where bands are moved around in the external raster file.
PostGIS 3.3.2 Manual 639 / 902
Note
Internally, this method replaces the PostGIS raster’s band at index band with a new band instead of updating the
existing path information.
Availability: 2.5.0
Examples
WITH foo AS (
SELECT
ST_AddBand(NULL::raster, '/home/pele/devel/geo/postgis-git/raster/test/regress/ ←-
loader/Projected.tif', NULL::int[]) AS rast
)
SELECT
1 AS query,
*
FROM ST_BandMetadata(
(SELECT rast FROM foo),
ARRAY[1,3,2]::int[]
)
UNION ALL
SELECT
2,
*
FROM ST_BandMetadata(
(
SELECT
ST_SetBandIndex(
rast,
2,
1
) AS rast
FROM foo
),
ARRAY[1,3,2]::int[]
)
ORDER BY 1, 2;
1 | 1 | 8BUI | | t | /home/pele/devel/geo/postgis-git/ ←-
raster/test/regress/loader/Projected.tif | 1
1 | 2 | 8BUI | | t | /home/pele/devel/geo/postgis-git/ ←-
raster/test/regress/loader/Projected.tif | 2
1 | 3 | 8BUI | | t | /home/pele/devel/geo/postgis-git/ ←-
raster/test/regress/loader/Projected.tif | 3
2 | 1 | 8BUI | | t | /home/pele/devel/geo/postgis-git/ ←-
raster/test/regress/loader/Projected.tif | 1
2 | 2 | 8BUI | | t | /home/pele/devel/geo/postgis-git/ ←-
raster/test/regress/loader/Projected.tif | 1
2 | 3 | 8BUI | | t | /home/pele/devel/geo/postgis-git/ ←-
raster/test/regress/loader/Projected.tif | 3
PostGIS 3.3.2 Manual 640 / 902
See Also
ST_BandMetaData, ST_SetBandPath
12.9.1 ST_Count
ST_Count — Returns the number of pixels in a given band of a raster or raster coverage. If no band is specified defaults to band
1. If exclude_nodata_value is set to true, will only count pixels that are not equal to the nodata value.
Synopsis
Description
Returns the number of pixels in a given band of a raster or raster coverage. If no band is specified nband defaults to 1.
Note
If exclude_nodata_value is set to true, will only count pixels with value not equal to the nodata value of the
raster. Set exclude_nodata_value to false to get count all pixels
Changed: 3.1.0 - The ST_Count(rastertable, rastercolumn, ...) variants removed. Use ST_CountAgg instead.
Availability: 2.0.0
Examples
--example will count all pixels not 249 and one will count all pixels. --
SELECT rid, ST_Count(ST_SetBandNoDataValue(rast,249)) As exclude_nodata,
ST_Count(ST_SetBandNoDataValue(rast,249),false) As include_nodata
FROM dummy_rast WHERE rid=2;
See Also
12.9.2 ST_CountAgg
ST_CountAgg — Aggregate. Returns the number of pixels in a given band of a set of rasters. If no band is specified defaults to
band 1. If exclude_nodata_value is set to true, will only count pixels that are not equal to the NODATA value.
PostGIS 3.3.2 Manual 641 / 902
Synopsis
bigint ST_CountAgg(setof raster rast, integer nband, boolean exclude_nodata_value, double precision sample_percent);
bigint ST_CountAgg(setof raster rast, integer nband, boolean exclude_nodata_value);
bigint ST_CountAgg(setof raster rast, boolean exclude_nodata_value);
Description
Returns the number of pixels in a given band of a set of rasters. If no band is specified nband defaults to 1.
If exclude_nodata_value is set to true, will only count pixels with value not equal to the NODATA value of the raster. Set
exclude_nodata_value to false to get count all pixels
By default will sample all pixels. To get faster response, set sample_percent to value between zero (0) and one (1)
Availability: 2.2.0
Examples
WITH foo AS (
SELECT
rast.rast
FROM (
SELECT ST_SetValue(
ST_SetValue(
ST_SetValue(
ST_AddBand(
ST_MakeEmptyRaster(10, 10, 10, 10, 2, 2, 0, 0,0)
, 1, '64BF', 0, 0
)
, 1, 1, 1, -10
)
, 1, 5, 4, 0
)
, 1, 5, 5, 3.14159
) AS rast
) AS rast
FULL JOIN (
SELECT generate_series(1, 10) AS id
) AS id
ON 1 = 1
)
SELECT
ST_CountAgg(rast, 1, TRUE)
FROM foo;
st_countagg
-------------
20
(1 row)
See Also
12.9.3 ST_Histogram
ST_Histogram — Returns a set of record summarizing a raster or raster coverage data distribution separate bin ranges. Number
of bins are autocomputed if not specified.
PostGIS 3.3.2 Manual 642 / 902
Synopsis
setof record ST_Histogram(raster rast, integer nband=1, boolean exclude_nodata_value=true, integer bins=autocomputed, dou-
ble precision[] width=NULL, boolean right=false);
setof record ST_Histogram(raster rast, integer nband, integer bins, double precision[] width=NULL, boolean right=false);
setof record ST_Histogram(raster rast, integer nband, boolean exclude_nodata_value, integer bins, boolean right);
setof record ST_Histogram(raster rast, integer nband, integer bins, boolean right);
Description
Returns set of records consisting of min, max, count, percent for a given raster band for each bin. If no band is specified nband
defaults to 1.
Note
By default only considers pixel values not equal to the nodata value . Set exclude_nodata_value to false to
get count all pixels.
width double precision[] width: an array indicating the width of each category/bin. If the number of bins is greater than the
number of widths, the widths are repeated.
Example: 9 bins, widths are [a, b, c] will have the output be [a, b, c, a, b, c, a, b, c]
bins integer Number of breakouts -- this is the number of records you’ll get back from the function if specified. If not specified
then the number of breakouts is autocomputed.
right boolean compute the histogram from the right rather than from the left (default). This changes the criteria for evaluating
a value x from [a, b) to (a, b]
Example: Single raster tile - compute histograms for bands 1, 2, 3 and autocompute bins
SELECT (stats).*
FROM (SELECT rid, ST_Histogram(rast, 2,6) As stats
FROM dummy_rast
WHERE rid=2) As foo;
-- Same as previous but we explicitly control the pixel value range of each bin.
SELECT (stats).*
FROM (SELECT rid, ST_Histogram(rast, 2,6,ARRAY[0.5,1,4,100,5]) As stats
FROM dummy_rast
WHERE rid=2) As foo;
See Also
12.9.4 ST_Quantile
ST_Quantile — Compute quantiles for a raster or raster table coverage in the context of the sample or population. Thus, a value
could be examined to be at the raster’s 25%, 50%, 75% percentile.
Synopsis
setof record ST_Quantile(raster rast, integer nband=1, boolean exclude_nodata_value=true, double precision[] quantiles=NULL);
setof record ST_Quantile(raster rast, double precision[] quantiles);
setof record ST_Quantile(raster rast, integer nband, double precision[] quantiles);
double precision ST_Quantile(raster rast, double precision quantile);
double precision ST_Quantile(raster rast, boolean exclude_nodata_value, double precision quantile=NULL);
double precision ST_Quantile(raster rast, integer nband, double precision quantile);
double precision ST_Quantile(raster rast, integer nband, boolean exclude_nodata_value, double precision quantile);
double precision ST_Quantile(raster rast, integer nband, double precision quantile);
Description
Compute quantiles for a raster or raster table coverage in the context of the sample or population. Thus, a value could be examined
to be at the raster’s 25%, 50%, 75% percentile.
PostGIS 3.3.2 Manual 644 / 902
Note
If exclude_nodata_value is set to false, will also count pixels with no data.
Examples
SELECT (pvq).*
FROM (SELECT ST_Quantile(rast, ARRAY[0.25,0.75]) As pvq
FROM dummy_rast WHERE rid=2) As foo
ORDER BY (pvq).quantile;
quantile | value
----------+-------
0.25 | 253
0.75 | 254
value
------
254
14 | 1 | 199
1 | 1 | 244
2 | 1 | 255
15 | 1 | 255
See Also
12.9.5 ST_SummaryStats
ST_SummaryStats — Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster band of a raster
or raster coverage. Band 1 is assumed is no band is specified.
Synopsis
Description
Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster band of a raster or raster coverage. If
no band is specified nband defaults to 1.
Note
By default only considers pixel values not equal to the nodata value. Set exclude_nodata_value to false to get
count of all pixels.
Note
By default will sample all pixels. To get faster response, set sample_percent to lower than 1
Changed: 3.1.0 ST_SummaryStats(rastertable, rastercolumn, ...) variants are removed. Use ST_SummaryStatsAgg instead.
Availability: 2.0.0
This example took 574ms on PostGIS windows 64-bit with all of Boston Buildings and aerial Tiles (tiles each 150x150 pixels ~
134,000 tiles), ~102,000 building records
WITH
-- our features of interest
feat AS (SELECT gid As building_id, geom_26986 As geom FROM buildings AS b
WHERE gid IN(100, 103,150)
),
-- clip band 2 of raster tiles to boundaries of builds
-- then get stats for these clipped regions
b_stats AS
(SELECT building_id, (stats).*
FROM (SELECT building_id, ST_SummaryStats(ST_Clip(rast,2,geom)) As stats
FROM aerials.boston
INNER JOIN feat
ON ST_Intersects(feat.geom,rast)
) As foo
)
-- finally summarize stats
SELECT building_id, SUM(count) As num_pixels
, MIN(min) As min_pval
, MAX(max) As max_pval
, SUM(mean*count)/SUM(count) As avg_pval
FROM b_stats
WHERE count > 0
GROUP BY building_id
ORDER BY building_id;
building_id | num_pixels | min_pval | max_pval | avg_pval
-------------+------------+----------+----------+------------------
100 | 1090 | 1 | 255 | 61.0697247706422
103 | 655 | 7 | 182 | 70.5038167938931
150 | 895 | 2 | 252 | 185.642458100559
-- For a table -- will get better speed if set sampling to less than 100%
-- Here we set to 25% and get a much faster answer
SELECT band, (stats).*
FROM (SELECT band, ST_SummaryStats('o_4_boston','rast', band,true,0.25) As stats
FROM generate_series(1,3) As band) As foo;
See Also
12.9.6 ST_SummaryStatsAgg
ST_SummaryStatsAgg — Aggregate. Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster
band of a set of raster. Band 1 is assumed is no band is specified.
Synopsis
summarystats ST_SummaryStatsAgg(setof raster rast, integer nband, boolean exclude_nodata_value, double precision sam-
ple_percent);
summarystats ST_SummaryStatsAgg(setof raster rast, boolean exclude_nodata_value, double precision sample_percent);
summarystats ST_SummaryStatsAgg(setof raster rast, integer nband, boolean exclude_nodata_value);
Description
Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster band of a raster or raster coverage. If
no band is specified nband defaults to 1.
Note
By default only considers pixel values not equal to the NODATA value. Set exclude_nodata_value to False to
get count of all pixels.
Note
By default will sample all pixels. To get faster response, set sample_percent to value between 0 and 1
Availability: 2.2.0
Examples
WITH foo AS (
SELECT
rast.rast
FROM (
SELECT ST_SetValue(
ST_SetValue(
ST_SetValue(
ST_AddBand(
ST_MakeEmptyRaster(10, 10, 10, 10, 2, 2, 0, 0,0)
, 1, '64BF', 0, 0
)
, 1, 1, 1, -10
)
, 1, 5, 4, 0
)
, 1, 5, 5, 3.14159
) AS rast
) AS rast
PostGIS 3.3.2 Manual 648 / 902
FULL JOIN (
SELECT generate_series(1, 10) AS id
) AS id
ON 1 = 1
)
SELECT
(stats).count,
round((stats).sum::numeric, 3),
round((stats).mean::numeric, 3),
round((stats).stddev::numeric, 3),
round((stats).min::numeric, 3),
round((stats).max::numeric, 3)
FROM (
SELECT
ST_SummaryStatsAgg(rast, 1, TRUE, 1) AS stats
FROM foo
) bar;
See Also
12.9.7 ST_ValueCount
ST_ValueCount — Returns a set of records containing a pixel band value and count of the number of pixels in a given band of
a raster (or a raster coverage) that have a given set of values. If no band is specified defaults to band 1. By default nodata value
pixels are not counted. and all other values in the pixel are output and pixel band values are rounded to the nearest integer.
Synopsis
record ST_ValueCount(setof raster rast, integer nband=1, boolean exclude_nodata_value=true, double precision[] searchval-
ues=NULL, double precision roundto=0, double precision OUT value, integer OUT count);
record ST_ValueCount(setof raster rast, integer nband, double precision[] searchvalues, double precision roundto=0, double
precision OUT value, integer OUT count);
record ST_ValueCount(setof raster rast, double precision[] searchvalues, double precision roundto=0, double precision OUT
value, integer OUT count);
bigint ST_ValueCount(setof raster rast, double precision searchvalue, double precision roundto=0);
bigint ST_ValueCount(setof raster rast, integer nband, boolean exclude_nodata_value, double precision searchvalue, double
precision roundto=0);
bigint ST_ValueCount(setof raster rast, integer nband, double precision searchvalue, double precision roundto=0);
setof record ST_ValueCount(text rastertable, text rastercolumn, integer nband=1, boolean exclude_nodata_value=true, double
precision[] searchvalues=NULL, double precision roundto=0, double precision OUT value, integer OUT count);
setof record ST_ValueCount(text rastertable, text rastercolumn, double precision[] searchvalues, double precision roundto=0,
double precision OUT value, integer OUT count);
setof record ST_ValueCount(text rastertable, text rastercolumn, integer nband, double precision[] searchvalues, double precision
roundto=0, double precision OUT value, integer OUT count);
bigintST_ValueCount(text rastertable, text rastercolumn, integer nband, boolean exclude_nodata_value, double precision search-
value, double precision roundto=0);
bigint ST_ValueCount(text rastertable, text rastercolumn, double precision searchvalue, double precision roundto=0);
bigint ST_ValueCount(text rastertable, text rastercolumn, integer nband, double precision searchvalue, double precision roundto=0);
PostGIS 3.3.2 Manual 649 / 902
Description
Returns a set of records with columns value count which contain the pixel band value and count of pixels in the raster tile or
raster coverage of selected band.
If no band is specified nband defaults to 1. If no searchvalues are specified, will return all pixel values found in the raster
or raster coverage. If one searchvalue is given, will return an integer instead of records denoting the count of pixels having that
pixel band value
Note
If exclude_nodata_value is set to false, will also count pixels with no data.
Availability: 2.0.0
Examples
SELECT (pvc).*
FROM (SELECT ST_ValueCount(rast) As pvc
FROM dummy_rast WHERE rid=2) As foo
ORDER BY (pvc).value;
value | count
-------+-------
250 | 2
251 | 1
252 | 2
253 | 6
254 | 12
value | count
-------+-------
249 | 2
250 | 2
251 | 1
252 | 2
253 | 6
254 | 12
89 | 1
96 | 1
97 | 1
98 | 1
99 | 2
112 | 2
:
--real live example. Count all the pixels in an aerial raster tile band 2 intersecting a ←-
geometry
-- and return only the pixel band values that have a count > 500
SELECT (pvc).value, SUM((pvc).count) As total
FROM (SELECT ST_ValueCount(rast,2) As pvc
FROM o_4_boston
WHERE ST_Intersects(rast,
ST_GeomFromText('POLYGON((224486 892151,224486 892200,224706 892200,224706 ←-
892151,224486 892151))',26986)
)
) As foo
GROUP BY (pvc).value
HAVING SUM((pvc).count) > 500
ORDER BY (pvc).value;
value | total
-------+-----
51 | 502
54 | 521
-- Just return count of pixels in each raster tile that have value of 100 of tiles that ←-
intersect a specific geometry --
SELECT rid, ST_ValueCount(rast,2,100) As count
FROM o_4_boston
WHERE ST_Intersects(rast,
ST_GeomFromText('POLYGON((224486 892151,224486 892200,224706 892200,224706 ←-
892151,224486 892151))',26986)
) ;
rid | count
-----+-------
1 | 56
2 | 95
14 | 37
15 | 64
See Also
ST_Count, ST_SetBandNoDataValue
12.10.1 ST_RastFromWKB
Synopsis
Description
Examples
SELECT (ST_Metadata(
ST_RastFromWKB(
'\001\000\000\000\000\000\000\000\000\000\000\000@\000\000\000\000\000\000\010@ ←-
\000\000\000\000\000\000\340?\000\000\000\000\000\000\340?\000\000\000\000\000\000\000\00
bytea
)
)).* AS metadata;
0.5 | 0.5 | 10 | 20 | 2 | 3 | 0 | 0 | 10 | ←-
0
See Also
12.10.2 ST_RastFromHexWKB
ST_RastFromHexWKB — Return a raster value from a Hex representation of Well-Known Binary (WKB) raster.
Synopsis
Description
Examples
SELECT (ST_Metadata(
ST_RastFromHexWKB(
'010000000000000000000000400000000000000840000000000000 ←-
E03F000000000000E03F000000000000000000000000000000000A0000000A001400'
)
)).* AS metadata;
PostGIS 3.3.2 Manual 652 / 902
0.5 | 0.5 | 10 | 20 | 2 | 3 | 0 | 0 | 10 | ←-
0
See Also
12.11.1 ST_AsBinary/ST_AsWKB
Synopsis
Description
Returns the Binary representation of the raster. If outasin is TRUE, out-db bands are treated as in-db. Refer to raster/doc/RFC2-
WellKnownBinaryFormat located in the PostGIS source folder for details of the representation.
This is useful in binary cursors to pull data out of the database without converting it to a string representation.
Note
By default, WKB output contains the external file path for out-db bands. If the client does not have access to the raster
file underlying an out-db band, set outasin to TRUE.
Examples
rastbin
---------------------------------------------------------------------------------
\001\000\000\000\000\000\000\000\000\000\000\000@\000\000\000\000\000\000\010@ ←-
\000\000\000\000\000\000\340?\000\000\000\000\000\000\340?\000\000\000\000\000\000\000\000\000\00
See Also
ST_RastFromWKB, ST_AsHexWKB
PostGIS 3.3.2 Manual 653 / 902
12.11.2 ST_AsHexWKB
ST_AsHexWKB — Return the Well-Known Binary (WKB) in Hex representation of the raster.
Synopsis
Description
Returns the Binary representation in Hex representation of the raster. If outasin is TRUE, out-db bands are treated as in-db.
Refer to raster/doc/RFC2-WellKnownBinaryFormat located in the PostGIS source folder for details of the representation.
Note
By default, Hex WKB output contains the external file path for out-db bands. If the client does not have access to the
raster file underlying an out-db band, set outasin to TRUE.
Availability: 2.5.0
Examples
st_ashexwkb
-----------------------------------------------------------------------------------------------------
010000000000000000000000400000000000000840000000000000 ←-
E03F000000000000E03F000000000000000000000000000000000A0000000A001400
See Also
ST_RastFromHexWKB, ST_AsBinary/ST_AsWKB
12.11.3 ST_AsGDALRaster
ST_AsGDALRaster — Return the raster tile in the designated GDAL Raster format. Raster formats are one of those supported
by your compiled library. Use ST_GDALDrivers() to get a list of formats supported by your library.
Synopsis
Description
Returns the raster tile in the designated format. Arguments are itemized below:
• format format to output. This is dependent on the drivers compiled in your libgdal library. Generally available are ’JPEG’,
’GTIff’, ’PNG’. Use ST_GDALDrivers to get a list of formats supported by your library.
• options text array of GDAL options. Valid options are dependent on the format. Refer to GDAL Raster format options for
more details.
• srs The proj4text or srtext (from spatial_ref_sys) to embed in the image
One way to export raster into another format is using PostgreSQL large object export functions. We’lll repeat the prior example
but also exporting. Note for this you’ll need to have super user access to db since it uses server side lo functions. It will also
export to path on server network. If you need export locally, use the psql equivalent lo_ functions which export to the local file
system instead of the server file system.
DROP TABLE IF EXISTS tmp_out ;
SELECT lo_unlink(loid)
FROM tmp_out;
See Also
12.11.4 ST_AsJPEG
ST_AsJPEG — Return the raster tile selected bands as a single Joint Photographic Exports Group (JPEG) image (byte array). If
no band is specified and 1 or more than 3 bands, then only the first band is used. If only 3 bands then all 3 bands are used and
mapped to RGB.
Synopsis
Description
Returns the selected bands of the raster as a single Joint Photographic Exports Group Image (JPEG). Use ST_AsGDALRaster if
you need to export as less common raster types. If no band is specified and 1 or more than 3 bands, then only the first band is
used. If 3 bands then all 3 bands are used. There are many variants of the function with many options. These are itemized below:
• nbands is an array of bands to export (note that max is 3 for JPEG) and the order of the bands is RGB. e.g ARRAY[3,2,1]
means map band 3 to Red, band 2 to green and band 1 to blue
• quality number from 0 to 100. The higher the number the crisper the image.
• options text Array of GDAL options as defined for JPEG (look at create_options for JPEG ST_GDALDrivers). For JPEG
valid ones are PROGRESSIVE ON or OFF and QUALITY a range from 0 to 100 and default to 75. Refer to GDAL Raster
format options for more details.
Examples: Output
-- output first 3 bands (but make band 2 Red, band 1 green, and band 3 blue, progressive ←-
and 90% quality
SELECT ST_AsJPEG(rast,ARRAY[2,1,3],ARRAY['QUALITY=90','PROGRESSIVE=ON']) As rastjpg
FROM dummy_rast WHERE rid=2;
See Also
12.11.5 ST_AsPNG
ST_AsPNG — Return the raster tile selected bands as a single portable network graphics (PNG) image (byte array). If 1, 3, or 4
bands in raster and no bands are specified, then all bands are used. If more 2 or more than 4 bands and no bands specified, then
only band 1 is used. Bands are mapped to RGB or RGBA space.
Synopsis
Description
Returns the selected bands of the raster as a single Portable Network Graphics Image (PNG). Use ST_AsGDALRaster if you
need to export as less common raster types. If no band is specified, then the first 3 bands are exported. There are many variants
of the function with many options. If no srid is specified then then srid of the raster is used. These are itemized below:
• nbands is an array of bands to export (note that max is 4 for PNG) and the order of the bands is RGBA. e.g ARRAY[3,2,1]
means map band 3 to Red, band 2 to green and band 1 to blue
• compression number from 1 to 9. The higher the number the greater the compression.
• options text Array of GDAL options as defined for PNG (look at create_options for PNG of ST_GDALDrivers). For PNG
valid one is only ZLEVEL (amount of time to spend on compression -- default 6) e.g. ARRAY[’ZLEVEL=9’]. WORLDFILE
is not allowed since the function would have to output two outputs. Refer to GDAL Raster format options for more details.
Examples
-- export the first 3 bands and map band 3 to Red, band 1 to Green, band 2 to blue
SELECT ST_AsPNG(rast, ARRAY[3,1,2]) As rastpng
FROM dummy_rast WHERE rid=2;
See Also
12.11.6 ST_AsTIFF
ST_AsTIFF — Return the raster selected bands as a single TIFF image (byte array). If no band is specified or any of specified
bands does not exist in the raster, then will try to use all bands.
Synopsis
Description
Returns the selected bands of the raster as a single Tagged Image File Format (TIFF). If no band is specified, will try to use all
bands. This is a wrapper around ST_AsGDALRaster. Use ST_AsGDALRaster if you need to export as less common raster types.
There are many variants of the function with many options. If no spatial reference SRS text is present, the spatial reference of
the raster is used. These are itemized below:
• nbands is an array of bands to export (note that max is 3 for PNG) and the order of the bands is RGB. e.g ARRAY[3,2,1]
means map band 3 to Red, band 2 to green and band 1 to blue
PostGIS 3.3.2 Manual 657 / 902
• compression Compression expression -- JPEG90 (or some other percent), LZW, JPEG, DEFLATE9.
• options text Array of GDAL create options as defined for GTiff (look at create_options for GTiff of ST_GDALDrivers). or
refer to GDAL Raster format options for more details.
• srid srid of spatial_ref_sys of the raster. This is used to populate the georeference information
See Also
12.12.1 ST_Clip
ST_Clip — Returns the raster clipped by the input geometry. If band number not is specified, all bands are processed. If crop
is not specified or TRUE, the output raster is cropped.
Synopsis
raster ST_Clip(raster rast, integer[] nband, geometry geom, double precision[] nodataval=NULL, boolean crop=TRUE);
raster ST_Clip(raster rast, integer nband, geometry geom, double precision nodataval, boolean crop=TRUE);
raster ST_Clip(raster rast, integer nband, geometry geom, boolean crop);
raster ST_Clip(raster rast, geometry geom, double precision[] nodataval=NULL, boolean crop=TRUE);
raster ST_Clip(raster rast, geometry geom, double precision nodataval, boolean crop=TRUE);
raster ST_Clip(raster rast, geometry geom, boolean crop);
Description
Returns a raster that is clipped by the input geometry geom. If band index is not specified, all bands are processed.
Rasters resulting from ST_Clip must have a nodata value assigned for areas clipped, one for each band. If none are provided and
the input raster do not have a nodata value defined, nodata values of the resulting raster are set to ST_MinPossibleValue(ST_BandPixelTyp
band)). When the number of nodata value in the array is smaller than the number of band, the last one in the array is used for
the remaining bands. If the number of nodata value is greater than the number of band, the extra nodata values are ignored. All
variants accepting an array of nodata values also accept a single value which will be assigned to each band.
If crop is not specified, true is assumed meaning the output raster is cropped to the intersection of the geomand rast extents.
If crop is set to false, the new raster gets the same extent as rast.
Availability: 2.0.0
Enhanced: 2.1.0 Rewritten in C
Examples here use Massachusetts aerial data available on MassGIS site MassGIS Aerial Orthos. Coordinates are in Mas-
sachusetts State Plane Meters.
PostGIS 3.3.2 Manual 658 / 902
Examples: 1 band clipping with no crop and add back other bands unchanged
-- Same example as before, but we need to set crop to false to be able to use ST_AddBand
-- because ST_AddBand requires all bands be the same Width and height
SELECT ST_AddBand(ST_Clip(rast, 1,
ST_Buffer(ST_Centroid(ST_Envelope(rast)),20),false
), ARRAY[ST_Band(rast,2),ST_Band(rast,3)] ) from aerials.boston
WHERE rid = 6;
PostGIS 3.3.2 Manual 659 / 902
See Also
12.12.2 ST_ColorMap
ST_ColorMap — Creates a new raster of up to four 8BUI bands (grayscale, RGB, RGBA) from the source raster and a specified
band. Band 1 is assumed if not specified.
Synopsis
Description
Apply a colormap to the band at nband of rast resulting a new raster comprised of up to four 8BUI bands. The number of
8BUI bands in the new raster is determined by the number of color components defined in colormap.
If nband is not specified, then band 1 is assumed.
colormap can be a keyword of a pre-defined colormap or a set of lines defining the value and the color components.
Valid pre-defined colormap keyword:
• fire for a four 8BUI (RGBA) band raster with colors going from black to red to pale yellow.
• bluered for a four 8BUI (RGBA) band raster with colors going from blue to pale white to red.
Users can pass a set of entries (one per line) to colormap to specify custom colormaps. Each entry generally consists of five
values: the pixel value and corresponding Red, Green, Blue, Alpha components (color components between 0 and 255). Percent
values can be used instead of pixel values where 0% and 100% are the minimum and maximum values found in the raster band.
Values can be separated with commas (’,’), tabs, colons (’:’) and/or spaces. The pixel value can be set to nv, null or nodata for
the NODATA value. An example is provided below.
5 0 0 0 255
4 100:50 55 255
1 150,100 150 255
0% 255 255 255 255
nv 0 0 0 0
The syntax of colormap is similar to that of the color-relief mode of GDAL gdaldem.
Valid keywords for method:
• INTERPOLATE to use linear interpolation to smoothly blend the colors between the given pixel values
• EXACT to strictly match only those pixels values found in the colormap. Pixels whose value does not match a colormap entry
will be set to 0 0 0 0 (RGBA)
• NEAREST to use the colormap entry whose value is closest to the pixel value
Note
A great reference for colormaps is ColorBrewer.
PostGIS 3.3.2 Manual 661 / 902
Warning
The resulting bands of new raster will have no NODATA value set. Use ST_SetBandNoDataValue to set a NODATA
value if one is needed.
Availability: 2.1.0
Examples
SELECT
ST_NumBands(rast) As n_orig,
ST_NumBands(ST_ColorMap(rast,1, 'greyscale')) As ngrey,
ST_NumBands(ST_ColorMap(rast,1, 'pseudocolor')) As npseudo,
ST_NumBands(ST_ColorMap(rast,1, 'fire')) As nfire,
ST_NumBands(ST_ColorMap(rast,1, 'bluered')) As nbluered,
ST_NumBands(ST_ColorMap(rast,1, '
100% 255 0 0
80% 160 0 0
50% 130 0 0
30% 30 0 0
20% 60 0 0
0% 0 0 0
nv 255 255 255
')) As nred
FROM funky_shapes;
SELECT
ST_AsPNG(rast) As orig_png,
ST_AsPNG(ST_ColorMap(rast,1,'greyscale')) As grey_png,
ST_AsPNG(ST_ColorMap(rast,1, 'pseudocolor')) As pseudo_png,
ST_AsPNG(ST_ColorMap(rast,1, 'nfire')) As fire_png,
ST_AsPNG(ST_ColorMap(rast,1, 'bluered')) As bluered_png,
ST_AsPNG(ST_ColorMap(rast,1, '
100% 255 0 0
80% 160 0 0
50% 130 0 0
30% 30 0 0
20% 60 0 0
0% 0 0 0
nv 255 255 255
')) As red_png
FROM funky_shapes;
See Also
ST_AsPNG, ST_AsRaster ST_MapAlgebra (callback function version), ST_Grayscale ST_NumBands, ST_Reclass, ST_SetBandNoDat
ST_Union
12.12.3 ST_Grayscale
ST_Grayscale — Creates a new one-8BUI band raster from the source raster and specified bands representing Red, Green and
Blue
Synopsis
(1) raster ST_Grayscale(raster rast, integer redband=1, integer greenband=2, integer blueband=3, text extenttype=INTERSECTION);
(2) raster ST_Grayscale(rastbandarg[] rastbandargset, text extenttype=INTERSECTION);
Description
Create a raster with one 8BUI band given three input bands (from one or more rasters). Any input band whose pixel type is not
8BUI will be reclassified using ST_Reclass.
Note
This function is not like ST_ColorMap with the grayscale keyword as ST_ColorMap operates on only one band
while this function expects three bands for RGB. This function applies the following equation for converting RGB to
Grayscale: 0.2989 * RED + 0.5870 * GREEN + 0.1140 * BLUE
Availability: 2.5.0
PostGIS 3.3.2 Manual 664 / 902
Examples: Variant 1
WITH apple AS (
SELECT ST_AddBand(
ST_MakeEmptyRaster(350, 246, 0, 0, 1, -1, 0, 0, 0),
'/tmp/apple.png'::text,
NULL::int[]
) AS rast
)
SELECT
ST_AsPNG(rast) AS original_png,
ST_AsPNG(ST_Grayscale(rast)) AS grayscale_png
FROM apple;
original_png grayscale_png
Examples: Variant 2
WITH apple AS (
SELECT ST_AddBand(
ST_MakeEmptyRaster(350, 246, 0, 0, 1, -1, 0, 0, 0),
'/tmp/apple.png'::text,
NULL::int[]
) AS rast
)
SELECT
ST_AsPNG(rast) AS original_png,
ST_AsPNG(ST_Grayscale(
ARRAY[
ROW(rast, 1)::rastbandarg, -- red
ROW(rast, 2)::rastbandarg, -- green
ROW(rast, 3)::rastbandarg, -- blue
]::rastbandarg[]
)) AS grayscale_png
FROM apple;
PostGIS 3.3.2 Manual 665 / 902
See Also
12.12.4 ST_Intersection
ST_Intersection — Returns a raster or a set of geometry-pixelvalue pairs representing the shared portion of two rasters or the
geometrical intersection of a vectorization of the raster and a geometry.
Synopsis
Description
Returns a raster or a set of geometry-pixelvalue pairs representing the shared portion of two rasters or the geometrical intersection
of a vectorization of the raster and a geometry.
The first three variants, returning a setof geomval, works in vector space. The raster is first vectorized (using ST_DumpAsPolygons)
into a set of geomval rows and those rows are then intersected with the geometry using the ST_Intersection (geometry, geom-
etry) PostGIS function. Geometries intersecting only with a nodata value area of a raster returns an empty geometry. They are
normally excluded from the results by the proper usage of ST_Intersects in the WHERE clause.
You can access the geometry and the value parts of the resulting set of geomval by surrounding them with parenthesis and adding
’.geom’ or ’.val’ at the end of the expression. e.g. (ST_Intersection(rast, geom)).geom
The other variants, returning a raster, works in raster space. They are using the two rasters version of ST_MapAlgebraExpr to
perform the intersection.
The extent of the resulting raster corresponds to the geometrical intersection of the two raster extents. The resulting raster
includes ’BAND1’, ’BAND2’ or ’BOTH’ bands, following what is passed as the returnband parameter. Nodata value areas
present in any band results in nodata value areas in every bands of the result. In other words, any pixel intersecting with a nodata
value pixel becomes a nodata value pixel in the result.
Rasters resulting from ST_Intersection must have a nodata value assigned for areas not intersecting. You can define or replace the
nodata value for any resulting band by providing a nodataval[] array of one or two nodata values depending if you request
’BAND1’, ’BAND2’ or ’BOTH’ bands. The first value in the array replace the nodata value in the first band and the second value
replace the nodata value in the second band. If one input band do not have a nodata value defined and none are provided as an
array, one is chosen using the ST_MinPossibleValue function. All variant accepting an array of nodata value can also accept a
single value which will be assigned to each requested band.
In all variants, if no band number is specified band 1 is assumed. If you need an intersection between a raster and geometry that
returns a raster, refer to ST_Clip.
Note
To get more control on the resulting extent or on what to return when encountering a nodata value, use the two rasters
version of ST_MapAlgebraExpr.
PostGIS 3.3.2 Manual 666 / 902
Note
To compute the intersection of a raster band with a geometry in raster space, use ST_Clip. ST_Clip works on multiple
bands rasters and does not return a band corresponding to the rasterized geometry.
Note
ST_Intersection should be used in conjunction with ST_Intersects and an index on the raster column and/or the geom-
etry column.
Enhanced: 2.0.0 - Intersection in the raster space was introduced. In earlier pre-2.0.0 versions, only intersection performed in
vector space were supported.
SELECT
foo.rid,
foo.gid,
ST_AsText((foo.geomval).geom) As geomwkt,
(foo.geomval).val
FROM (
SELECT
A.rid,
g.gid,
ST_Intersection(A.rast, g.geom) As geomval
FROM dummy_rast AS A
CROSS JOIN (
VALUES
(1, ST_Point(3427928, 5793243.85) ),
(2, ST_GeomFromText('LINESTRING(3427927.85 5793243.75,3427927.8 ←-
5793243.75,3427927.8 5793243.8)')),
(3, ST_GeomFromText('LINESTRING(1 2, 3 4)'))
) As g(gid,geom)
WHERE A.rid = 2
) As foo;
See Also
ST_MapAlgebra (callback function version) — Callback function version - Returns a one-band raster given one or more input
rasters, band indexes and one user-specified callback function.
PostGIS 3.3.2 Manual 667 / 902
Synopsis
Description
Returns a one-band raster given one or more input rasters, band indexes and one user-specified callback function.
callbackfunc The callbackfunc parameter must be the name and signature of an SQL or PL/pgSQL function, cast to a
regprocedure. An example PL/pgSQL function example is:
CREATE OR REPLACE FUNCTION sample_callbackfunc(value double precision[][][], position ←-
integer[][], VARIADIC userargs text[])
RETURNS double precision
AS $$
BEGIN
RETURN 0;
END;
$$ LANGUAGE 'plpgsql' IMMUTABLE;
The callbackfunc must have three arguments: a 3-dimension double precision array, a 2-dimension integer array and a
variadic 1-dimension text array. The first argument value is the set of values (as double precision) from all input rasters.
The three dimensions (where indexes are 1-based) are: raster #, row y, column x. The second argument position is
the set of pixel positions from the output raster and input rasters. The outer dimension (where indexes are 0-based) is the
raster #. The position at outer dimension index 0 is the output raster’s pixel position. For each outer dimension, there are
two elements in the inner dimension for X and Y. The third argument userargs is for passing through any user-specified
arguments.
Passing a regprocedure argument to a SQL function requires the full function signature to be passed, then cast to a regpro-
cedure type. To pass the above example PL/pgSQL function as an argument, the SQL for the argument is:
'sample_callbackfunc(double precision[], integer[], text[])'::regprocedure
Note that the argument contains the name of the function, the types of the function arguments, quotes around the name and
argument types, and a cast to a regprocedure.
mask An n-dimensional array (matrix) of numbers used to filter what cells get passed to map algebra call-back function. 0
means a neighbor cell value should be treated as no-data and 1 means value should be treated as data. If weight is set to
true, then the values, are used as multipliers to multiple the pixel value of that value in the neighborhood position.
weighted boolean (true/false) to denote if a mask value should be weighted (multiplied by original value) or not (only applies to
proto that takes a mask).
PostGIS 3.3.2 Manual 668 / 902
pixeltype If pixeltype is passed in, the one band of the new raster will be of that pixeltype. If pixeltype is passed NULL
or left out, the new raster band will have the same pixeltype as the specified band of the first raster (for extent types:
INTERSECTION, UNION, FIRST, CUSTOM) or the specified band of the appropriate raster (for extent types: SECOND,
LAST). If in doubt, always specify pixeltype.
The resulting pixel type of the output raster must be one listed in ST_BandPixelType or left out or set to NULL.
extenttype Possible values are INTERSECTION (default), UNION, FIRST (default for one raster variants), SECOND, LAST,
CUSTOM.
customextent If extentype is CUSTOM, a raster must be provided for customextent. See example 4 of Variant 1.
distancex The distance in pixels from the reference cell in x direction. So width of resulting matrix would be 2*distancex
+ 1.If not specified only the reference cell is considered (neighborhood of 0).
distancey The distance in pixels from reference cell in y direction. Height of resulting matrix would be 2*distancey + 1
.If not specified only the reference cell is considered (neighborhood of 0).
userargs The third argument to the callbackfunc is a variadic text array. All trailing text arguments are passed through to
the specified callbackfunc, and are contained in the userargs argument.
Note
For more information about the VARIADIC keyword, please refer to the PostgreSQL documentation and the "SQL
Functions with Variable Numbers of Arguments" section of Query Language (SQL) Functions.
Note
The text[] argument to the callbackfunc is required, regardless of whether you choose to pass any arguments to
the callback function for processing or not.
Variant 1 accepts an array of rastbandarg allowing the use of a map algebra operation on many rasters and/or many bands.
See example Variant 1.
Variants 2 and 3 operate upon one or more bands of one raster. See example Variant 2 and 3.
Variant 4 operate upon two rasters with one band per raster. See example Variant 4.
Availability: 2.2.0: Ability to add a mask
Availability: 2.1.0
Examples: Variant 1
WITH foo AS (
SELECT 1 AS rid, ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 0, 1, -1, ←-
0, 0, 0), 1, '16BUI', 1, 0), 2, '8BUI', 10, 0), 3, '32BUI', 100, 0) AS rast
)
SELECT
ST_MapAlgebra(
ARRAY[ROW(rast, 3), ROW(rast, 1), ROW(rast, 3), ROW(rast, 2)]::rastbandarg[],
'sample_callbackfunc(double precision[], int[], text[])'::regprocedure
) AS rast
FROM foo
Complete example of tiles of a coverage with neighborhood. This query only works with PostgreSQL 9.1 or higher.
WITH foo AS (
SELECT 0 AS rid, ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 0, 1, -1, 0, 0, 0), 1, '16BUI', ←-
1, 0) AS rast UNION ALL
SELECT 1, ST_AddBand(ST_MakeEmptyRaster(2, 2, 2, 0, 1, -1, 0, 0, 0), 1, '16BUI', 2, 0) ←-
AS rast UNION ALL
SELECT 2, ST_AddBand(ST_MakeEmptyRaster(2, 2, 4, 0, 1, -1, 0, 0, 0), 1, '16BUI', 3, 0) ←-
AS rast UNION ALL
'CUSTOM', t1.rast,
1, 1
) AS rast
FROM foo t1
CROSS JOIN foo t2
WHERE t1.rid = 4
AND t2.rid BETWEEN 0 AND 8
AND ST_Intersects(t1.rast, t2.rast)
GROUP BY t1.rid, t1.rast
Example like the prior one for tiles of a coverage with neighborhood but works with PostgreSQL 9.0.
WITH src AS (
SELECT 0 AS rid, ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 0, 1, -1, 0, 0, 0), 1, '16BUI', ←-
1, 0) AS rast UNION ALL
SELECT 1, ST_AddBand(ST_MakeEmptyRaster(2, 2, 2, 0, 1, -1, 0, 0, 0), 1, '16BUI', 2, 0) ←-
AS rast UNION ALL
SELECT 2, ST_AddBand(ST_MakeEmptyRaster(2, 2, 4, 0, 1, -1, 0, 0, 0), 1, '16BUI', 3, 0) ←-
AS rast UNION ALL
ST_Value(rast, 1, 1, 1)
FROM bar;
Examples: Variant 4
UNION ALL
SELECT 'mask weighted only consider neighbors, exclude center multi otehr pixel values by ←-
2' AS title, ST_MapAlgebra(rast,1,'ST_mean4ma(double precision[], int[], text[])':: ←-
regprocedure,
'{{2,2,2}, {2,0,2}, {2,2,2}}'::double precision[], true) As rast
FROM foo;
See Also
ST_MapAlgebra (expression version) — Expression version - Returns a one-band raster given one or two input rasters, band
indexes and one or more user-specified SQL expressions.
Synopsis
raster ST_MapAlgebra(raster rast, integer nband, text pixeltype, text expression, double precision nodataval=NULL);
raster ST_MapAlgebra(raster rast, text pixeltype, text expression, double precision nodataval=NULL);
raster ST_MapAlgebra(raster rast1, integer nband1, raster rast2, integer nband2, text expression, text pixeltype=NULL, text
extenttype=INTERSECTION, text nodata1expr=NULL, text nodata2expr=NULL, double precision nodatanodataval=NULL);
raster ST_MapAlgebra(raster rast1, raster rast2, text expression, text pixeltype=NULL, text extenttype=INTERSECTION, text
nodata1expr=NULL, text nodata2expr=NULL, double precision nodatanodataval=NULL);
Description
Expression version - Returns a one-band raster given one or two input rasters, band indexes and one or more user-specified SQL
expressions.
Availability: 2.1.0
Creates a new one band raster formed by applying a valid PostgreSQL algebraic operation defined by the expression on the
input raster (rast). If nband is not provided, band 1 is assumed. The new raster will have the same georeference, width, and
height as the original raster but will only have one band.
If pixeltype is passed in, then the new raster will have a band of that pixeltype. If pixeltype is passed NULL, then the new
raster band will have the same pixeltype as the input rast band.
PostGIS 3.3.2 Manual 674 / 902
Creates a new one band raster formed by applying a valid PostgreSQL algebraic operation to the two bands defined by the
expression on the two input raster bands rast1, (rast2). If no band1, band2 is specified band 1 is assumed. The
resulting raster will be aligned (scale, skew and pixel corners) on the grid defined by the first raster. The resulting raster will have
the extent defined by the extenttype parameter.
expression A PostgreSQL algebraic expression involving the two rasters and PostgreSQL defined functions/operators that will
define the pixel value when pixels intersect. e.g. (([rast1] + [rast2])/2.0)::integer
pixeltype The resulting pixel type of the output raster. Must be one listed in ST_BandPixelType, left out or set to NULL. If not
passed in or set to NULL, will default to the pixeltype of the first raster.
extenttype Controls the extent of resulting raster
1. INTERSECTION - The extent of the new raster is the intersection of the two rasters. This is the default.
2. UNION - The extent of the new raster is the union of the two rasters.
3. FIRST - The extent of the new raster is the same as the one of the first raster.
4. SECOND - The extent of the new raster is the same as the one of the second raster.
nodata1expr An algebraic expression involving only rast2 or a constant that defines what to return when pixels of rast1
are nodata values and spatially corresponding rast2 pixels have values.
nodata2expr An algebraic expression involving only rast1 or a constant that defines what to return when pixels of rast2
are nodata values and spatially corresponding rast1 pixels have values.
nodatanodataval A numeric constant to return when spatially corresponding rast1 and rast2 pixels are both nodata values.
WITH foo AS (
SELECT ST_AddBand(ST_MakeEmptyRaster(10, 10, 0, 0, 1, 1, 0, 0, 0), '32BF'::text, 1, -1) ←-
AS rast
)
SELECT
ST_MapAlgebra(rast, 1, NULL, 'ceil([rast]*[rast.x]/[rast.y]+[rast.val])')
FROM foo;
PostGIS 3.3.2 Manual 675 / 902
WITH foo AS (
SELECT 1 AS rid, ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 0, 1, -1, ←-
0, 0, 0), 1, '16BUI', 1, 0), 2, '8BUI', 10, 0), 3, '32BUI'::text, 100, 0) AS rast ←-
UNION ALL
SELECT 2 AS rid, ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 1, 1, -1, ←-
0, 0, 0), 1, '16BUI', 2, 0), 2, '8BUI', 20, 0), 3, '32BUI'::text, 300, 0) AS rast
)
SELECT
ST_MapAlgebra(
t1.rast, 2,
t2.rast, 1,
'([rast2] + [rast1.val]) / 2'
) AS rast
FROM foo t1
CROSS JOIN foo t2
WHERE t1.rid = 1
AND t2.rid = 2;
See Also
12.12.7 ST_MapAlgebraExpr
ST_MapAlgebraExpr — 1 raster band version: Creates a new one band raster formed by applying a valid PostgreSQL algebraic
operation on the input raster band and of pixeltype provided. Band 1 is assumed if no band is specified.
Synopsis
raster ST_MapAlgebraExpr(raster rast, integer band, text pixeltype, text expression, double precision nodataval=NULL);
raster ST_MapAlgebraExpr(raster rast, text pixeltype, text expression, double precision nodataval=NULL);
Description
Warning
ST_MapAlgebraExpr is deprecated as of 2.1.0. Use ST_MapAlgebra (expression version) instead.
Creates a new one band raster formed by applying a valid PostgreSQL algebraic operation defined by the expression on the
input raster (rast). If no band is specified band 1 is assumed. The new raster will have the same georeference, width, and
height as the original raster but will only have one band.
If pixeltype is passed in, then the new raster will have a band of that pixeltype. If pixeltype is passed NULL, then the new
raster band will have the same pixeltype as the input rast band.
In the expression you can use the term [rast] to refer to the pixel value of the original band, [rast.x] to refer to the 1-based
pixel column index, [rast.y] to refer to the 1-based pixel row index.
Availability: 2.0.0
PostGIS 3.3.2 Manual 676 / 902
Examples
Create a new 1 band raster from our original that is a function of modulo 2 of the original raster band.
ALTER TABLE dummy_rast ADD COLUMN map_rast raster;
UPDATE dummy_rast SET map_rast = ST_MapAlgebraExpr(rast,NULL,'mod([rast]::numeric,2)') ←-
WHERE rid = 2;
SELECT
ST_Value(rast,1,i,j) As origval,
ST_Value(map_rast, 1, i, j) As mapval
FROM dummy_rast
CROSS JOIN generate_series(1, 3) AS i
CROSS JOIN generate_series(1,3) AS j
WHERE rid = 2;
origval | mapval
---------+--------
253 | 1
254 | 0
253 | 1
253 | 1
254 | 0
254 | 0
250 | 0
254 | 0
254 | 0
Create a new 1 band raster of pixel-type 2BUI from our original that is reclassified and set the nodata value to be 0.
ALTER TABLE dummy_rast ADD COLUMN map_rast2 raster;
UPDATE dummy_rast SET
map_rast2 = ST_MapAlgebraExpr(rast,'2BUI'::text,'CASE WHEN [rast] BETWEEN 100 and 250 ←-
THEN 1 WHEN [rast] = 252 THEN 2 WHEN [rast] BETWEEN 253 and 254 THEN 3 ELSE 0 END':: ←-
text, '0')
WHERE rid = 2;
SELECT DISTINCT
ST_Value(rast,1,i,j) As origval,
ST_Value(map_rast2, 1, i, j) As mapval
FROM dummy_rast
CROSS JOIN generate_series(1, 5) AS i
CROSS JOIN generate_series(1,5) AS j
WHERE rid = 2;
origval | mapval
---------+--------
249 | 1
250 | 1
251 |
252 | 2
253 | 3
254 | 3
SELECT
ST_BandPixelType(map_rast2) As b1pixtyp
FROM dummy_rast
WHERE rid = 2;
b1pixtyp
----------
2BUI
PostGIS 3.3.2 Manual 677 / 902
Create a new 3 band raster same pixel type from our original 3 band raster with first band altered by map algebra and remaining
2 bands unaltered.
SELECT
ST_AddBand(
ST_AddBand(
ST_AddBand(
ST_MakeEmptyRaster(rast_view),
ST_MapAlgebraExpr(rast_view,1,NULL,'tan([rast])*[rast]')
),
ST_Band(rast_view,2)
),
ST_Band(rast_view, 3)
) As rast_view_ma
FROM wind
WHERE rid=167;
See Also
12.12.8 ST_MapAlgebraExpr
ST_MapAlgebraExpr — 2 raster band version: Creates a new one band raster formed by applying a valid PostgreSQL algebraic
operation on the two input raster bands and of pixeltype provided. band 1 of each raster is assumed if no band numbers are
specified. The resulting raster will be aligned (scale, skew and pixel corners) on the grid defined by the first raster and have its
extent defined by the "extenttype" parameter. Values for "extenttype" can be: INTERSECTION, UNION, FIRST, SECOND.
Synopsis
raster ST_MapAlgebraExpr(raster rast1, raster rast2, text expression, text pixeltype=same_as_rast1_band, text extenttype=INTERSECT
text nodata1expr=NULL, text nodata2expr=NULL, double precision nodatanodataval=NULL);
raster ST_MapAlgebraExpr(raster rast1, integer band1, raster rast2, integer band2, text expression, text pixeltype=same_as_rast1_band,
text extenttype=INTERSECTION, text nodata1expr=NULL, text nodata2expr=NULL, double precision nodatanodataval=NULL);
PostGIS 3.3.2 Manual 678 / 902
Description
Warning
ST_MapAlgebraExpr is deprecated as of 2.1.0. Use ST_MapAlgebra (expression version) instead.
Creates a new one band raster formed by applying a valid PostgreSQL algebraic operation to the two bands defined by the
expression on the two input raster bands rast1, (rast2). If no band1, band2 is specified band 1 is assumed. The
resulting raster will be aligned (scale, skew and pixel corners) on the grid defined by the first raster. The resulting raster will have
the extent defined by the extenttype parameter.
expression A PostgreSQL algebraic expression involving the two rasters and PostgreSQL defined functions/operators that will
define the pixel value when pixels intersect. e.g. (([rast1] + [rast2])/2.0)::integer
pixeltype The resulting pixel type of the output raster. Must be one listed in ST_BandPixelType, left out or set to NULL. If not
passed in or set to NULL, will default to the pixeltype of the first raster.
extenttype Controls the extent of resulting raster
1. INTERSECTION - The extent of the new raster is the intersection of the two rasters. This is the default.
2. UNION - The extent of the new raster is the union of the two rasters.
3. FIRST - The extent of the new raster is the same as the one of the first raster.
4. SECOND - The extent of the new raster is the same as the one of the second raster.
nodata1expr An algebraic expression involving only rast2 or a constant that defines what to return when pixels of rast1
are nodata values and spatially corresponding rast2 pixels have values.
nodata2expr An algebraic expression involving only rast1 or a constant that defines what to return when pixels of rast2
are nodata values and spatially corresponding rast1 pixels have values.
nodatanodataval A numeric constant to return when spatially corresponding rast1 and rast2 pixels are both nodata values.
If pixeltype is passed in, then the new raster will have a band of that pixeltype. If pixeltype is passed NULL or no pixel type
specified, then the new raster band will have the same pixeltype as the input rast1 band.
Use the term [rast1.val] [rast2.val] to refer to the pixel value of the original raster bands and [rast1.x], [rast1.y]
etc. to refer to the column / row positions of the pixels.
Availability: 2.0.0
Create a new 1 band raster from our original that is a function of modulo 2 of the original raster band.
--Create a cool set of rasters --
DROP TABLE IF EXISTS fun_shapes;
CREATE TABLE fun_shapes(rid serial PRIMARY KEY, fun_name text, rast raster);
-- Insert some cool shapes around Boston in Massachusetts state plane meters --
INSERT INTO fun_shapes(fun_name, rast)
VALUES ('ref', ST_AsRaster(ST_MakeEnvelope(235229, 899970, 237229, 901930,26986),200,200,'8 ←-
BUI',0,0));
--map them -
SELECT ST_MapAlgebraExpr(
area.rast, bub.rast, '[rast2.val]', '8BUI', 'INTERSECTION', '[rast2.val]', '[rast1. ←-
val]') As interrast,
ST_MapAlgebraExpr(
area.rast, bub.rast, '[rast2.val]', '8BUI', 'UNION', '[rast2.val]', '[rast1.val ←-
]') As unionrast
FROM
(SELECT rast FROM fun_shapes WHERE
fun_name = 'area') As area
CROSS JOIN (SELECT rast
FROM fun_shapes WHERE
fun_name = 'rand bubbles') As bub
mapalgebra intersection
-- we use ST_AsPNG to render the image so all single band ones look grey --
WITH mygeoms
AS ( SELECT 2 As bnum, ST_Buffer(ST_Point(1,5),10) As geom
UNION ALL
SELECT 3 AS bnum,
ST_Buffer(ST_GeomFromText('LINESTRING(50 50,150 150,150 50)'), 10,'join= ←-
bevel') As geom
UNION ALL
PostGIS 3.3.2 Manual 680 / 902
SELECT 1 As bnum,
ST_Buffer(ST_GeomFromText('LINESTRING(60 50,150 150,150 50)'), 5,'join= ←-
bevel') As geom
),
-- define our canvas to be 1 to 1 pixel to geometry
canvas
AS (SELECT ST_AddBand(ST_MakeEmptyRaster(200,
200,
ST_XMin(e)::integer, ST_YMax(e)::integer, 1, -1, 0, 0) , '8BUI'::text,0) As rast
FROM (SELECT ST_Extent(geom) As e,
Max(ST_SRID(geom)) As srid
from mygeoms
) As foo
),
rbands AS (SELECT ARRAY(SELECT ST_MapAlgebraExpr(canvas.rast, ST_AsRaster(m.geom, canvas ←-
.rast, '8BUI', 100),
'[rast2.val]', '8BUI', 'FIRST', '[rast2.val]', '[rast1.val]') As rast
FROM mygeoms AS m CROSS JOIN canvas
ORDER BY m.bnum) As rasts
)
SELECT rasts[1] As rast1 , rasts[2] As rast2, rasts[3] As rast3, ST_AddBand(
ST_AddBand(rasts[1],rasts[2]), rasts[3]) As final_rast
FROM rbands;
rast1 rast2
PostGIS 3.3.2 Manual 681 / 902
rast3 final_rast
-- Create new 3 band raster composed of first 2 clipped bands, and overlay of 3rd band with ←-
our geometry
-- This query took 3.6 seconds on PostGIS windows 64-bit install
WITH pr AS
-- Note the order of operation: we clip all the rasters to dimensions of our region
(SELECT ST_Clip(rast,ST_Expand(geom,50) ) As rast, g.geom
FROM aerials.o_2_boston AS r INNER JOIN
-- union our parcels of interest so they form a single geometry we can later intersect with
(SELECT ST_Union(ST_Transform(geom,26986)) AS geom
FROM landparcels WHERE pid IN('0303890000', '0303900000')) As g
ON ST_Intersects(rast::geometry, ST_Expand(g.geom,50))
),
-- we then union the raster shards together
-- ST_Union on raster is kinda of slow but much faster the smaller you can get the rasters
-- therefore we want to clip first and then union
prunion AS
(SELECT ST_AddBand(NULL, ARRAY[ST_Union(rast,1),ST_Union(rast,2),ST_Union(rast,3)] ) As ←-
clipped,geom
FROM pr
GROUP BY geom)
-- return our final raster which is the unioned shard with
-- with the overlay of our parcel boundaries
-- add first 2 bands, then mapalgebra of 3rd band + geometry
SELECT ST_AddBand(ST_Band(clipped,ARRAY[1,2])
, ST_MapAlgebraExpr(ST_Band(clipped,3), ST_AsRaster(ST_Buffer(ST_Boundary(geom),2), ←-
clipped, '8BUI',250),
'[rast2.val]', '8BUI', 'FIRST', '[rast2.val]', '[rast1.val]') ) As rast
FROM prunion;
PostGIS 3.3.2 Manual 682 / 902
See Also
12.12.9 ST_MapAlgebraFct
ST_MapAlgebraFct — 1 band version - Creates a new one band raster formed by applying a valid PostgreSQL function on the
input raster band and of pixeltype prodived. Band 1 is assumed if no band is specified.
Synopsis
Description
Warning
ST_MapAlgebraFct is deprecated as of 2.1.0. Use ST_MapAlgebra (callback function version) instead.
PostGIS 3.3.2 Manual 683 / 902
Creates a new one band raster formed by applying a valid PostgreSQL function specified by the onerasteruserfunc on the
input raster (rast). If no band is specified, band 1 is assumed. The new raster will have the same georeference, width, and
height as the original raster but will only have one band.
If pixeltype is passed in, then the new raster will have a band of that pixeltype. If pixeltype is passed NULL, then the new
raster band will have the same pixeltype as the input rast band.
The onerasteruserfunc parameter must be the name and signature of a SQL or PL/pgSQL function, cast to a regprocedure.
A very simple and quite useless PL/pgSQL function example is:
CREATE OR REPLACE FUNCTION simple_function(pixel FLOAT, pos INTEGER[], VARIADIC args TEXT ←-
[])
RETURNS FLOAT
AS $$ BEGIN
RETURN 0.0;
END; $$
LANGUAGE 'plpgsql' IMMUTABLE;
The userfunction may accept two or three arguments: a float value, an optional integer array, and a variadic text array. The
first argument is the value of an individual raster cell (regardless of the raster datatype). The second argument is the position of
the current processing cell in the form ’{x,y}’. The third argument indicates that all remaining parameters to ST_MapAlgebraFct
shall be passed through to the userfunction.
Passing a regprodedure argument to a SQL function requires the full function signature to be passed, then cast to a regprocedure
type. To pass the above example PL/pgSQL function as an argument, the SQL for the argument is:
'simple_function(float,integer[],text[])'::regprocedure
Note that the argument contains the name of the function, the types of the function arguments, quotes around the name and
argument types, and a cast to a regprocedure.
The third argument to the userfunction is a variadic text array. All trailing text arguments to any ST_MapAlgebraFct call
are passed through to the specified userfunction, and are contained in the args argument.
Note
For more information about the VARIADIC keyword, please refer to the PostgreSQL documentation and the "SQL
Functions with Variable Numbers of Arguments" section of Query Language (SQL) Functions.
Note
The text[] argument to the userfunction is required, regardless of whether you choose to pass any arguments to
your user function for processing or not.
Availability: 2.0.0
Examples
Create a new 1 band raster from our original that is a function of modulo 2 of the original raster band.
ALTER TABLE dummy_rast ADD COLUMN map_rast raster;
CREATE FUNCTION mod_fct(pixel float, pos integer[], variadic args text[])
RETURNS float
AS $$
BEGIN
RETURN pixel::integer % 2;
END;
$$
PostGIS 3.3.2 Manual 684 / 902
origval | mapval
---------+--------
253 | 1
254 | 0
253 | 1
253 | 1
254 | 0
254 | 0
250 | 0
254 | 0
254 | 0
Create a new 1 band raster of pixel-type 2BUI from our original that is reclassified and set the nodata value to a passed parameter
to the user function (0).
ALTER TABLE dummy_rast ADD COLUMN map_rast2 raster;
CREATE FUNCTION classify_fct(pixel float, pos integer[], variadic args text[])
RETURNS float
AS
$$
DECLARE
nodata float := 0;
BEGIN
IF NOT args[1] IS NULL THEN
nodata := args[1];
END IF;
IF pixel < 251 THEN
RETURN 1;
ELSIF pixel = 252 THEN
RETURN 2;
ELSIF pixel > 252 THEN
RETURN 3;
ELSE
RETURN nodata;
END IF;
END;
$$
LANGUAGE 'plpgsql';
UPDATE dummy_rast SET map_rast2 = ST_MapAlgebraFct(rast,'2BUI','classify_fct(float,integer ←-
[],text[])'::regprocedure, '0') WHERE rid = 2;
origval | mapval
---------+--------
249 | 1
250 | 1
251 |
252 | 2
253 | 3
254 | 3
PostGIS 3.3.2 Manual 685 / 902
b1pixtyp
----------
2BUI
Create a new 3 band raster same pixel type from our original 3 band raster with first band altered by map algebra and remaining
2 bands unaltered.
CREATE FUNCTION rast_plus_tan(pixel float, pos integer[], variadic args text[])
RETURNS float
AS
$$
BEGIN
RETURN tan(pixel) * pixel;
END;
$$
LANGUAGE 'plpgsql';
SELECT ST_AddBand(
ST_AddBand(
ST_AddBand(
ST_MakeEmptyRaster(rast_view),
ST_MapAlgebraFct(rast_view,1,NULL,'rast_plus_tan(float,integer[],text[])':: ←-
regprocedure)
),
ST_Band(rast_view,2)
),
ST_Band(rast_view, 3) As rast_view_ma
)
FROM wind
WHERE rid=167;
PostGIS 3.3.2 Manual 686 / 902
See Also
12.12.10 ST_MapAlgebraFct
ST_MapAlgebraFct — 2 band version - Creates a new one band raster formed by applying a valid PostgreSQL function on the 2
input raster bands and of pixeltype prodived. Band 1 is assumed if no band is specified. Extent type defaults to INTERSECTION
if not specified.
Synopsis
raster ST_MapAlgebraFct(raster rast1, raster rast2, regprocedure tworastuserfunc, text pixeltype=same_as_rast1, text extent-
type=INTERSECTION, text[] VARIADIC userargs);
raster ST_MapAlgebraFct(raster rast1, integer band1, raster rast2, integer band2, regprocedure tworastuserfunc, text pixel-
type=same_as_rast1, text extenttype=INTERSECTION, text[] VARIADIC userargs);
Description
Warning
ST_MapAlgebraFct is deprecated as of 2.1.0. Use ST_MapAlgebra (callback function version) instead.
Creates a new one band raster formed by applying a valid PostgreSQL function specified by the tworastuserfunc on the
input raster rast1, rast2. If no band1 or band2 is specified, band 1 is assumed. The new raster will have the same
georeference, width, and height as the original rasters but will only have one band.
If pixeltype is passed in, then the new raster will have a band of that pixeltype. If pixeltype is passed NULL or left out, then
the new raster band will have the same pixeltype as the input rast1 band.
The tworastuserfunc parameter must be the name and signature of an SQL or PL/pgSQL function, cast to a regprocedure.
An example PL/pgSQL function example is:
CREATE OR REPLACE FUNCTION simple_function_for_two_rasters(pixel1 FLOAT, pixel2 FLOAT, pos ←-
INTEGER[], VARIADIC args TEXT[])
RETURNS FLOAT
AS $$ BEGIN
RETURN 0.0;
END; $$
LANGUAGE 'plpgsql' IMMUTABLE;
The tworastuserfunc may accept three or four arguments: a double precision value, a double precision value, an optional
integer array, and a variadic text array. The first argument is the value of an individual raster cell in rast1 (regardless of the
raster datatype). The second argument is an individual raster cell value in rast2. The third argument is the position of the
current processing cell in the form ’{x,y}’. The fourth argument indicates that all remaining parameters to ST_MapAlgebraFct
shall be passed through to the tworastuserfunc.
Passing a regprodedure argument to a SQL function requires the full function signature to be passed, then cast to a regprocedure
type. To pass the above example PL/pgSQL function as an argument, the SQL for the argument is:
'simple_function(double precision, double precision, integer[], text[])'::regprocedure
Note that the argument contains the name of the function, the types of the function arguments, quotes around the name and
argument types, and a cast to a regprocedure.
The fourth argument to the tworastuserfunc is a variadic text array. All trailing text arguments to any ST_MapAlgebraFct
call are passed through to the specified tworastuserfunc, and are contained in the userargs argument.
PostGIS 3.3.2 Manual 687 / 902
Note
For more information about the VARIADIC keyword, please refer to the PostgreSQL documentation and the "SQL
Functions with Variable Numbers of Arguments" section of Query Language (SQL) Functions.
Note
The text[] argument to the tworastuserfunc is required, regardless of whether you choose to pass any arguments
to your user function for processing or not.
Availability: 2.0.0
RETURN NULL;
END;
$$ LANGUAGE 'plpgsql' IMMUTABLE COST 1000;
250,
ST_XMin(e)::integer, ST_YMax(e)::integer, 1, -1, 0, 0 ) , '8BUI'::text,0) As rast
FROM (SELECT ST_Extent(geom) As e,
Max(ST_SRID(geom)) As srid
from mygeoms
) As foo
)
-- return our rasters aligned with our canvas
SELECT ST_AsRaster(m.geom, canvas.rast, '8BUI', 240) As rast, bnum, descrip
FROM mygeoms AS m CROSS JOIN canvas
UNION ALL
SELECT canvas.rast, 4, 'canvas'
FROM canvas;
-- Map algebra on single band rasters and then collect with ST_AddBand
INSERT INTO map_shapes(rast,bnum,descrip)
SELECT ST_AddBand(ST_AddBand(rasts[1], rasts[2]),rasts[3]), 4, 'map bands overlay fct union ←-
(canvas)'
FROM (SELECT ARRAY(SELECT ST_MapAlgebraFct(m1.rast, m2.rast,
'raster_mapalgebra_union(double precision, double precision, integer[], text[]) ←-
'::regprocedure, '8BUI', 'FIRST')
FROM map_shapes As m1 CROSS JOIN map_shapes As m2
WHERE m1.descrip = 'canvas' AND m2.descrip <> 'canvas' ORDER BY m2.bnum) As rasts) As ←-
foo;
map bands overlay (canvas) (R: small road, G: circle, B: big road)
)
RETURNS double precision
AS $$
DECLARE
BEGIN
CASE
WHEN rast1 IS NOT NULL AND rast2 IS NOT NULL THEN
RETURN least(userargs[1]::integer,(rast1 + rast2)/2.);
WHEN rast1 IS NULL AND rast2 IS NULL THEN
RETURN userargs[2]::integer;
WHEN rast1 IS NULL THEN
RETURN greatest(rast2,random()*userargs[3]::integer)::integer;
ELSE
RETURN greatest(rast1, random()*userargs[4]::integer)::integer;
END CASE;
RETURN NULL;
END;
$$ LANGUAGE 'plpgsql' VOLATILE COST 1000;
user defined with extra args and different bands from same raster
See Also
12.12.11 ST_MapAlgebraFctNgb
ST_MapAlgebraFctNgb — 1-band version: Map Algebra Nearest Neighbor using user-defined PostgreSQL function. Return a
raster which values are the result of a PLPGSQL user function involving a neighborhood of values from the input raster band.
Synopsis
raster ST_MapAlgebraFctNgb(raster rast, integer band, text pixeltype, integer ngbwidth, integer ngbheight, regprocedure on-
erastngbuserfunc, text nodatamode, text[] VARIADIC args);
Description
Warning
ST_MapAlgebraFctNgb is deprecated as of 2.1.0. Use ST_MapAlgebra (callback function version) instead.
(one raster version) Return a raster which values are the result of a PLPGSQL user function involving a neighborhood of values
from the input raster band. The user function takes the neighborhood of pixel values as an array of numbers, for each pixel,
returns the result from the user function, replacing pixel value of currently inspected pixel with the function result.
Availability: 2.0.0
Examples
Examples utilize the katrina raster loaded as a single tile described in http://trac.osgeo.org/gdal/wiki/frmts_wtkraster.html and
then prepared in the ST_Rescale examples
PostGIS 3.3.2 Manual 691 / 902
--
-- A simple 'callback' user function that averages up all the values in a neighborhood.
--
CREATE OR REPLACE FUNCTION rast_avg(matrix float[][], nodatamode text, variadic args text ←-
[])
RETURNS float AS
$$
DECLARE
_matrix float[][];
x1 integer;
x2 integer;
y1 integer;
y2 integer;
sum float;
BEGIN
_matrix := matrix;
sum := 0;
FOR x in array_lower(matrix, 1)..array_upper(matrix, 1) LOOP
FOR y in array_lower(matrix, 2)..array_upper(matrix, 2) LOOP
sum := sum + _matrix[x][y];
END LOOP;
END LOOP;
RETURN (sum*1.0/(array_upper(matrix,1)*array_upper(matrix,2) ))::integer ;
END;
$$
LANGUAGE 'plpgsql' IMMUTABLE COST 1000;
-- now we apply to our raster averaging pixels within 2 pixels of each other in X and Y ←-
direction --
SELECT ST_MapAlgebraFctNgb(rast, 1, '8BUI', 4,4,
'rast_avg(float[][], text, text[])'::regprocedure, 'NULL', NULL) As nn_with_border
FROM katrinas_rescaled
limit 1;
See Also
12.12.12 ST_Reclass
ST_Reclass — Creates a new raster composed of band types reclassified from original. The nband is the band to be changed. If
nband is not specified assumed to be 1. All other bands are returned unchanged. Use case: convert a 16BUI band to a 8BUI and
so forth for simpler rendering as viewable formats.
Synopsis
raster ST_Reclass(raster rast, integer nband, text reclassexpr, text pixeltype, double precision nodataval=NULL);
raster ST_Reclass(raster rast, reclassarg[] VARIADIC reclassargset);
raster ST_Reclass(raster rast, text reclassexpr, text pixeltype);
Description
Creates a new raster formed by applying a valid PostgreSQL algebraic operation defined by the reclassexpr on the input
raster (rast). If no band is specified band 1 is assumed. The new raster will have the same georeference, width, and height as
the original raster. Bands not designated will come back unchanged. Refer to reclassarg for description of valid reclassification
expressions.
The bands of the new raster will have pixel type of pixeltype. If reclassargset is passed in then each reclassarg defines
behavior of each band generated.
Availability: 2.0.0
Examples Basic
Create a new raster from the original where band 2 is converted from 8BUI to 4BUI and all values from 101-254 are set to nodata
value.
ALTER TABLE dummy_rast ADD COLUMN reclass_rast raster;
UPDATE dummy_rast SET reclass_rast = ST_Reclass(rast,2,'0-87:1-10, 88-100:11-15, ←-
101-254:0-0', '4BUI',0) WHERE rid = 2;
Create a new raster from the original where band 1,2,3 is converted to 1BB,4BUI, 4BUI respectively and reclassified. Note this
uses the variadic reclassarg argument which can take as input an indefinite number of reclassargs (theoretically as many
bands as you have)
PostGIS 3.3.2 Manual 693 / 902
Example: Advanced Map a single band 32BF raster to multiple viewable bands
Create a new 3 band (8BUI,8BUI,8BUI viewable raster) from a raster that has only one 32bf band
ALTER TABLE wind ADD COLUMN rast_view raster;
UPDATE wind
set rast_view = ST_AddBand( NULL,
ARRAY[
ST_Reclass(rast, 1,'0.1-10]:1-10,9-10]:11,(11-33:0'::text, '8BUI'::text,0),
ST_Reclass(rast,1, '11-33):0-255,[0-32:0,(34-1000:0'::text, '8BUI'::text,0),
ST_Reclass(rast,1,'0-32]:0,(32-100:100-255'::text, '8BUI'::text,0)
]
);
See Also
12.12.13 ST_Union
ST_Union — Returns the union of a set of raster tiles into a single raster composed of 1 or more bands.
Synopsis
Description
Returns the union of a set of raster tiles into a single raster composed of at least one band. The resulting raster’s extent is the
extent of the whole set. In the case of intersection, the resulting value is defined by uniontype which is one of the following:
LAST (default), FIRST, MIN, MAX, COUNT, SUM, MEAN, RANGE.
Note
In order for rasters to be unioned, they must all have the same alignment. Use ST_SameAlignment and
ST_NotSameAlignmentReason for more details and help. One way to fix alignment issues is to use ST_Resample
and use the same reference raster for alignment.
Availability: 2.0.0
Enhanced: 2.1.0 Improved Speed (fully C-Based).
Availability: 2.1.0 ST_Union(rast, unionarg) variant was introduced.
Enhanced: 2.1.0 ST_Union(rast) (variant 1) unions all bands of all input rasters. Prior versions of PostGIS assumed the first
band.
Enhanced: 2.1.0 ST_Union(rast, uniontype) (variant 4) unions all bands of all input rasters.
Examples: Return a multi-band raster that is the union of tiles intersecting geometry
-- this creates a multi band raster collecting all the tiles that intersect a line
-- Note: In 2.0, this would have just returned a single band raster
-- , new union works on all bands by default
-- this is equivalent to unionarg: ARRAY[ROW(1, 'LAST'), ROW(2, 'LAST'), ROW(3, 'LAST')]:: ←-
unionarg[]
SELECT ST_Union(rast)
FROM aerials.boston
WHERE ST_Intersects(rast, ST_GeomFromText('LINESTRING(230486 887771, 230500 88772)',26986) ←-
);
Examples: Return a multi-band raster that is the union of tiles intersecting geometry
Here we use the longer syntax if we only wanted a subset of bands or we want to change order of bands
-- this creates a multi band raster collecting all the tiles that intersect a line
SELECT ST_Union(rast,ARRAY[ROW(2, 'LAST'), ROW(1, 'LAST'), ROW(3, 'LAST')]::unionarg[])
FROM aerials.boston
WHERE ST_Intersects(rast, ST_GeomFromText('LINESTRING(230486 887771, 230500 88772)',26986) ←-
);
See Also
12.13.1 ST_Distinct4ma
ST_Distinct4ma — Raster processing function that calculates the number of unique pixel values in a neighborhood.
Synopsis
Description
Note
Variant 1 is a specialized callback function for use as a callback parameter to ST_MapAlgebraFctNgb.
Note
Variant 2 is a specialized callback function for use as a callback parameter to ST_MapAlgebra (callback function ver-
sion).
Warning
Use of Variant 1 is discouraged since ST_MapAlgebraFctNgb has been deprecated as of 2.1.0.
Availability: 2.0.0
Enhanced: 2.1.0 Addition of Variant 2
Examples
SELECT
rid,
st_value(
st_mapalgebrafctngb(rast, 1, NULL, 1, 1, 'st_distinct4ma(float[][],text,text[])':: ←-
regprocedure, 'ignore', NULL), 2, 2
)
FROM dummy_rast
WHERE rid = 2;
rid | st_value
-----+----------
2 | 3
(1 row)
See Also
12.13.2 ST_InvDistWeight4ma
ST_InvDistWeight4ma — Raster processing function that interpolates a pixel’s value from the pixel’s neighborhood.
Synopsis
double precision ST_InvDistWeight4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);
Description
Calculate an interpolated value for a pixel using the Inverse Distance Weighted method.
There are two optional parameters that can be passed through userargs. The first parameter is the power factor (variable k in
the equation below) between 0 and 1 used in the Inverse Distance Weighted equation. If not specified, default value is 1. The
second parameter is the weight percentage applied only when the value of the pixel of interest is included with the interpolated
value from the neighborhood. If not specified and the pixel of interest has a value, that value is returned.
The basic inverse distance weight equation is:
Note
This function is a specialized callback function for use as a callback parameter to ST_MapAlgebra (callback function
version).
Availability: 2.1.0
Examples
-- NEEDS EXAMPLE
See Also
12.13.3 ST_Max4ma
ST_Max4ma — Raster processing function that calculates the maximum pixel value in a neighborhood.
Synopsis
Description
Note
Variant 1 is a specialized callback function for use as a callback parameter to ST_MapAlgebraFctNgb.
Note
Variant 2 is a specialized callback function for use as a callback parameter to ST_MapAlgebra (callback function ver-
sion).
Warning
Use of Variant 1 is discouraged since ST_MapAlgebraFctNgb has been deprecated as of 2.1.0.
Availability: 2.0.0
Enhanced: 2.1.0 Addition of Variant 2
Examples
SELECT
rid,
st_value(
st_mapalgebrafctngb(rast, 1, NULL, 1, 1, 'st_max4ma(float[][],text,text[])':: ←-
regprocedure, 'ignore', NULL), 2, 2
)
FROM dummy_rast
WHERE rid = 2;
rid | st_value
-----+----------
2 | 254
(1 row)
See Also
12.13.4 ST_Mean4ma
ST_Mean4ma — Raster processing function that calculates the mean pixel value in a neighborhood.
Synopsis
Description
Note
Variant 1 is a specialized callback function for use as a callback parameter to ST_MapAlgebraFctNgb.
Note
Variant 2 is a specialized callback function for use as a callback parameter to ST_MapAlgebra (callback function ver-
sion).
Warning
Use of Variant 1 is discouraged since ST_MapAlgebraFctNgb has been deprecated as of 2.1.0.
Availability: 2.0.0
Enhanced: 2.1.0 Addition of Variant 2
Examples: Variant 1
SELECT
rid,
st_value(
st_mapalgebrafctngb(rast, 1, '32BF', 1, 1, 'st_mean4ma(float[][],text,text[])':: ←-
regprocedure, 'ignore', NULL), 2, 2
)
FROM dummy_rast
WHERE rid = 2;
rid | st_value
-----+------------------
2 | 253.222229003906
(1 row)
Examples: Variant 2
SELECT
rid,
st_value(
ST_MapAlgebra(rast, 1, 'st_mean4ma(double precision[][][], integer[][], text ←-
[])'::regprocedure,'32BF', 'FIRST', NULL, 1, 1)
, 2, 2)
FROM dummy_rast
WHERE rid = 2;
rid | st_value
-----+------------------
2 | 253.222229003906
(1 row)
PostGIS 3.3.2 Manual 699 / 902
See Also
12.13.5 ST_Min4ma
ST_Min4ma — Raster processing function that calculates the minimum pixel value in a neighborhood.
Synopsis
Description
Note
Variant 1 is a specialized callback function for use as a callback parameter to ST_MapAlgebraFctNgb.
Note
Variant 2 is a specialized callback function for use as a callback parameter to ST_MapAlgebra (callback function ver-
sion).
Warning
Use of Variant 1 is discouraged since ST_MapAlgebraFctNgb has been deprecated as of 2.1.0.
Availability: 2.0.0
Enhanced: 2.1.0 Addition of Variant 2
Examples
SELECT
rid,
st_value(
st_mapalgebrafctngb(rast, 1, NULL, 1, 1, 'st_min4ma(float[][],text,text[])':: ←-
regprocedure, 'ignore', NULL), 2, 2
)
FROM dummy_rast
WHERE rid = 2;
rid | st_value
-----+----------
2 | 250
(1 row)
PostGIS 3.3.2 Manual 700 / 902
See Also
12.13.6 ST_MinDist4ma
ST_MinDist4ma — Raster processing function that returns the minimum distance (in number of pixels) between the pixel of
interest and a neighboring pixel with value.
Synopsis
double precision ST_MinDist4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);
Description
Return the shortest distance (in number of pixels) between the pixel of interest and the closest pixel with value in the neighbor-
hood.
Note
The intent of this function is to provide an informative data point that helps infer the usefulness of the pixel of interest’s
interpolated value from ST_InvDistWeight4ma. This function is particularly useful when the neighborhood is sparsely
populated.
Note
This function is a specialized callback function for use as a callback parameter to ST_MapAlgebra (callback function
version).
Availability: 2.1.0
Examples
-- NEEDS EXAMPLE
See Also
12.13.7 ST_Range4ma
ST_Range4ma — Raster processing function that calculates the range of pixel values in a neighborhood.
Synopsis
Description
Note
Variant 1 is a specialized callback function for use as a callback parameter to ST_MapAlgebraFctNgb.
Note
Variant 2 is a specialized callback function for use as a callback parameter to ST_MapAlgebra (callback function ver-
sion).
Warning
Use of Variant 1 is discouraged since ST_MapAlgebraFctNgb has been deprecated as of 2.1.0.
Availability: 2.0.0
Enhanced: 2.1.0 Addition of Variant 2
Examples
SELECT
rid,
st_value(
st_mapalgebrafctngb(rast, 1, NULL, 1, 1, 'st_range4ma(float[][],text,text[])':: ←-
regprocedure, 'ignore', NULL), 2, 2
)
FROM dummy_rast
WHERE rid = 2;
rid | st_value
-----+----------
2 | 4
(1 row)
See Also
12.13.8 ST_StdDev4ma
ST_StdDev4ma — Raster processing function that calculates the standard deviation of pixel values in a neighborhood.
Synopsis
Description
Note
Variant 1 is a specialized callback function for use as a callback parameter to ST_MapAlgebraFctNgb.
Note
Variant 2 is a specialized callback function for use as a callback parameter to ST_MapAlgebra (callback function ver-
sion).
Warning
Use of Variant 1 is discouraged since ST_MapAlgebraFctNgb has been deprecated as of 2.1.0.
Availability: 2.0.0
Enhanced: 2.1.0 Addition of Variant 2
Examples
SELECT
rid,
st_value(
st_mapalgebrafctngb(rast, 1, '32BF', 1, 1, 'st_stddev4ma(float[][],text,text[])':: ←-
regprocedure, 'ignore', NULL), 2, 2
)
FROM dummy_rast
WHERE rid = 2;
rid | st_value
-----+------------------
2 | 1.30170822143555
(1 row)
See Also
12.13.9 ST_Sum4ma
ST_Sum4ma — Raster processing function that calculates the sum of all pixel values in a neighborhood.
Synopsis
Description
Note
Variant 1 is a specialized callback function for use as a callback parameter to ST_MapAlgebraFctNgb.
Note
Variant 2 is a specialized callback function for use as a callback parameter to ST_MapAlgebra (callback function ver-
sion).
Warning
Use of Variant 1 is discouraged since ST_MapAlgebraFctNgb has been deprecated as of 2.1.0.
Availability: 2.0.0
Enhanced: 2.1.0 Addition of Variant 2
Examples
SELECT
rid,
st_value(
st_mapalgebrafctngb(rast, 1, '32BF', 1, 1, 'st_sum4ma(float[][],text,text[])':: ←-
regprocedure, 'ignore', NULL), 2, 2
)
FROM dummy_rast
WHERE rid = 2;
rid | st_value
-----+----------
2 | 2279
(1 row)
See Also
12.14.1 ST_Aspect
ST_Aspect — Returns the aspect (in degrees by default) of an elevation raster band. Useful for analyzing terrain.
PostGIS 3.3.2 Manual 704 / 902
Synopsis
raster ST_Aspect(raster rast, integer band=1, text pixeltype=32BF, text units=DEGREES, boolean interpolate_nodata=FALSE);
raster ST_Aspect(raster rast, integer band, raster customextent, text pixeltype=32BF, text units=DEGREES, boolean interpo-
late_nodata=FALSE);
Description
Returns the aspect (in degrees by default) of an elevation raster band. Utilizes map algebra and applies the aspect equation to
neighboring pixels.
units indicates the units of the aspect. Possible values are: RADIANS, DEGREES (default).
When units = RADIANS, values are between 0 and 2 * pi radians measured clockwise from North.
When units = DEGREES, values are between 0 and 360 degrees measured clockwise from North.
If slope of pixel is zero, aspect of pixel is -1.
Note
For more information about Slope, Aspect and Hillshade, please refer to ESRI - How hillshade works and ERDAS Field
Guide - Aspect Images.
Availability: 2.0.0
Enhanced: 2.1.0 Uses ST_MapAlgebra() and added optional interpolate_nodata function parameter
Changed: 2.1.0 In prior versions, return values were in radians. Now, return values default to degrees
Examples: Variant 1
WITH foo AS (
SELECT ST_SetValues(
ST_AddBand(ST_MakeEmptyRaster(5, 5, 0, 0, 1, -1, 0, 0, 0), 1, '32BF', 0, -9999),
1, 1, 1, ARRAY[
[1, 1, 1, 1, 1],
[1, 2, 2, 2, 1],
[1, 2, 3, 2, 1],
[1, 2, 2, 2, 1],
[1, 1, 1, 1, 1]
]::double precision[][]
) AS rast
)
SELECT
ST_DumpValues(ST_Aspect(rast, 1, '32BF'))
FROM foo
-----------------------------------------------------------------------------------------------------
----------------------------------
(1,"{{315,341.565063476562,0,18.4349479675293,45},{288.434936523438,315,0,45,71.5650482177734},{270,
2227,180,161.565048217773,135}}")
(1 row)
PostGIS 3.3.2 Manual 705 / 902
Examples: Variant 2
Complete example of tiles of a coverage. This query only works with PostgreSQL 9.1 or higher.
WITH foo AS (
SELECT ST_Tile(
ST_SetValues(
ST_AddBand(
ST_MakeEmptyRaster(6, 6, 0, 0, 1, -1, 0, 0, 0),
1, '32BF', 0, -9999
),
1, 1, 1, ARRAY[
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 2, 1],
[1, 2, 2, 3, 3, 1],
[1, 1, 3, 2, 1, 1],
[1, 2, 2, 1, 2, 1],
[1, 1, 1, 1, 1, 1]
]::double precision[]
),
2, 2
) AS rast
)
SELECT
t1.rast,
ST_Aspect(ST_Union(t2.rast), 1, t1.rast)
FROM foo t1
CROSS JOIN foo t2
WHERE ST_Intersects(t1.rast, t2.rast)
GROUP BY t1.rast;
See Also
12.14.2 ST_HillShade
ST_HillShade — Returns the hypothetical illumination of an elevation raster band using provided azimuth, altitude, brightness
and scale inputs.
Synopsis
raster ST_HillShade(raster rast, integer band=1, text pixeltype=32BF, double precision azimuth=315, double precision alti-
tude=45, double precision max_bright=255, double precision scale=1.0, boolean interpolate_nodata=FALSE);
raster ST_HillShade(raster rast, integer band, raster customextent, text pixeltype=32BF, double precision azimuth=315, double
precision altitude=45, double precision max_bright=255, double precision scale=1.0, boolean interpolate_nodata=FALSE);
Description
Returns the hypothetical illumination of an elevation raster band using the azimuth, altitude, brightness, and scale inputs. Utilizes
map algebra and applies the hill shade equation to neighboring pixels. Return pixel values are between 0 and 255.
azimuth is a value between 0 and 360 degrees measured clockwise from North.
altitude is a value between 0 and 90 degrees where 0 degrees is at the horizon and 90 degrees is directly overhead.
max_bright is a value between 0 and 255 with 0 as no brightness and 255 as max brightness.
PostGIS 3.3.2 Manual 706 / 902
scale is the ratio of vertical units to horizontal. For Feet:LatLon use scale=370400, for Meters:LatLon use scale=111120.
If interpolate_nodata is TRUE, values for NODATA pixels from the input raster will be interpolated using ST_InvDistWeight4ma
before computing the hillshade illumination.
Note
For more information about Hillshade, please refer to How hillshade works.
Availability: 2.0.0
Enhanced: 2.1.0 Uses ST_MapAlgebra() and added optional interpolate_nodata function parameter
Changed: 2.1.0 In prior versions, azimuth and altitude were expressed in radians. Now, azimuth and altitude are expressed in
degrees
Examples: Variant 1
WITH foo AS (
SELECT ST_SetValues(
ST_AddBand(ST_MakeEmptyRaster(5, 5, 0, 0, 1, -1, 0, 0, 0), 1, '32BF', 0, -9999),
1, 1, 1, ARRAY[
[1, 1, 1, 1, 1],
[1, 2, 2, 2, 1],
[1, 2, 3, 2, 1],
[1, 2, 2, 2, 1],
[1, 1, 1, 1, 1]
]::double precision[][]
) AS rast
)
SELECT
ST_DumpValues(ST_Hillshade(rast, 1, '32BF'))
FROM foo
-----------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------
(1,"{{NULL,NULL,NULL,NULL,NULL},{NULL,251.32763671875,220.749786376953,147.224319458008, ←-
NULL},{NULL,220.749786376953,180.312225341797,67.7497863769531,NULL},{NULL ←-
,147.224319458008
,67.7497863769531,43.1210060119629,NULL},{NULL,NULL,NULL,NULL,NULL}}")
(1 row)
Examples: Variant 2
Complete example of tiles of a coverage. This query only works with PostgreSQL 9.1 or higher.
WITH foo AS (
SELECT ST_Tile(
ST_SetValues(
ST_AddBand(
ST_MakeEmptyRaster(6, 6, 0, 0, 1, -1, 0, 0, 0),
1, '32BF', 0, -9999
),
PostGIS 3.3.2 Manual 707 / 902
1, 1, 1, ARRAY[
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 2, 1],
[1, 2, 2, 3, 3, 1],
[1, 1, 3, 2, 1, 1],
[1, 2, 2, 1, 2, 1],
[1, 1, 1, 1, 1, 1]
]::double precision[]
),
2, 2
) AS rast
)
SELECT
t1.rast,
ST_Hillshade(ST_Union(t2.rast), 1, t1.rast)
FROM foo t1
CROSS JOIN foo t2
WHERE ST_Intersects(t1.rast, t2.rast)
GROUP BY t1.rast;
See Also
12.14.3 ST_Roughness
Synopsis
raster ST_Roughness(raster rast, integer nband, raster customextent, text pixeltype="32BF" , boolean interpolate_nodata=FALSE
);
Description
Calculates the "roughness" of a DEM, by subtracting the maximum from the minimum for a given area.
Availability: 2.1.0
Examples
-- needs examples
See Also
12.14.4 ST_Slope
ST_Slope — Returns the slope (in degrees by default) of an elevation raster band. Useful for analyzing terrain.
PostGIS 3.3.2 Manual 708 / 902
Synopsis
raster ST_Slope(raster rast, integer nband=1, text pixeltype=32BF, text units=DEGREES, double precision scale=1.0, boolean
interpolate_nodata=FALSE);
raster ST_Slope(raster rast, integer nband, raster customextent, text pixeltype=32BF, text units=DEGREES, double precision
scale=1.0, boolean interpolate_nodata=FALSE);
Description
Returns the slope (in degrees by default) of an elevation raster band. Utilizes map algebra and applies the slope equation to
neighboring pixels.
units indicates the units of the slope. Possible values are: RADIANS, DEGREES (default), PERCENT.
scale is the ratio of vertical units to horizontal. For Feet:LatLon use scale=370400, for Meters:LatLon use scale=111120.
If interpolate_nodata is TRUE, values for NODATA pixels from the input raster will be interpolated using ST_InvDistWeight4ma
before computing the surface slope.
Note
For more information about Slope, Aspect and Hillshade, please refer to ESRI - How hillshade works and ERDAS Field
Guide - Slope Images.
Availability: 2.0.0
Enhanced: 2.1.0 Uses ST_MapAlgebra() and added optional units, scale, interpolate_nodata function parameters
Changed: 2.1.0 In prior versions, return values were in radians. Now, return values default to degrees
Examples: Variant 1
WITH foo AS (
SELECT ST_SetValues(
ST_AddBand(ST_MakeEmptyRaster(5, 5, 0, 0, 1, -1, 0, 0, 0), 1, '32BF', 0, -9999),
1, 1, 1, ARRAY[
[1, 1, 1, 1, 1],
[1, 2, 2, 2, 1],
[1, 2, 3, 2, 1],
[1, 2, 2, 2, 1],
[1, 1, 1, 1, 1]
]::double precision[][]
) AS rast
)
SELECT
ST_DumpValues(ST_Slope(rast, 1, '32BF'))
FROM foo
st_dumpvalues
-----------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------
---------------------------------------------------------------------
(1,"{{10.0249881744385,21.5681285858154,26.5650520324707,21.5681285858154,10.0249881744385},{21.5681
{26.5650520324707,36.8698959350586,0,36.8698959350586,26.5650520324707},{21.5681285858154,35.26438903
5681285858154,26.5650520324707,21.5681285858154,10.0249881744385}}")
(1 row)
PostGIS 3.3.2 Manual 709 / 902
Examples: Variant 2
Complete example of tiles of a coverage. This query only works with PostgreSQL 9.1 or higher.
WITH foo AS (
SELECT ST_Tile(
ST_SetValues(
ST_AddBand(
ST_MakeEmptyRaster(6, 6, 0, 0, 1, -1, 0, 0, 0),
1, '32BF', 0, -9999
),
1, 1, 1, ARRAY[
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 2, 1],
[1, 2, 2, 3, 3, 1],
[1, 1, 3, 2, 1, 1],
[1, 2, 2, 1, 2, 1],
[1, 1, 1, 1, 1, 1]
]::double precision[]
),
2, 2
) AS rast
)
SELECT
t1.rast,
ST_Slope(ST_Union(t2.rast), 1, t1.rast)
FROM foo t1
CROSS JOIN foo t2
WHERE ST_Intersects(t1.rast, t2.rast)
GROUP BY t1.rast;
See Also
12.14.5 ST_TPI
Synopsis
raster ST_TPI(raster rast, integer nband, raster customextent, text pixeltype="32BF" , boolean interpolate_nodata=FALSE );
Description
Calculates the Topographic Position Index, which is defined as the focal mean with radius of one minus the center cell.
Note
This function only supports a focalmean radius of one.
Availability: 2.1.0
PostGIS 3.3.2 Manual 710 / 902
Examples
-- needs examples
See Also
12.14.6 ST_TRI
Synopsis
raster ST_TRI(raster rast, integer nband, raster customextent, text pixeltype="32BF" , boolean interpolate_nodata=FALSE );
Description
Terrain Ruggedness Index is calculated by comparing a central pixel with its neighbors, taking the absolute values of the differ-
ences, and averaging the result.
Note
This function only supports a focalmean radius of one.
Availability: 2.1.0
Examples
-- needs examples
See Also
12.15.1 Box3D
Box3D — Returns the box 3d representation of the enclosing box of the raster.
Synopsis
Description
Examples
SELECT
rid,
Box3D(rast) AS rastbox
FROM dummy_rast;
rid | rastbox
----+-------------------------------------------------
1 | BOX3D(0.5 0.5 0,20.5 60.5 0)
2 | BOX3D(3427927.75 5793243.5 0,3427928 5793244 0)
See Also
ST_Envelope
12.15.2 ST_ConvexHull
ST_ConvexHull — Return the convex hull geometry of the raster including pixel values equal to BandNoDataValue. For regular
shaped and non-skewed rasters, this gives the same result as ST_Envelope so only useful for irregularly shaped or skewed rasters.
Synopsis
Description
Return the convex hull geometry of the raster including the NoDataBandValue band pixels. For regular shaped and non-skewed
rasters, this gives more or less the same result as ST_Envelope so only useful for irregularly shaped or skewed rasters.
Note
ST_Envelope floors the coordinates and hence add a little buffer around the raster so the answer is subtly different from
ST_ConvexHull which does not floor.
Examples
convhull | env
PostGIS 3.3.2 Manual 712 / 902
--------------------------------------------------------+------------------------------------ ←-
POLYGON((0.5 0.5,20.5 0.5,20.5 60.5,0.5 60.5,0.5 0.5)) | POLYGON((0 0,20 0,20 60,0 60,0 0) ←-
)
convhull | env
--------------------------------------------------------+------------------------------------ ←-
POLYGON((0.5 0.5,20.5 1.5,22.5 61.5,2.5 60.5,0.5 0.5)) | POLYGON((0 0,22 0,22 61,0 61,0 0) ←-
)
See Also
12.15.3 ST_DumpAsPolygons
ST_DumpAsPolygons — Returns a set of geomval (geom,val) rows, from a given raster band. If no band number is specified,
band num defaults to 1.
Synopsis
Description
This is a set-returning function (SRF). It returns a set of geomval rows, formed by a geometry (geom) and a pixel band value
(val). Each polygon is the union of all pixels for that band that have the same pixel value denoted by val.
ST_DumpAsPolygon is useful for polygonizing rasters. It is the reverse of a GROUP BY in that it creates new rows. For example
it can be used to expand a single raster into multiple POLYGONS/MULTIPOLYGONS.
Changed 3.3.0, validation and fixing is disabled to improve performance. May result invalid geometries.
Availability: Requires GDAL 1.7 or higher.
Note
If there is a no data value set for a band, pixels with that value will not be returned except in the case of ex-
clude_nodata_value=false.
Note
If you only care about count of pixels with a given value in a raster, it is faster to use ST_ValueCount.
Note
This is different than ST_PixelAsPolygons where one geometry is returned for each pixel regardless of pixel value.
PostGIS 3.3.2 Manual 713 / 902
Examples
val | geomwkt
-----+--------------------------------------------------------------------------
249 | POLYGON((3427927.95 5793243.95,3427927.95 5793243.85,3427928 5793243.85,
3427928 5793243.95,3427927.95 5793243.95))
250 | POLYGON((3427927.75 5793243.9,3427927.75 5793243.85,3427927.8 5793243.85,
3427927.8 5793243.9,3427927.75 5793243.9))
250 | POLYGON((3427927.8 5793243.8,3427927.8 5793243.75,3427927.85 5793243.75,
3427927.85 5793243.8, 3427927.8 5793243.8))
251 | POLYGON((3427927.75 5793243.85,3427927.75 5793243.8,3427927.8 5793243.8,
3427927.8 5793243.85,3427927.75 5793243.85))
See Also
12.15.4 ST_Envelope
Synopsis
Description
Returns the polygon representation of the extent of the raster in spatial coordinate units defined by srid. It is a float8 minimum
bounding box represented as a polygon.
The polygon is defined by the corner points of the bounding box ((MINX, MINY), (MINX, MAXY), (MAXX, MAXY), (MAXX, MINY),
(MINX, MINY))
Examples
rid | envgeomwkt
-----+--------------------------------------------------------------------
1 | POLYGON((0 0,20 0,20 60,0 60,0 0))
2 | POLYGON((3427927 5793243,3427928 5793243,
3427928 5793244,3427927 5793244, 3427927 5793243))
PostGIS 3.3.2 Manual 714 / 902
See Also
12.15.5 ST_MinConvexHull
ST_MinConvexHull — Return the convex hull geometry of the raster excluding NODATA pixels.
Synopsis
Description
Return the convex hull geometry of the raster excluding NODATA pixels. If nband is NULL, all bands of the raster are
considered.
Availability: 2.1.0
Examples
WITH foo AS (
SELECT
ST_SetValues(
ST_SetValues(
ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(9, 9, 0, 0, 1, -1, 0, 0, 0), 1, '8 ←-
BUI', 0, 0), 2, '8BUI', 1, 0),
1, 1, 1,
ARRAY[
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 1],
[0, 0, 0, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]
]::double precision[][]
),
2, 1, 1,
ARRAY[
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0]
]::double precision[][]
) AS rast
)
SELECT
ST_AsText(ST_ConvexHull(rast)) AS hull,
ST_AsText(ST_MinConvexHull(rast)) AS mhull,
PostGIS 3.3.2 Manual 715 / 902
hull | mhull | ←-
mhull_1 | mhull_2
----------------------------------+-------------------------------------+----------------------------
POLYGON((0 0,9 0,9 -9,0 -9,0 0)) | POLYGON((0 -3,9 -3,9 -9,0 -9,0 -3)) | POLYGON((3 -3,9 ←-
-3,9 -6,3 -6,3 -3)) | POLYGON((0 -3,6 -3,6 -9,0 -9,0 -3))
See Also
12.15.6 ST_Polygon
ST_Polygon — Returns a multipolygon geometry formed by the union of pixels that have a pixel value that is not no data value.
If no band number is specified, band num defaults to 1.
Synopsis
Description
Changed 3.3.0, validation and fixing is disabled to improve performance. May result invalid geometries.
Availability: 0.1.6 Requires GDAL 1.7 or higher.
Enhanced: 2.1.0 Improved Speed (fully C-Based) and the returning multipolygon is ensured to be valid.
Changed: 2.1.0 In prior versions would sometimes return a polygon, changed to always return multipolygon.
Examples
-- by default no data band value is 0 or not set, so polygon will return a square polygon
SELECT ST_AsText(ST_Polygon(rast)) As geomwkt
FROM dummy_rast
WHERE rid = 2;
geomwkt
--------------------------------------------
MULTIPOLYGON(((3427927.75 5793244,3427928 5793244,3427928 5793243.75,3427927.75 ←-
5793243.75,3427927.75 5793244)))
geomwkt
---------------------------------------------------------
MULTIPOLYGON(((3427927.9 5793243.95,3427927.85 5793243.95,3427927.85 5793244,3427927.9 ←-
5793244,3427927.9 5793243.95)),((3427928 5793243.85,3427928 5793243.8,3427927.95 ←-
5793243.8,3427927.95 5793243.85,3427927.9 5793243.85,3427927.9 5793243.9,3427927.9 ←-
5793243.95,3427927.95 5793243.95,3427928 5793243.95,3427928 5793243.85)),((3427927.8 ←-
5793243.75,3427927.75 5793243.75,3427927.75 5793243.8,3427927.75 5793243.85,3427927.75 ←-
5793243.9,3427927.75 5793244,3427927.8 5793244,3427927.8 5793243.9,3427927.8 ←-
5793243.85,3427927.85 5793243.85,3427927.85 5793243.8,3427927.85 5793243.75,3427927.8 ←-
5793243.75)))
-- Or if you want the no data value different for just one time
SELECT ST_AsText(
ST_Polygon(
ST_SetBandNoDataValue(rast,1,252)
)
) As geomwkt
FROM dummy_rast
WHERE rid =2;
geomwkt
---------------------------------
MULTIPOLYGON(((3427928 5793243.85,3427928 5793243.8,3427928 5793243.75,3427927.85 ←-
5793243.75,3427927.8 5793243.75,3427927.8 5793243.8,3427927.75 5793243.8,3427927.75 ←-
5793243.85,3427927.75 5793243.9,3427927.75 5793244,3427927.8 5793244,3427927.85 ←-
5793244,3427927.9 5793244,3427928 5793244,3427928 5793243.95,3427928 5793243.85) ←-
,(3427927.9 5793243.9,3427927.9 5793243.85,3427927.95 5793243.85,3427927.95 ←-
5793243.9,3427927.9 5793243.9)))
See Also
ST_Value, ST_DumpAsPolygons
12.16.1 &&
&& — Returns TRUE if A’s bounding box intersects B’s bounding box.
Synopsis
Description
The && operator returns TRUE if the bounding box of raster/geometr A intersects the bounding box of raster/geometr B.
Note
This operand will make use of any indexes that may be available on the rasters.
PostGIS 3.3.2 Manual 717 / 902
Availability: 2.0.0
Examples
12.16.2 &<
Synopsis
Description
The &< operator returns TRUE if the bounding box of raster A overlaps or is to the left of the bounding box of raster B, or more
accurately, overlaps or is NOT to the right of the bounding box of raster B.
Note
This operand will make use of any indexes that may be available on the rasters.
Examples
12.16.3 &>
Synopsis
Description
The &> operator returns TRUE if the bounding box of raster A overlaps or is to the right of the bounding box of raster B, or more
accurately, overlaps or is NOT to the left of the bounding box of raster B.
Note
This operand will make use of any indexes that may be available on the geometries.
Examples
12.16.4 =
= — Returns TRUE if A’s bounding box is the same as B’s. Uses double precision bounding box.
Synopsis
Description
The = operator returns TRUE if the bounding box of raster A is the same as the bounding box of raster B. PostgreSQL uses the
=, <, and > operators defined for rasters to perform internal orderings and comparison of rasters (ie. in a GROUP BY or ORDER
BY clause).
Caution
This operand will NOT make use of any indexes that may be available on the rasters. Use ~= instead. This operator
exists mostly so one can group by the raster column.
Availability: 2.1.0
PostGIS 3.3.2 Manual 719 / 902
See Also
~=
12.16.5 @
@ — Returns TRUE if A’s bounding box is contained by B’s. Uses double precision bounding box.
Synopsis
Description
The @ operator returns TRUE if the bounding box of raster/geometry A is contained by bounding box of raster/geometr B.
Note
This operand will use spatial indexes on the rasters.
See Also
12.16.6 ~=
Synopsis
Description
The ~= operator returns TRUE if the bounding box of raster A is the same as the bounding box of raster B.
Note
This operand will make use of any indexes that may be available on the rasters.
Availability: 2.0.0
PostGIS 3.3.2 Manual 720 / 902
Examples
Very useful usecase is for taking two sets of single band rasters that are of the same chunk but represent different themes and
creating a multi-band raster
SELECT ST_AddBand(prec.rast, alt.rast) As new_rast
FROM prec INNER JOIN alt ON (prec.rast ~= alt.rast);
See Also
ST_AddBand, =
12.16.7 ~
~ — Returns TRUE if A’s bounding box is contains B’s. Uses double precision bounding box.
Synopsis
Description
The ~ operator returns TRUE if the bounding box of raster/geometry A is contains bounding box of raster/geometr B.
Note
This operand will use spatial indexes on the rasters.
Availability: 2.0.0
See Also
12.17.1 ST_Contains
ST_Contains — Return true if no points of raster rastB lie in the exterior of raster rastA and at least one point of the interior of
rastB lies in the interior of rastA.
Synopsis
boolean ST_Contains( raster rastA , integer nbandA , raster rastB , integer nbandB );
boolean ST_Contains( raster rastA , raster rastB );
PostGIS 3.3.2 Manual 721 / 902
Description
Raster rastA contains rastB if and only if no points of rastB lie in the exterior of rastA and at least one point of the interior of
rastB lies in the interior of rastA. If the band number is not provided (or set to NULL), only the convex hull of the raster is
considered in the test. If the band number is provided, only those pixels with value (not NODATA) are considered in the test.
Note
This function will make use of any indexes that may be available on the rasters.
Note
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g.
ST_Contains(ST_Polygon(raster), geometry) or ST_Contains(geometry, ST_Polygon(raster)).
Note
ST_Contains() is the inverse of ST_Within(). So, ST_Contains(rastA, rastB) implies ST_Within(rastB, rastA).
Availability: 2.1.0
Examples
See Also
ST_Intersects, ST_Within
12.17.2 ST_ContainsProperly
ST_ContainsProperly — Return true if rastB intersects the interior of rastA but not the boundary or exterior of rastA.
PostGIS 3.3.2 Manual 722 / 902
Synopsis
boolean ST_ContainsProperly( raster rastA , integer nbandA , raster rastB , integer nbandB );
boolean ST_ContainsProperly( raster rastA , raster rastB );
Description
Raster rastA contains properly rastB if rastB intersects the interior of rastA but not the boundary or exterior of rastA. If the band
number is not provided (or set to NULL), only the convex hull of the raster is considered in the test. If the band number is
provided, only those pixels with value (not NODATA) are considered in the test.
Raster rastA does not contain properly itself but does contain itself.
Note
This function will make use of any indexes that may be available on the rasters.
Note
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g.
ST_ContainsProperly(ST_Polygon(raster), geometry) or ST_ContainsProperly(geometry, ST_Polygon(raster)).
Availability: 2.1.0
Examples
See Also
ST_Intersects, ST_Contains
12.17.3 ST_Covers
ST_Covers — Return true if no points of raster rastB lie outside raster rastA.
Synopsis
boolean ST_Covers( raster rastA , integer nbandA , raster rastB , integer nbandB );
boolean ST_Covers( raster rastA , raster rastB );
PostGIS 3.3.2 Manual 723 / 902
Description
Raster rastA covers rastB if and only if no points of rastB lie in the exterior of rastA. If the band number is not provided (or set to
NULL), only the convex hull of the raster is considered in the test. If the band number is provided, only those pixels with value
(not NODATA) are considered in the test.
Note
This function will make use of any indexes that may be available on the rasters.
Note
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g.
ST_Covers(ST_Polygon(raster), geometry) or ST_Covers(geometry, ST_Polygon(raster)).
Availability: 2.1.0
Examples
See Also
ST_Intersects, ST_CoveredBy
12.17.4 ST_CoveredBy
ST_CoveredBy — Return true if no points of raster rastA lie outside raster rastB.
Synopsis
boolean ST_CoveredBy( raster rastA , integer nbandA , raster rastB , integer nbandB );
boolean ST_CoveredBy( raster rastA , raster rastB );
Description
Raster rastA is covered by rastB if and only if no points of rastA lie in the exterior of rastB. If the band number is not provided
(or set to NULL), only the convex hull of the raster is considered in the test. If the band number is provided, only those pixels
with value (not NODATA) are considered in the test.
Note
This function will make use of any indexes that may be available on the rasters.
PostGIS 3.3.2 Manual 724 / 902
Note
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g.
ST_CoveredBy(ST_Polygon(raster), geometry) or ST_CoveredBy(geometry, ST_Polygon(raster)).
Availability: 2.1.0
Examples
See Also
ST_Intersects, ST_Covers
12.17.5 ST_Disjoint
ST_Disjoint — Return true if raster rastA does not spatially intersect rastB.
Synopsis
boolean ST_Disjoint( raster rastA , integer nbandA , raster rastB , integer nbandB );
boolean ST_Disjoint( raster rastA , raster rastB );
Description
Raster rastA and rastB are disjointed if they do not share any space together. If the band number is not provided (or set to
NULL), only the convex hull of the raster is considered in the test. If the band number is provided, only those pixels with value
(not NODATA) are considered in the test.
Note
This function does NOT use any indexes.
Note
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g.
ST_Disjoint(ST_Polygon(raster), geometry).
Availability: 2.1.0
PostGIS 3.3.2 Manual 725 / 902
Examples
-- rid = 1 has no bands, hence the NOTICE and the NULL value for st_disjoint
SELECT r1.rid, r2.rid, ST_Disjoint(r1.rast, 1, r2.rast, 1) FROM dummy_rast r1 CROSS JOIN ←-
dummy_rast r2 WHERE r1.rid = 2;
See Also
ST_Intersects
12.17.6 ST_Intersects
Synopsis
boolean ST_Intersects( raster rastA , integer nbandA , raster rastB , integer nbandB );
boolean ST_Intersects( raster rastA , raster rastB );
boolean ST_Intersects( raster rast , integer nband , geometry geommin );
boolean ST_Intersects( raster rast , geometry geommin , integer nband=NULL );
boolean ST_Intersects( geometry geommin , raster rast , integer nband=NULL );
Description
Return true if raster rastA spatially intersects raster rastB. If the band number is not provided (or set to NULL), only the convex
hull of the raster is considered in the test. If the band number is provided, only those pixels with value (not NODATA) are
considered in the test.
Note
This function will make use of any indexes that may be available on the rasters.
Warning
Changed: 2.1.0 The behavior of the ST_Intersects(raster, geometry) variants changed to match that of
ST_Intersects(geometry, raster).
PostGIS 3.3.2 Manual 726 / 902
Examples
st_intersects
---------------
t
See Also
ST_Intersection, ST_Disjoint
12.17.7 ST_Overlaps
ST_Overlaps — Return true if raster rastA and rastB intersect but one does not completely contain the other.
Synopsis
boolean ST_Overlaps( raster rastA , integer nbandA , raster rastB , integer nbandB );
boolean ST_Overlaps( raster rastA , raster rastB );
Description
Return true if raster rastA spatially overlaps raster rastB. This means that rastA and rastB intersect but one does not completely
contain the other. If the band number is not provided (or set to NULL), only the convex hull of the raster is considered in the test.
If the band number is provided, only those pixels with value (not NODATA) are considered in the test.
Note
This function will make use of any indexes that may be available on the rasters.
Note
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g.
ST_Overlaps(ST_Polygon(raster), geometry).
Availability: 2.1.0
Examples
st_overlaps
-------------
f
PostGIS 3.3.2 Manual 727 / 902
See Also
ST_Intersects
12.17.8 ST_Touches
ST_Touches — Return true if raster rastA and rastB have at least one point in common but their interiors do not intersect.
Synopsis
boolean ST_Touches( raster rastA , integer nbandA , raster rastB , integer nbandB );
boolean ST_Touches( raster rastA , raster rastB );
Description
Return true if raster rastA spatially touches raster rastB. This means that rastA and rastB have at least one point in common
but their interiors do not intersect. If the band number is not provided (or set to NULL), only the convex hull of the raster is
considered in the test. If the band number is provided, only those pixels with value (not NODATA) are considered in the test.
Note
This function will make use of any indexes that may be available on the rasters.
Note
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g.
ST_Touches(ST_Polygon(raster), geometry).
Availability: 2.1.0
Examples
See Also
ST_Intersects
12.17.9 ST_SameAlignment
ST_SameAlignment — Returns true if rasters have same skew, scale, spatial ref, and offset (pixels can be put on same grid
without cutting into pixels) and false if they don’t with notice detailing issue.
PostGIS 3.3.2 Manual 728 / 902
Synopsis
Description
Non-Aggregate version (Variants 1 and 2): Returns true if the two rasters (either provided directly or made using the values for
upperleft, scale, skew and srid) have the same scale, skew, srid and at least one of any of the four corners of any pixel of one
raster falls on any corner of the grid of the other raster. Returns false if they don’t and a NOTICE detailing the alignment issue.
Aggregate version (Variant 3): From a set of rasters, returns true if all rasters in the set are aligned. The ST_SameAlignment()
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.
Availability: 2.0.0
Enhanced: 2.1.0 addition of Aggegrate variant
Examples: Rasters
SELECT ST_SameAlignment(
ST_MakeEmptyRaster(1, 1, 0, 0, 1, 1, 0, 0),
ST_MakeEmptyRaster(1, 1, 0, 0, 1, 1, 0, 0)
) as sm;
sm
----
t
SELECT ST_SameAlignment(A.rast,b.rast)
FROM dummy_rast AS A CROSS JOIN dummy_rast AS B;
See Also
12.17.10 ST_NotSameAlignmentReason
ST_NotSameAlignmentReason — Returns text stating if rasters are aligned and if not aligned, a reason why.
Synopsis
Description
Returns text stating if rasters are aligned and if not aligned, a reason why.
Note
If there are several reasons why the rasters are not aligned, only one reason (the first test to fail) will be returned.
Availability: 2.1.0
Examples
SELECT
ST_SameAlignment(
ST_MakeEmptyRaster(1, 1, 0, 0, 1, 1, 0, 0),
ST_MakeEmptyRaster(1, 1, 0, 0, 1.1, 1.1, 0, 0)
),
ST_NotSameAlignmentReason(
ST_MakeEmptyRaster(1, 1, 0, 0, 1, 1, 0, 0),
ST_MakeEmptyRaster(1, 1, 0, 0, 1.1, 1.1, 0, 0)
)
;
st_samealignment | st_notsamealignmentreason
------------------+-------------------------------------------------
f | The rasters have different scales on the X axis
(1 row)
See Also
12.17.11 ST_Within
ST_Within — Return true if no points of raster rastA lie in the exterior of raster rastB and at least one point of the interior of
rastA lies in the interior of rastB.
Synopsis
boolean ST_Within( raster rastA , integer nbandA , raster rastB , integer nbandB );
boolean ST_Within( raster rastA , raster rastB );
Description
Raster rastA is within rastB if and only if no points of rastA lie in the exterior of rastB and at least one point of the interior
of rastA lies in the interior of rastB. If the band number is not provided (or set to NULL), only the convex hull of the raster is
considered in the test. If the band number is provided, only those pixels with value (not NODATA) are considered in the test.
Note
This operand will make use of any indexes that may be available on the rasters.
PostGIS 3.3.2 Manual 730 / 902
Note
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g.
ST_Within(ST_Polygon(raster), geometry) or ST_Within(geometry, ST_Polygon(raster)).
Note
ST_Within() is the inverse of ST_Contains(). So, ST_Within(rastA, rastB) implies ST_Contains(rastB, rastA).
Availability: 2.1.0
Examples
See Also
12.17.12 ST_DWithin
ST_DWithin — Return true if rasters rastA and rastB are within the specified distance of each other.
Synopsis
boolean ST_DWithin( raster rastA , integer nbandA , raster rastB , integer nbandB , double precision distance_of_srid );
boolean ST_DWithin( raster rastA , raster rastB , double precision distance_of_srid );
Description
Return true if rasters rastA and rastB are within the specified distance of each other. If the band number is not provided (or set to
NULL), only the convex hull of the raster is considered in the test. If the band number is provided, only those pixels with value
(not NODATA) are considered in the test.
The distance is specified in units defined by the spatial reference system of the rasters. For this function to make sense, the source
rasters must both be of the same coordinate projection, having the same SRID.
Note
This operand will make use of any indexes that may be available on the rasters.
PostGIS 3.3.2 Manual 731 / 902
Note
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g.
ST_DWithin(ST_Polygon(raster), geometry).
Availability: 2.1.0
Examples
See Also
ST_Within, ST_DFullyWithin
12.17.13 ST_DFullyWithin
ST_DFullyWithin — Return true if rasters rastA and rastB are fully within the specified distance of each other.
Synopsis
boolean ST_DFullyWithin( raster rastA , integer nbandA , raster rastB , integer nbandB , double precision distance_of_srid );
boolean ST_DFullyWithin( raster rastA , raster rastB , double precision distance_of_srid );
Description
Return true if rasters rastA and rastB are fully within the specified distance of each other. If the band number is not provided (or
set to NULL), only the convex hull of the raster is considered in the test. If the band number is provided, only those pixels with
value (not NODATA) are considered in the test.
The distance is specified in units defined by the spatial reference system of the rasters. For this function to make sense, the source
rasters must both be of the same coordinate projection, having the same SRID.
Note
This operand will make use of any indexes that may be available on the rasters.
Note
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g.
ST_DFullyWithin(ST_Polygon(raster), geometry).
Availability: 2.1.0
PostGIS 3.3.2 Manual 732 / 902
Examples
See Also
ST_Within, ST_DWithin
When GDAL opens a file, GDAL eagerly scans the directory of that file to build a catalog of other files. If this directory contains
many files (e.g. thousands, millions), opening that file becomes extremely slow (especially if that file happens to be on a network
drive such as NFS).
To control this behavior, GDAL provides the following environment variable: GDAL_DISABLE_READDIR_ON_OPEN. Set
GDAL_DISABLE_READDIR_ON_OPEN to TRUE to disable directory scanning.
In Ubuntu (and assuming you are using PostgreSQL’s packages for Ubuntu), GDAL_DISABLE_READDIR_ON_OPEN can be set
in /etc/postgresql/POSTGRESQL_VERSION/CLUSTER_NAME/environment (where POSTGRESQL_VERSION is the version
of PostgreSQL, e.g. 9.6 and CLUSTER_NAME is the name of the cluster, e.g. maindb). You can also set PostGIS environment
variables here as well.
# environment variables for postmaster process
# This file has the same syntax as postgresql.conf:
# VARIABLE = simple_value
# VARIABLE2 = 'any value!'
# I. e. you need to enclose any value which does not only consist of letters,
# numbers, and '-', '_', '.' in single quotes. Shell commands are not
# evaluated.
POSTGIS_GDAL_ENABLED_DRIVERS = 'ENABLE_ALL'
POSTGIS_ENABLE_OUTDB_RASTERS = 1
GDAL_DISABLE_READDIR_ON_OPEN = 'TRUE'
The maximum number of open files permitted by Linux and PostgreSQL are typically conservative (typically 1024 open files per
process) given the assumption that the system is consumed by human users. For Out-DB Rasters, a single valid query can easily
exceed this limit (e.g. a dataset of 10 year’s worth of rasters with one raster for each day containing minimum and maximum
temperatures and we want to know the absolute min and max value for a pixel in that dataset).
The easiest change to make is the following PostgreSQL setting: max_files_per_process. The default is set to 1000, which is far
too low for Out-DB Rasters. A safe starting value could be 65536 but this really depends on your datasets and the queries run
against those datasets. This setting can only be made on server start and probably only in the PostgreSQL configuration file (e.g.
/etc/postgresql/POSTGRESQL_VERSION/CLUSTER_NAME/postgresql.conf in Ubuntu environments).
PostGIS 3.3.2 Manual 733 / 902
...
# - Kernel Resource Usage -
The major change to make is the Linux kernel’s open files limits. There are two parts to this:
You can inspect the current maximum number of open files for the entire system with the following example:
$ sysctl -a | grep fs.file-max
fs.file-max = 131072
If the value returned is not large enough, add a file to /etc/sysctl.d/ as per the following example:
$ echo "fs.file-max = 6145324" >> /etc/sysctl.d/fs.conf
$ cat /etc/sysctl.d/fs.conf
fs.file-max = 6145324
$ sysctl -p --system
* Applying /etc/sysctl.d/fs.conf ...
fs.file-max = 2097152
* Applying /etc/sysctl.conf ...
We need to increase the maximum number of open files per process for the PostgreSQL server processes.
To see what the current PostgreSQL service processes are using for maximum number of open files, do as per the following
example (make sure to have PostgreSQL running):
$ ps aux | grep postgres
postgres 31713 0.0 0.4 179012 17564 pts/0 S Dec26 0:03 /home/dustymugs/devel/ ←-
postgresql/sandbox/10/usr/local/bin/postgres -D /home/dustymugs/devel/postgresql/sandbox ←-
/10/pgdata
postgres 31716 0.0 0.8 179776 33632 ? Ss Dec26 0:01 postgres: checkpointer ←-
process
postgres 31717 0.0 0.2 179144 9416 ? Ss Dec26 0:05 postgres: writer process
postgres 31718 0.0 0.2 179012 8708 ? Ss Dec26 0:06 postgres: wal writer ←-
process
postgres 31719 0.0 0.1 179568 7252 ? Ss Dec26 0:03 postgres: autovacuum ←-
launcher process
postgres 31720 0.0 0.1 34228 4124 ? Ss Dec26 0:09 postgres: stats collector ←-
process
postgres 31721 0.0 0.1 179308 6052 ? Ss Dec26 0:00 postgres: bgworker: ←-
logical replication launcher
$ cat /proc/31718/limits
PostGIS 3.3.2 Manual 734 / 902
In the example above, we inspected the open files limit for Process 31718. It doesn’t matter which PostgreSQL process, any of
them will do. The response we are interested in is Max open files.
We want to increase Soft Limit and Hard Limit of Max open files to be greater than the value we specified for the PostgreSQL
setting max_files_per_process. In our example, we set max_files_per_process to 65536.
In Ubuntu (and assuming you are using PostgreSQL’s packages for Ubuntu), the easiest way to change the Soft Limit and Hard
Limit is to edit /etc/init.d/postgresql (SysV) or /lib/systemd/system/postgresql*.service (systemd).
Let’s first address the SysV Ubuntu case where we add ulimit -H -n 262144 and ulimit -n 131072 to /etc/init.d/postgresql.
...
case "$1" in
start|stop|restart|reload)
if [ "$1" = "start" ]; then
create_socket_directory
fi
if [ -z " `pg_lsclusters -h`" ]; then
log_warning_msg 'No PostgreSQL clusters exist; see "man pg_createcluster"'
exit 0
fi
ulimit -H -n 262144
ulimit -n 131072
for v in $versions; do
$1 $v || EXIT=$?
done
exit ${EXIT:-0}
;;
status)
...
Now to address the systemd Ubuntu case. We will add LimitNOFILE=131072 to every /lib/systemd/system/postgresql*.service
file in the [Service] section.
...
[Service]
LimitNOFILE=131072
...
[Install]
WantedBy=multi-user.target
PostGIS 3.3.2 Manual 735 / 902
...
After making the necessary systemd changes, make sure to reload the daemon
systemctl daemon-reload
PostGIS 3.3.2 Manual 736 / 902
Chapter 13
1. Where can I find out more about the PostGIS Raster Project?
Refer to the PostGIS Raster home page.
2. Are there any books or tutorials to get me started with this wonderful invention?
There is a full length beginner tutorial Intersecting vector buffers with large raster coverage using PostGIS Raster. Jorge has
a series of blog articles on PostGIS Raster that demonstrate how to load raster data as well as cross compare to same tasks
in Oracle GeoRaster. Check out: Jorge’s PostGIS Raster / Oracle GeoRaster Series. There is a whole chapter (more than
35 pages of content) dedicated to PostGIS Raster with free code and data downloads at PostGIS in Action - Raster chapter.
Also covered in second edition.. You can buy PostGIS in Action now from Manning in hard-copy (significant discounts
for bulk purchases) or just the E-book format. You can also buy from Amazon and various other book distributors. All
hard-copy books come with a free coupon to download the E-book version. Here is a review from a PostGIS Raster user
PostGIS raster applied to land classification urban forestry
3. How do I install Raster support in my PostGIS database?
PostGIS Raster is part of the PostGIS codebase and generally available with most PostGIS binary distributions. Starting
with PostGIS 3.0, PostGIS raster is now a separate extension and requires: `CREATE EXTENSION postgis_raster;` to
enable it in your database. If you are compiling your own PostGIS, you will need to compile with GDAL otherwise
postgis_raster extension will not be built.Refer to Download PostGIS binaries for popular distributions of PostGIS that
include raster support.
4. How do I load Raster data into PostGIS?
The latest version of PostGIS comes packaged with a raster2pgsql raster loader executable capable of loading many
kinds of rasters and also generating lower resolution overviews without any additional software. Please refer to Sec-
tion 11.1.1 for more details.
5. What kind of raster file formats can I load into my database?
Any that your GDAL library supports. GDAL supported formats are documented GDAL File Formats.Your particular
GDAL install may not support all formats. To verify the ones supported by your particular GDAL install, you can use
raster2pgsql -G
to enable the driver. Refer to GDAL Build Hints for tips on building GDAL against in various OS platforms. If your
version of GDAL is compiled with the PostGIS Raster driver you should see PostGIS Raster in list when you do
gdalinfo --formats
To export data to other raster formats, use gdal_translate the below will export all data from a table to a PNG file at 10%
size.Depending on your pixel band types, some translations may not work if the export format does not support that Pixel
type. For example floating point band types and 32 bit unsigned ints will not translate easily to JPG or some others.Here is
an example simple translation
gdal_translate -of PNG -outsize 10% 10% "PG:host=localhost port=5432 dbname='mygisdb' ←-
user='postgres' password='whatever' schema='someschema' table=sometable" C:\ ←-
somefile.png
You can also use SQL where clauses in your export using the where=... in your driver connection string. Below are some
using a where clause
gdal_translate -of PNG -outsize 10% 10% "PG:host=localhost port=5432 dbname='mygisdb' ←-
user='postgres' password='whatever' schema='someschema' table=sometable where=' ←-
filename=\'abcd.sid\''" " C:\somefile.png
To see more examples and syntax refer to Reading Raster Data of PostGIS Raster section
7. Are their binaries of GDAL available already compiled with PostGIS Raster suppport?
Yes. Check out the page GDAL Binaries page. Any compiled with PostgreSQL support should have PostGIS Raster in
them. GDAL tools is also generally included as part of QGIS.If you want to get the latest nightly build for Windows --
then check out the Tamas Szekeres nightly builds built with Visual Studio which contain GDAL trunk, Python Bindings
and MapServer executables and PostGIS Raster driver built-in. Just click the SDK bat and run your commands from there.
http://www.gisinternals.com. Also available are VS project files.
8. What tools can I use to view PostGIS raster data?
You can use MapServer compiled with GDAL to view Raster data. QGIS supports viewing of PostGIS Raster if you have
PostGIS raster driver installed.In theory any tool that renders data using GDAL can support PostGIS raster data or support
it with fairly minimal effort. Again for Windows, Tamas’ binaries (includes Mapserver) http://www.gisinternals.com are a
good choice for windows users if you don’t want the hassle of having to setup to compile your own.
9. How can I add a PostGIS raster layer to my MapServer map?
First you need GDAL 1.7 or higher compiled with PostGIS raster support. GDAL 3 or above is preferred since many issues
have been fixed in 1.8 and more PostGIS raster issues fixed in trunk version.You can much like you can with any other
raster. Refer to MapServer Raster processing options for list of various processing functions you can use with MapServer
raster layers.What makes PostGIS raster data particularly interesting, is that since each tile can have various standard
database columns, you can segment it in your data sourceBelow is an example of how you would define a PostGIS raster
layer in MapServer.
Note
The mode=2 is required for tiled rasters and was added in PostGIS 2.0 and GDAL 1.8 drivers. This does not exist
in GDAL 1.7 drivers.
PostGIS 3.3.2 Manual 738 / 902
Cast the textual geometry representation to a geometry by changing your code to this:
SELECT rast
PostGIS 3.3.2 Manual 739 / 902
FROM my_raster
WHERE ST_Intersects(rast, 'SRID=4326;POINT(-10 10)'::geometry);
12. How is PostGIS Raster different from Oracle GeoRaster (SDO_GEORASTER) and SDO_RASTER types?
For a more extensive discussion on this topic, check out Jorge Arévalo Oracle GeoRaster and PostGIS Raster: First
impressions The major advantage of one-georeference-by-raster over one-georeference-by-layer is to allow:* coverages
to be not necessarily rectangular (which is often the case of raster coverage covering large extents. See the possible
raster arrangements in the documentation)* rasters to overlaps (which is necessary to implement lossless vector to raster
conversion) These arrangements are possible in Oracle as well, but they imply the storage of multiple SDO_GEORASTER
objects linked to as many SDO_RASTER tables. A complex coverage can lead to hundreds of tables in the database. With
PostGIS Raster you can store a similar raster arrangement into a unique table.It’s a bit like if PostGIS would force you to
store only full rectangular vector coverage without gaps or overlaps (a perfect rectangular topological layer). This is very
practical in some applications but practice has shown that it is not realistic or desirable for most geographical coverages.
Vector structures needs the flexibility to store discontinuous and non-rectangular coverages. We think it is a big advantage
that raster structure should benefit as well.
13. raster2pgsql load of large file fails with String of N bytes is too long for encoding conversion?
raster2pgsql doesn’t make any connections to your database when generating the file to load. If your database has set an
explicit client encoding different from your database encoding, then when loading large raster files (above 30 MB in size),
you may run into a bytes is too long for encoding conversion.This generally happens if for example
you have your database in UTF8, but to support windows apps, you have the client encoding set to WIN1252.To work
around this make sure the client encoding is the same as your database encoding during load. You can do this by explicitly
setting the encoding in your load script. Example, if you are on windows:
set PGCLIENTENCODING=UTF8
14. I’m getting error ERROR: RASTER_fromGDALRaster: Could not open bytea with GDAL. Check that
the bytea is of a GDAL supported format. when using ST_FromGDALRaster or ERROR: rt_raster_to_g
Could not load the output GDAL driver when trying to use ST_AsPNG or other raster input functions.
As of PostGIS 2.1.3 and 2.0.5, a security change was made to by default disable all GDAL drivers and out of db rasters.
The release notes are at PostGIS 2.0.6, 2.1.3 security release. In order to reenable specific drivers or all drivers and reenable
out of database support, refer to Section 2.1.
PostGIS 3.3.2 Manual 740 / 902
Chapter 14
PostGIS Extras
This chapter documents features found in the extras folder of the PostGIS source tarballs and source repository. These are not
always packaged with PostGIS binary releases, but are usually PL/pgSQL based or standard shell scripts that can be run as is.
This is a fork of the PAGC standardizer (original code for this portion was PAGC PostgreSQL Address Standardizer).
The address standardizer is a single line address parser that takes an input address and normalizes it based on a set of rules stored
in a table and helper lex and gaz tables.
The code is built into a single PostgreSQL extension library called address_standardizer which can be installed with
CREATE EXTENSION address_standardizer;. In addition to the address_standardizer extension, a sample data ex-
tension called address_standardizer_data_us extensions is built, which contains gaz, lex, and rules tables for US data.
This extensions can be installed via: CREATE EXTENSION address_standardizer_data_us;
The code for this extension can be found in the PostGIS extensions/address_standardizer and is currently self-
contained.
For installation instructions refer to: Section 2.3.
The parser works from right to left looking first at the macro elements for postcode, state/province, city, and then looks micro
elements to determine if we are dealing with a house number street or intersection or landmark. It currently does not look for a
country code or name, but that could be introduced in the future.
Country code Assumed to be US or CA based on: postcode as US or Canada state/province as US or Canada else US
Postcode/zipcode These are recognized using Perl compatible regular expressions. These regexs are currently in the parseaddress-
api.c and are relatively simple to make changes to if needed.
State/province These are recognized using Perl compatible regular expressions. These regexs are currently in the parseaddress-
api.c but could get moved into includes in the future for easier maintenance.
14.1.2.1 stdaddr
stdaddr — A composite type that consists of the elements of an address. This is the return type for standardize_address
function.
PostGIS 3.3.2 Manual 741 / 902
Description
A composite type that consists of elements of an address. This is the return type for standardize_address function. Some
descriptions for elements are borrowed from PAGC Postal Attributes.
The token numbers denote the output reference number in the rules table.
building is text (token number 0): Refers to building number or name. Unparsed building identifiers and types. Generally blank
for most addresses.
house_num is a text (token number 1): This is the street number on a street. Example 75 in 75 State Street.
predir is text (token number 2): STREET NAME PRE-DIRECTIONAL such as North, South, East, West etc.
qual is text (token number 3): STREET NAME PRE-MODIFIER Example OLD in 3715 OLD HIGHWAY 99.
pretype is text (token number 4): STREET PREFIX TYPE
name is text (token number 5): STREET NAME
suftype is text (token number 6): STREET POST TYPE e.g. St, Ave, Cir. A street type following the root street name. Example
STREET in 75 State Street.
sufdir is text (token number 7): STREET POST-DIRECTIONAL A directional modifier that follows the street name.. Example
WEST in 3715 TENTH AVENUE WEST.
ruralroute is text (token number 8): RURAL ROUTE . Example 7 in RR 7.
rules table — The rules table contains a set of rules that maps address input sequence tokens to standardized output sequence. A
rule is defined as a set of input tokens followed by -1 (terminator) followed by set of output tokens followed by -1 followed by
number denoting kind of rule followed by ranking of rule.
Description
A rules table must have at least the following columns, though you are allowed to add more for your own uses.
rule text field denoting the rule. Details at PAGC Address Standardizer Rule records.
A rule consists of a set of non-negative integers representing input tokens, terminated by a -1, followed by an equal number
of non-negative integers representing postal attributes, terminated by a -1, followed by an integer representing a rule type,
followed by an integer representing the rank of the rule. The rules are ranked from 0 (lowest) to 17 (highest).
So for example the rule 2 0 2 22 3 -1 5 5 6 7 3 -1 2 6 maps to sequence of output tokens TYPE NUMBER
TYPE DIRECT QUALIF to the output sequence STREET STREET SUFTYP SUFDIR QUALIF. The rule is an ARC_C rule
of rank 6.
Numbers for corresponding output tokens are listed in stdaddr.
Input Tokens
Each rule starts with a set of input tokens followed by a terminator -1. Valid input tokens excerpted from PAGC Input Tokens
are as follows:
Form-Based Input Tokens
AMPERS (13). The ampersand (&) is frequently used to abbreviate the word "and".
DASH (9). A punctuation character.
DOUBLE (21). A sequence of two letters. Often used as identifiers.
FRACT (25). Fractions are sometimes used in civic numbers or unit numbers.
MIXED (23). An alphanumeric string that contains both letters and digits. Used for identifiers.
NUMBER (0). A string of digits.
ORD (15). Representations such as First or 1st. Often used in street names.
ORD (18). A single letter.
WORD (1). A word is a string of letters of arbitrary length. A single letter can be both a SINGLE and a WORD.
BOXH (14). Words used to denote post office boxes. For example Box or PO Box.
BUILDH (19). Words used to denote buildings or building complexes, usually as a prefix. For example: Tower in Tower 7A.
BUILDT (24). Words and abbreviations used to denote buildings or building complexes, usually as a suffix. For example:
Shopping Centre.
DIRECT (22). Words used to denote directions, for example North.
MILE (20). Words used to denote milepost addresses.
ROAD (6). Words and abbreviations used to denote highways and roads. For example: the Interstate in Interstate 5
RR (8). Words and abbreviations used to denote rural routes. RR.
TYPE (2). Words and abbreviation used to denote street typess. For example: ST or AVE.
UNITH (16). Words and abbreviation used to denote internal subaddresses. For example, APT or UNIT.
PCT (26). A 3 character sequence of number letter number. Identifies an LDU, the last 3 characters of a Canadian postal code.
Stopwords
STOPWORDS combine with WORDS. In rules a string of multiple WORDs and STOPWORDs will be represented by a single
WORD token.
STOPWORD (7). A word with low lexical significance, that can be omitted in parsing. For example: THE.
Output Tokens
After the first -1 (terminator), follows the output tokens and their order, followed by a terminator -1. Numbers for corresponding
output tokens are listed in stdaddr. What are allowed is dependent on kind of rule. Output tokens valid for each rule type are
listed in the section called “Rule Types and Rank”.
The final part of the rule is the rule type which is denoted by one of the following, followed by a rule rank. The rules are ranked
from 0 (lowest) to 17 (highest).
MACRO_C
(token number = "0"). The class of rules for parsing MACRO clauses such as PLACE STATE ZIP
MACRO_C output tokens (excerpted from http://www.pagcgeo.org/docs/html/pagc-12.html#--r-typ--.
POSTAL (token number "13"). (SADS elements "ZIP CODE" , "PLUS 4" ). This attribute is used for both the US Zip and the
Canadian Postal Codes.
MICRO_C
(token number = "1"). The class of rules for parsing full MICRO clauses (such as House, street, sufdir, predir, pretyp, suftype,
qualif) (ie ARC_C plus CIVIC_C). These rules are not used in the build phase.
MICRO_C output tokens (excerpted from http://www.pagcgeo.org/docs/html/pagc-12.html#--r-typ--.
HOUSE is a text (token number 1): This is the street number on a street. Example 75 in 75 State Street.
predir is text (token number 2): STREET NAME PRE-DIRECTIONAL such as North, South, East, West etc.
qual is text (token number 3): STREET NAME PRE-MODIFIER Example OLD in 3715 OLD HIGHWAY 99.
pretype is text (token number 4): STREET PREFIX TYPE
street is text (token number 5): STREET NAME
suftype is text (token number 6): STREET POST TYPE e.g. St, Ave, Cir. A street type following the root street name. Example
STREET in 75 State Street.
sufdir is text (token number 7): STREET POST-DIRECTIONAL A directional modifier that follows the street name.. Example
WEST in 3715 TENTH AVENUE WEST.
PostGIS 3.3.2 Manual 744 / 902
ARC_C
(token number = "2"). The class of rules for parsing MICRO clauses, excluding the HOUSE attribute. As such uses same set of
output tokens as MICRO_C minus the HOUSE token.
CIVIC_C
(token number = "3"). The class of rules for parsing the HOUSE attribute.
EXTRA_C
(token number = "4"). The class of rules for parsing EXTRA attributes - attributes excluded from geocoding. These rules are not
used in the build phase.
EXTRA_C output tokens (excerpted from http://www.pagcgeo.org/docs/html/pagc-12.html#--r-typ--.
lex table — A lex table is used to classify alphanumeric input and associate that input with (a) input tokens ( See the section
called “Input Tokens”) and (b) standardized representations.
Description
A lex (short for lexicon) table is used to classify alphanumeric input and associate that input with the section called “Input
Tokens” and (b) standardized representations. Things you will find in these tables are ONE mapped to stdword: 1.
A lex has at least the following columns in the table. You may add
gaz table — A gaz table is used to standardize place names and associate that input with (a) input tokens ( See the section called
“Input Tokens”) and (b) standardized representations.
PostGIS 3.3.2 Manual 745 / 902
Description
A gaz (short for gazeteer) table is used to standardize place names and associate that input with the section called “Input Tokens”
and (b) standardized representations. For example if you are in US, you may load these with State Names and associated
abbreviations.
A gaz table has at least the following columns in the table. You may add more columns if you wish for your own purposes.
14.1.4.1 parse_address
Synopsis
Description
Returns takes an address as input, and returns a record output consisting of fields num, street, street2, address1, city, state, zip,
zipplus, country.
Availability: 2.2.0
Examples
Single Addresss
SELECT num, street, city, zip, zipplus
FROM parse_address('1 Devonshire Place, Boston, MA 02109-1234') AS a;
Table of addresses
-- basic table
CREATE TABLE places(addid serial PRIMARY KEY, address text);
See Also
14.1.4.2 standardize_address
standardize_address — Returns an stdaddr form of an input address utilizing lex, gaz, and rule tables.
Synopsis
Description
Returns an stdaddr form of an input address utilizing lex table table name, gaz table, and rules table table names and an address.
Variant 1: Takes an address as a single line.
Variant 2: Takes an address as 2 parts. A micro consisting of standard first line of postal address e.g. house_num street,
and a macro consisting of standard postal second line of an address e.g city, state postal_code country.
Availability: 2.2.0
Examples
Variant 1: Single line address. This doesn’t work well with non-US addresses
SELECT house_num, name, suftype, city, country, state, unit FROM standardize_address(' ←-
us_lex',
'us_gaz', 'us_rules', 'One Devonshire Place, PH 301, Boston, MA 02109');
Using tables packaged with tiger geocoder. This example only works if you installed postgis_tiger_geocoder.
SELECT * FROM standardize_address('tiger.pagc_lex',
'tiger.pagc_gaz', 'tiger.pagc_rules', 'One Devonshire Place, PH 301, Boston, MA ←-
02109-1234');
Make easier to read we’ll dump output using hstore extension CREATE EXTENSION hstore; you need to install
SELECT (each(hstore(p))).*
FROM standardize_address('tiger.pagc_lex', 'tiger.pagc_gaz',
'tiger.pagc_rules', 'One Devonshire Place, PH 301, Boston, MA 02109') As p;
key | value
------------+-----------------
box |
city | BOSTON
name | DEVONSHIRE
qual |
unit | # PENTHOUSE 301
extra |
state | MA
predir |
sufdir |
country | USA
pretype |
suftype | PL
building |
postcode | 02109
house_num | 1
ruralroute |
(16 rows)
key | value
------------+-----------------
box |
city | BOSTON
name | DEVONSHIRE
qual |
unit | # PENTHOUSE 301
extra |
state | MA
predir |
sufdir |
country | USA
pretype |
suftype | PL
building |
postcode | 02109
house_num | 1
ruralroute |
(16 rows)
See Also
There are a couple other open source geocoders for PostGIS, that unlike tiger geocoder have the advantage of multi-country
geocoding support
• Nominatim uses OpenStreetMap gazeteer formatted data. It requires osm2pgsql for loading the data, PostgreSQL 8.4+ and
PostGIS 1.5+ to function. It is packaged as a webservice interface and seems designed to be called as a webservice. Just like
the tiger geocoder, it has both a geocoder and a reverse geocoder component. From the documentation, it is unclear if it has a
pure SQL interface like the tiger geocoder, or if a good deal of the logic is implemented in the web interface.
• GIS Graphy also utilizes PostGIS and like Nominatim works with OpenStreetMap (OSM) data. It comes with a loader to load
OSM data and similar to Nominatim is capable of geocoding not just US. Much like Nominatim, it runs as a webservice and
relies on Java 1.5, Servlet apps, Solr. GisGraphy is cross-platform and also has a reverse geocoder among some other neat
features.
14.2.1 Drop_Indexes_Generate_Script
Drop_Indexes_Generate_Script — Generates a script that drops all non-primary key and non-unique indexes on tiger schema
and user specified schema. Defaults schema to tiger_data if no schema is specified.
Synopsis
Description
Generates a script that drops all non-primary key and non-unique indexes on tiger schema and user specified schema. Defaults
schema to tiger_data if no schema is specified.
This is useful for minimizing index bloat that may confuse the query planner or take up unnecessary space. Use in combination
with Install_Missing_Indexes to add just the indexes used by the geocoder.
Availability: 2.0.0
Examples
See Also
Install_Missing_Indexes, Missing_Indexes_Generate_Script
14.2.2 Drop_Nation_Tables_Generate_Script
Drop_Nation_Tables_Generate_Script — Generates a script that drops all tables in the specified schema that start with county_all,
state_all or state code followed by county or state.
Synopsis
Description
Generates a script that drops all tables in the specified schema that start with county_all, state_all or state code followed
by county or state. This is needed if you are upgrading from tiger_2010 to tiger_2011 data.
Availability: 2.1.0
Examples
SELECT drop_nation_tables_generate_script();
DROP TABLE tiger_data.county_all;
DROP TABLE tiger_data.county_all_lookup;
DROP TABLE tiger_data.state_all;
DROP TABLE tiger_data.ma_county;
DROP TABLE tiger_data.ma_state;
See Also
Loader_Generate_Nation_Script
14.2.3 Drop_State_Tables_Generate_Script
Drop_State_Tables_Generate_Script — Generates a script that drops all tables in the specified schema that are prefixed with the
state abbreviation. Defaults schema to tiger_data if no schema is specified.
PostGIS 3.3.2 Manual 750 / 902
Synopsis
Description
Generates a script that drops all tables in the specified schema that are prefixed with the state abbreviation. Defaults schema to
tiger_data if no schema is specified. This function is useful for dropping tables of a state just before you reload a state in
case something went wrong during your previous load.
Availability: 2.0.0
Examples
SELECT drop_state_tables_generate_script('PA');
DROP TABLE tiger_data.pa_addr;
DROP TABLE tiger_data.pa_county;
DROP TABLE tiger_data.pa_county_lookup;
DROP TABLE tiger_data.pa_cousub;
DROP TABLE tiger_data.pa_edges;
DROP TABLE tiger_data.pa_faces;
DROP TABLE tiger_data.pa_featnames;
DROP TABLE tiger_data.pa_place;
DROP TABLE tiger_data.pa_state;
DROP TABLE tiger_data.pa_zip_lookup_base;
DROP TABLE tiger_data.pa_zip_state;
DROP TABLE tiger_data.pa_zip_state_loc;
See Also
Loader_Generate_Script
14.2.4 Geocode
Geocode — Takes in an address as a string (or other normalized address) and outputs a set of possible locations which include a
point geometry in NAD 83 long lat, a normalized address for each, and the rating. The lower the rating the more likely the match.
Results are sorted by lowest rating first. Can optionally pass in maximum results, defaults to 10, and restrict_region (defaults to
NULL)
Synopsis
setof record geocode(varchar address, integer max_results=10, geometry restrict_region=NULL, norm_addy OUT addy, geom-
etry OUT geomout, integer OUT rating);
setof record geocode(norm_addy in_addy, integer max_results=10, geometry restrict_region=NULL, norm_addy OUT addy,
geometry OUT geomout, integer OUT rating);
Description
Takes in an address as a string (or already normalized address) and outputs a set of possible locations which include a point
geometry in NAD 83 long lat, a normalized_address (addy) for each, and the rating. The lower the rating the more
likely the match. Results are sorted by lowest rating first. Uses Tiger data (edges,faces,addr), PostgreSQL fuzzy string matching
(soundex,levenshtein) and PostGIS line interpolation functions to interpolate address along the Tiger edges. The higher the rating
the less likely the geocode is right. The geocoded point is defaulted to offset 10 meters from center-line off to side (L/R) of street
address is located on.
PostGIS 3.3.2 Manual 751 / 902
Enhanced: 2.0.0 to support Tiger 2010 structured data and revised some logic to improve speed, accuracy of geocoding, and
to offset point from centerline to side of street address is located on. The new parameter max_results useful for specifying
number of best results or just returning the best result.
Examples: Basic
The below examples timings are on a 3.0 GHZ single processor Windows 7 machine with 2GB ram running PostgreSQL
9.1rc1/PostGIS 2.0 loaded with all of MA,MN,CA, RI state Tiger data loaded.
Exact matches are faster to compute (61ms)
SELECT g.rating, ST_X(g.geomout) As lon, ST_Y(g.geomout) As lat,
(addy).address As stno, (addy).streetname As street,
(addy).streettypeabbrev As styp, (addy).location As city, (addy).stateabbrev As st,( ←-
addy).zip
FROM geocode('75 State Street, Boston MA 02109', 1) As g;
rating | lon | lat | stno | street | styp | city | st | zip
--------+-------------------+----------------+------+--------+------+--------+----+-------
0 | -71.0557505845646 | 42.35897920691 | 75 | State | St | Boston | MA | 02109
Even if zip is not passed in the geocoder can guess (took about 122-150 ms)
SELECT g.rating, ST_AsText(ST_SnapToGrid(g.geomout,0.00001)) As wktlonlat,
(addy).address As stno, (addy).streetname As street,
(addy).streettypeabbrev As styp, (addy).location As city, (addy).stateabbrev As st,( ←-
addy).zip
FROM geocode('226 Hanover Street, Boston, MA',1) As g;
rating | wktlonlat | stno | street | styp | city | st | zip
--------+---------------------------+------+---------+------+--------+----+-------
1 | POINT(-71.05528 42.36316) | 226 | Hanover | St | Boston | MA | 02113
Can handle misspellings and provides more than one possible solution with ratings and takes longer (500ms).
SELECT g.rating, ST_AsText(ST_SnapToGrid(g.geomout,0.00001)) As wktlonlat,
(addy).address As stno, (addy).streetname As street,
(addy).streettypeabbrev As styp, (addy).location As city, (addy).stateabbrev As st,( ←-
addy).zip
FROM geocode('31 - 37 Stewart Street, Boston, MA 02116',1) As g;
rating | wktlonlat | stno | street | styp | city | st | zip
--------+---------------------------+------+--------+------+--------+----+-------
70 | POINT(-71.06466 42.35114) | 31 | Stuart | St | Boston | MA | 02116
Using to do a batch geocode of addresses. Easiest is to set max_results=1. Only process those not yet geocoded (have no
rating).
CREATE TABLE addresses_to_geocode(addid serial PRIMARY KEY, address text,
lon numeric, lat numeric, new_address text, rating integer);
-- only update the first 3 addresses (323-704 ms - there are caching and shared memory ←-
effects so first geocode you do is always slower) --
-- for large numbers of addresses you don't want to update all at once
-- since the whole geocode must commit at once
-- For this example we rejoin with LEFT JOIN
PostGIS 3.3.2 Manual 752 / 902
result
-----
Query returned successfully: 3 rows affected, 480 ms execution time.
1 | 529 Main Street, Boston MA, 02129 | -71.07177 | 42.38357 | 529 Main St, ←-
Boston, MA 02129 | 0
2 | 77 Massachusetts Avenue, Cambridge, MA 02139 | -71.09396 | 42.35961 | 77 ←-
Massachusetts Ave, Cambridge, MA 02139 | 0
3 | 25 Wizard of Oz, Walaford, KS 99912323 | -97.92913 | 38.12717 | Willowbrook, ←-
KS 67502 | 108
(3 rows)
Time: 622.939 ms
See Also
14.2.5 Geocode_Intersection
Geocode_Intersection — Takes in 2 streets that intersect and a state, city, zip, and outputs a set of possible locations on the first
cross street that is at the intersection, also includes a geomout as the point location in NAD 83 long lat, a normalized_address
PostGIS 3.3.2 Manual 753 / 902
(addy) for each location, and the rating. The lower the rating the more likely the match. Results are sorted by lowest rating first.
Can optionally pass in maximum results, defaults to 10. Uses Tiger data (edges, faces, addr), PostgreSQL fuzzy string matching
(soundex, levenshtein).
Synopsis
setof record geocode_intersection(text roadway1, text roadway2, text in_state, text in_city, text in_zip, integer max_results=10,
norm_addy OUT addy, geometry OUT geomout, integer OUT rating);
Description
Takes in 2 streets that intersect and a state, city, zip, and outputs a set of possible locations on the first cross street that is at the
intersection, also includes a point geometry in NAD 83 long lat, a normalized address for each location, and the rating. The lower
the rating the more likely the match. Results are sorted by lowest rating first. Can optionally pass in maximum results, defaults
to 10. Returns normalized_address (addy) for each, geomout as the point location in nad 83 long lat, and the rating.
The lower the rating the more likely the match. Results are sorted by lowest rating first. Uses Tiger data (edges,faces,addr),
PostgreSQL fuzzy string matching (soundex,levenshtein)
Availability: 2.0.0
Examples: Basic
The below examples timings are on a 3.0 GHZ single processor Windows 7 machine with 2GB ram running PostgreSQL 9.0/Post-
GIS 1.5 loaded with all of MA state Tiger data loaded. Currently a bit slow (3000 ms)
Testing on Windows 2003 64-bit 8GB on PostGIS 2.0 PostgreSQL 64-bit Tiger 2011 data loaded -- (41ms)
SELECT pprint_addy(addy), st_astext(geomout),rating
FROM geocode_intersection( 'Haverford St','Germania St', 'MA', 'Boston', ←-
'02130',1);
pprint_addy | st_astext | rating
----------------------------------+----------------------------+--------
98 Haverford St, Boston, MA 02130 | POINT(-71.101375 42.31376) | 0
Even if zip is not passed in the geocoder can guess (took about 3500 ms on the windows 7 box), on the windows 2003 64-bit 741
ms
SELECT pprint_addy(addy), st_astext(geomout),rating
FROM geocode_intersection('Weld', 'School', 'MA', 'Boston');
pprint_addy | st_astext | rating
-------------------------------+--------------------------+--------
98 Weld Ave, Boston, MA 02119 | POINT(-71.099 42.314234) | 3
99 Weld Ave, Boston, MA 02119 | POINT(-71.099 42.314234) | 3
See Also
14.2.6 Get_Geocode_Setting
Synopsis
Description
Returns value of specific setting stored in tiger.geocode_settings table. Settings allow you to toggle debugging of functions. Later
plans will be to control rating with settings. Current list of settings are as follows:
name | setting | unit | category | ←-
short_desc
--------------------------------+---------+---------+-----------+------------------------------------
Changed: 2.2.0 : default settings are now kept in a table called geocode_settings_default. Use customized settingsa are in
geocode_settings and only contain those that have been set by user.
Availability: 2.1.0
See Also
Set_Geocode_Setting
14.2.7 Get_Tract
Get_Tract — Returns census tract or field from tract table of where the geometry is located. Default to returning short name of
tract.
Synopsis
Description
Given a geometry will return the census tract location of that geometry. NAD 83 long lat is assumed if no spatial ref sys is
specified.
Note
This function uses the census tract which is not loaded by default. If you have already loaded your state table, you
can load tract as well as bg, and tabblock using the Loader_Generate_Census_Script script.
If you have not loaded your state data yet and want these additional tables loaded, do the following
UPDATE tiger.loader_lookuptables SET load = true WHERE load = false AND lookup_name ←-
IN('tract', 'bg', 'tabblock');
Availability: 2.0.0
Examples: Basic
See Also
Geocode>
14.2.8 Install_Missing_Indexes
Install_Missing_Indexes — Finds all tables with key columns used in geocoder joins and filter conditions that are missing used
indexes on those columns and will add them.
Synopsis
boolean Install_Missing_Indexes();
Description
Finds all tables in tiger and tiger_data schemas with key columns used in geocoder joins and filters that are missing
indexes on those columns and will output the SQL DDL to define the index for those tables and then execute the generated
script. This is a helper function that adds new indexes needed to make queries faster that may have been missing during the load
process. This function is a companion to Missing_Indexes_Generate_Script that in addition to generating the create index script,
also executes it. It is called as part of the update_geocode.sql upgrade script.
Availability: 2.0.0
PostGIS 3.3.2 Manual 756 / 902
Examples
SELECT install_missing_indexes();
install_missing_indexes
-------------------------
t
See Also
Loader_Generate_Script, Missing_Indexes_Generate_Script
14.2.9 Loader_Generate_Census_Script
Loader_Generate_Census_Script — Generates a shell script for the specified platform for the specified states that will download
Tiger census state tract, bg, and tabblocks data tables, stage and load into tiger_data schema. Each state script is returned as
a separate record.
Synopsis
Description
Generates a shell script for the specified platform for the specified states that will download Tiger data census state tract, block
groups bg, and tabblocks data tables, stage and load into tiger_data schema. Each state script is returned as a separate
record.
It uses unzip on Linux (7-zip on Windows by default) and wget to do the downloading. It uses Section 4.7.2 to load in the data.
Note the smallest unit it does is a whole state. It will only process the files in the staging and temp folders.
It uses the following control tables to control the process and different OS shell syntax variations.
1. loader_variables keeps track of various variables such as census site, year, data and staging schemas
2. loader_platform profiles of various platforms and where the various executables are located. Comes with windows
and linux. More can be added.
3. loader_lookuptables each record defines a kind of table (state, county), whether to process records in it and how
to load them in. Defines the steps to import data, stage data, add, removes columns, indexes, and constraints for each.
Each table is prefixed with the state and inherits from a table in the tiger schema. e.g. creates tiger_data.ma_faces
which inherits from tiger.faces
Availability: 2.0.0
Note
Loader_Generate_Script includes this logic, but if you installed tiger geocoder prior to PostGIS 2.0.0 alpha5, you’ll need
to run this on the states you have already done to get these additional tables.
PostGIS 3.3.2 Manual 757 / 902
Examples
Generate script to load up data for select states in Windows shell script format.
SELECT loader_generate_census_script(ARRAY['MA'], 'windows');
-- result --
set STATEDIR="\gisdata\www2.census.gov\geo\pvs\tiger2010st\25_Massachusetts"
set TMPDIR=\gisdata\temp\
set UNZIPTOOL="C:\Program Files\7-Zip\7z.exe"
set WGETTOOL="C:\wget\wget.exe"
set PGBIN=C:\projects\pg\pg91win\bin\
set PGPORT=5432
set PGHOST=localhost
set PGUSER=postgres
set PGPASSWORD=yourpasswordhere
set PGDATABASE=tiger_postgis20
set PSQL="%PGBIN%psql"
set SHP2PGSQL="%PGBIN%shp2pgsql"
cd \gisdata
Generate sh script
STATEDIR="/gisdata/www2.census.gov/geo/pvs/tiger2010st/25_Massachusetts"
TMPDIR="/gisdata/temp/"
UNZIPTOOL=unzip
WGETTOOL="/usr/bin/wget"
export PGBIN=/usr/pgsql-9.0/bin
export PGPORT=5432
export PGHOST=localhost
export PGUSER=postgres
export PGPASSWORD=yourpasswordhere
export PGDATABASE=geocoder
PSQL=${PGBIN}/psql
SHP2PGSQL=${PGBIN}/shp2pgsql
cd /gisdata
cd $STATEDIR
for z in *.zip; do $UNZIPTOOL -o -d $TMPDIR $z; done
:
:
See Also
Loader_Generate_Script
14.2.10 Loader_Generate_Script
Loader_Generate_Script — Generates a shell script for the specified platform for the specified states that will download Tiger
data, stage and load into tiger_data schema. Each state script is returned as a separate record. Latest version supports Tiger
2010 structural changes and also loads census tract, block groups, and blocks tables.
Synopsis
Description
Generates a shell script for the specified platform for the specified states that will download Tiger data, stage and load into
tiger_data schema. Each state script is returned as a separate record.
It uses unzip on Linux (7-zip on Windows by default) and wget to do the downloading. It uses Section 4.7.2 to load in the data.
Note the smallest unit it does is a whole state, but you can overwrite this by downloading the files yourself. It will only process
the files in the staging and temp folders.
It uses the following control tables to control the process and different OS shell syntax variations.
1. loader_variables keeps track of various variables such as census site, year, data and staging schemas
2. loader_platform profiles of various platforms and where the various executables are located. Comes with windows
and linux. More can be added.
3. loader_lookuptables each record defines a kind of table (state, county), whether to process records in it and how
to load them in. Defines the steps to import data, stage data, add, removes columns, indexes, and constraints for each.
Each table is prefixed with the state and inherits from a table in the tiger schema. e.g. creates tiger_data.ma_faces
which inherits from tiger.faces
Availability: 2.0.0 to support Tiger 2010 structured data and load census tract (tract), block groups (bg), and blocks (tabblocks)
tables .
Note
If you are using pgAdmin 3, be warned that by default pgAdmin 3 truncates long text. To fix, change File -> Options ->
Query Tool -> Query Editor - > Max. characters per column to larger than 50000 characters.
PostGIS 3.3.2 Manual 759 / 902
Examples
Using psql where gistest is your database and /gisdata/data_load.sh is the file to create with the shell commands to run.
psql -U postgres -h localhost -d gistest -A -t \
-c "SELECT Loader_Generate_Script(ARRAY['MA'], 'gistest')" > /gisdata/data_load.sh;
Generate script to load up data for 2 states in Windows shell script format.
SELECT loader_generate_script(ARRAY['MA','RI'], 'windows') AS result;
-- result --
set TMPDIR=\gisdata\temp\
set UNZIPTOOL="C:\Program Files\7-Zip\7z.exe"
set WGETTOOL="C:\wget\wget.exe"
set PGBIN=C:\Program Files\PostgreSQL\9.4\bin\
set PGPORT=5432
set PGHOST=localhost
set PGUSER=postgres
set PGPASSWORD=yourpasswordhere
set PGDATABASE=geocoder
set PSQL="%PGBIN%psql"
set SHP2PGSQL="%PGBIN%shp2pgsql"
cd \gisdata
cd \gisdata
%WGETTOOL% ftp://ftp2.census.gov/geo/tiger/TIGER2015/PLACE/tl_*_25_* --no-parent --relative ←-
--recursive --level=2 --accept=zip --mirror --reject=html
cd \gisdata/ftp2.census.gov/geo/tiger/TIGER2015/PLACE
:
:
Generate sh script
SELECT loader_generate_script(ARRAY['MA','RI'], 'sh') AS result;
-- result --
TMPDIR="/gisdata/temp/"
UNZIPTOOL=unzip
WGETTOOL="/usr/bin/wget"
export PGBIN=/usr/lib/postgresql/9.4/bin
-- variables used by psql: https://www.postgresql.org/docs/current/static/libpq-envars.html
export PGPORT=5432
export PGHOST=localhost
export PGUSER=postgres
export PGPASSWORD=yourpasswordhere
export PGDATABASE=geocoder
PSQL=${PGBIN}/psql
SHP2PGSQL=${PGBIN}/shp2pgsql
cd /gisdata
cd /gisdata
wget ftp://ftp2.census.gov/geo/tiger/TIGER2015/PLACE/tl_*_25_* --no-parent --relative -- ←-
recursive --level=2 --accept=zip --mirror --reject=html
cd /gisdata/ftp2.census.gov/geo/tiger/TIGER2015/PLACE
rm -f ${TMPDIR}/*.*
:
:
See Also
14.2.11 Loader_Generate_Nation_Script
Loader_Generate_Nation_Script — Generates a shell script for the specified platform that loads in the county and state lookup
tables.
Synopsis
Description
Generates a shell script for the specified platform that loads in the county_all, county_all_lookup, state_all tables
into tiger_data schema. These inherit respectively from the county, county_lookup, state tables in tiger schema.
It uses unzip on Linux (7-zip on Windows by default) and wget to do the downloading. It uses Section 4.7.2 to load in the data.
It uses the following control tables tiger.loader_platform, tiger.loader_variables, and tiger.loader_lookupt
to control the process and different OS shell syntax variations.
1. loader_variables keeps track of various variables such as census site, year, data and staging schemas
2. loader_platform profiles of various platforms and where the various executables are located. Comes with windows
and linux/unix. More can be added.
3. loader_lookuptables each record defines a kind of table (state, county), whether to process records in it and how
to load them in. Defines the steps to import data, stage data, add, removes columns, indexes, and constraints for each.
Each table is prefixed with the state and inherits from a table in the tiger schema. e.g. creates tiger_data.ma_faces
which inherits from tiger.faces
Enhanced: 2.4.1 zip code 5 tabulation area (zcta5) load step was fixed and when enabled, zcta5 data is loaded as a single table
called zcta5_all as part of the nation script load.
Availability: 2.1.0
Note
If you want zip code 5 tabulation area (zcta5) to be included in your nation script load, do the following:
UPDATE tiger.loader_lookuptables SET load = true WHERE table_name = 'zcta510';
Note
If you were running tiger_2010 version and you want to reload as state with newer tiger data, you’ll need to for the
very first load generate and run drop statements Drop_Nation_Tables_Generate_Script before you run this script.
Examples
See Also
Loader_Generate_Script, Drop_Nation_Tables_Generate_Script
14.2.12 Missing_Indexes_Generate_Script
Missing_Indexes_Generate_Script — Finds all tables with key columns used in geocoder joins that are missing indexes on those
columns and will output the SQL DDL to define the index for those tables.
Synopsis
text Missing_Indexes_Generate_Script();
Description
Finds all tables in tiger and tiger_data schemas with key columns used in geocoder joins that are missing indexes on
those columns and will output the SQL DDL to define the index for those tables. This is a helper function that adds new indexes
needed to make queries faster that may have been missing during the load process. As the geocoder is improved, this function
will be updated to accommodate new indexes being used. If this function outputs nothing, it means all your tables have what we
think are the key indexes already in place.
Availability: 2.0.0
Examples
SELECT missing_indexes_generate_script();
-- output: This was run on a database that was created before many corrections were made to ←-
the loading script ---
CREATE INDEX idx_tiger_county_countyfp ON tiger.county USING btree(countyfp);
CREATE INDEX idx_tiger_cousub_countyfp ON tiger.cousub USING btree(countyfp);
CREATE INDEX idx_tiger_edges_tfidr ON tiger.edges USING btree(tfidr);
CREATE INDEX idx_tiger_edges_tfidl ON tiger.edges USING btree(tfidl);
CREATE INDEX idx_tiger_zip_lookup_all_zip ON tiger.zip_lookup_all USING btree(zip);
CREATE INDEX idx_tiger_data_ma_county_countyfp ON tiger_data.ma_county USING btree(countyfp ←-
);
CREATE INDEX idx_tiger_data_ma_cousub_countyfp ON tiger_data.ma_cousub USING btree(countyfp ←-
);
CREATE INDEX idx_tiger_data_ma_edges_countyfp ON tiger_data.ma_edges USING btree(countyfp);
CREATE INDEX idx_tiger_data_ma_faces_countyfp ON tiger_data.ma_faces USING btree(countyfp);
See Also
Loader_Generate_Script, Install_Missing_Indexes
14.2.13 Normalize_Address
Normalize_Address — Given a textual street address, returns a composite norm_addy type that has road suffix, prefix and type
standardized, street, streetname etc. broken into separate fields. This function will work with just the lookup data packaged with
the tiger_geocoder (no need for tiger census data).
Synopsis
Description
Given a textual street address, returns a composite norm_addy type that has road suffix, prefix and type standardized, street,
streetname etc. broken into separate fields. This is the first step in the geocoding process to get all addresses into normalized
postal form. No other data is required aside from what is packaged with the geocoder.
This function just uses the various direction/state/suffix lookup tables preloaded with the tiger_geocoder and located in the
tiger schema, so it doesn’t need you to download tiger census data or any other additional data to make use of it. You may find
the need to add more abbreviations or alternative namings to the various lookup tables in the tiger schema.
It uses various control lookup tables located in tiger schema to normalize the input address.
Fields in the norm_addy type object returned by this function in this order where () indicates a field required by the geocoder,
[] indicates an optional field:
(address) [predirAbbrev] (streetName) [streetTypeAbbrev] [postdirAbbrev] [internal] [location] [stateAbbrev] [zip] [parsed]
[zip4] [address_alphanumeric]
Enhanced: 2.4.0 norm_addy object includes additional fields zip4 and address_alphanumeric.
Examples
Output select fields. Use Pprint_Addy if you want a pretty textual output.
SELECT address As orig, (g.na).streetname, (g.na).streettypeabbrev
FROM (SELECT address, normalize_address(address) As na
FROM addresses_to_geocode) As g;
See Also
Geocode, Pprint_Addy
14.2.14 Pagc_Normalize_Address
Pagc_Normalize_Address — Given a textual street address, returns a composite norm_addy type that has road suffix, prefix
and type standardized, street, streetname etc. broken into separate fields. This function will work with just the lookup data
packaged with the tiger_geocoder (no need for tiger census data). Requires address_standardizer extension.
Synopsis
Description
Given a textual street address, returns a composite norm_addy type that has road suffix, prefix and type standardized, street,
streetname etc. broken into separate fields. This is the first step in the geocoding process to get all addresses into normalized
postal form. No other data is required aside from what is packaged with the geocoder.
This function just uses the various pagc_* lookup tables preloaded with the tiger_geocoder and located in the tiger schema,
so it doesn’t need you to download tiger census data or any other additional data to make use of it. You may find the need to add
more abbreviations or alternative namings to the various lookup tables in the tiger schema.
It uses various control lookup tables located in tiger schema to normalize the input address.
Fields in the norm_addy type object returned by this function in this order where () indicates a field required by the geocoder,
[] indicates an optional field:
There are slight variations in casing and formatting over the Normalize_Address.
Availability: 2.1.0
11. zip4 last 4 digits of a 9 digit zip code. Availability: PostGIS 2.4.0.
12. address_alphanumeric Full street number even if it has alpha characters like 17R. Parsing of this is better using
Pagc_Normalize_Address function. Availability: PostGIS 2.4.0.
Examples
Batch call. There are currently speed issues with the way postgis_tiger_geocoder wraps the address_standardizer. These will
hopefully be resolved in later editions. To work around them, if you need speed for batch geocoding to call generate a normaddy
in batch mode, you are encouraged to directly call the address_standardizer standardize_address function as shown below which
is similar exercise to what we did in Normalize_Address that uses data created in Geocode.
WITH g AS (SELECT address, ROW((sa).house_num, (sa).predir, (sa).name
, (sa).suftype, (sa).sufdir, (sa).unit , (sa).city, (sa).state, (sa).postcode, true):: ←-
norm_addy As na
FROM (SELECT address, standardize_address('tiger.pagc_lex'
, 'tiger.pagc_gaz'
, 'tiger.pagc_rules', address) As sa
FROM addresses_to_geocode) As g)
SELECT address As orig, (g.na).streetname, (g.na).streettypeabbrev
FROM g;
See Also
Normalize_Address, Geocode
14.2.15 Pprint_Addy
Pprint_Addy — Given a norm_addy composite type object, returns a pretty print representation of it. Usually used in conjunc-
tion with normalize_address.
PostGIS 3.3.2 Manual 765 / 902
Synopsis
Description
Given a norm_addy composite type object, returns a pretty print representation of it. No other data is required aside from what
is packaged with the geocoder.
Usually used in conjunction with Normalize_Address.
Examples
orig | pretty_address
-----------------------------------------------------+------------------------------------------- ←-
529 Main Street, Boston MA, 02129 | 529 Main St, Boston MA, 02129
77 Massachusetts Avenue, Cambridge, MA 02139 | 77 Massachusetts Ave, Cambridge, MA ←-
02139
28 Capen Street, Medford, MA | 28 Capen St, Medford, MA
124 Mount Auburn St, Cambridge, Massachusetts 02138 | 124 Mount Auburn St, Cambridge, MA ←-
02138
950 Main Street, Worcester, MA 01610 | 950 Main St, Worcester, MA 01610
See Also
Normalize_Address
14.2.16 Reverse_Geocode
Reverse_Geocode — Takes a geometry point in a known spatial ref sys and returns a record containing an array of theoretically
possible addresses and an array of cross streets. If include_strnum_range = true, includes the street range in the cross streets.
Synopsis
record Reverse_Geocode(geometry pt, boolean include_strnum_range=false, geometry[] OUT intpt, norm_addy[] OUT addy,
varchar[] OUT street);
PostGIS 3.3.2 Manual 766 / 902
Description
Takes a geometry point in a known spatial ref and returns a record containing an array of theoretically possible addresses and
an array of cross streets. If include_strnum_range = true, includes the street range in the cross streets. include_strnum_range
defaults to false if not passed in. Addresses are sorted according to which road a point is closest to so first address is most likely
the right one.
Why do we say theoretical instead of actual addresses. The Tiger data doesn’t have real addresses, but just street ranges. As such
the theoretical address is an interpolated address based on the street ranges. Like for example interpolating one of my addresses
returns a 26 Court St. and 26 Court Sq., though there is no such place as 26 Court Sq. This is because a point may be at a corner
of 2 streets and thus the logic interpolates along both streets. The logic also assumes addresses are equally spaced along a street,
which of course is wrong since you can have a municipal building taking up a good chunk of the street range and the rest of the
buildings are clustered at the end.
Note: Hmm this function relies on Tiger data. If you have not loaded data covering the region of this point, then hmm you will
get a record filled with NULLS.
Returned elements of the record are as follows:
1. intpt is an array of points: These are the center line points on the street closest to the input point. There are as many
points as there are addresses.
2. addy is an array of norm_addy (normalized addresses): These are an array of possible addresses that fit the input point.
The first one in the array is most likely. Generally there should be only one, except in the case when a point is at the corner
of 2 or 3 streets, or the point is somewhere on the road and not off to the side.
3. street an array of varchar: These are cross streets (or the street) (streets that intersect or are the street the point is
projected to be on).
Enhanced: 2.4.1 if optional zcta5 dataset is loaded, the reverse_geocode function can resolve to state and zip even if the specific
state data is not loaded. Refer to Loader_Generate_Nation_Script for details on loading zcta5 data.
Availability: 2.0.0
Examples
Example of a point at the corner of two streets, but closest to one. This is approximate location of MIT: 77 Massachusetts Ave,
Cambridge, MA 02139 Note that although we don’t have 3 streets, PostgreSQL will just return null for entries above our upper
bound so safe to use. This includes street ranges
SELECT pprint_addy(r.addy[1]) As st1, pprint_addy(r.addy[2]) As st2, pprint_addy(r.addy[3]) ←-
As st3,
array_to_string(r.street, ',') As cross_streets
FROM reverse_geocode(ST_GeomFromText('POINT(-71.093902 42.359446)',4269),true) As r ←-
;
result
------
st1 | st2 | st3 | cross_streets
-------------------------------------------+-----+-----+---------------------------------------------
Here we choose not to include the address ranges for the cross streets and picked a location really really close to a corner of 2
streets thus could be known by two different addresses.
SELECT pprint_addy(r.addy[1]) As st1, pprint_addy(r.addy[2]) As st2,
pprint_addy(r.addy[3]) As st3, array_to_string(r.street, ',') As cross_str
FROM reverse_geocode(ST_GeomFromText('POINT(-71.06941 42.34225)',4269)) As r;
PostGIS 3.3.2 Manual 767 / 902
result
--------
st1 | st2 | st3 | cross_str
---------------------------------+---------------------------------+-----+------------------------ ←
For this one we reuse our geocoded example from Geocode and we only want the primary address and at most 2 cross streets.
SELECT actual_addr, lon, lat, pprint_addy((rg).addy[1]) As int_addr1,
(rg).street[1] As cross1, (rg).street[2] As cross2
FROM (SELECT address As actual_addr, lon, lat,
reverse_geocode( ST_SetSRID(ST_Point(lon,lat),4326) ) As rg
FROM addresses_to_geocode WHERE rating > -1) As foo;
529 Main Street, Boston MA, 02129 | -71.07181 | 42.38359 | 527 Main St, ←-
Boston, MA 02129 | Medford St |
77 Massachusetts Avenue, Cambridge, MA 02139 | -71.09428 | 42.35988 | 77 ←-
Massachusetts Ave, Cambridge, MA 02139 | Vassar St |
26 Capen Street, Medford, MA | -71.12377 | 42.41101 | 9 Edison Ave, ←-
Medford, MA 02155 | Capen St | Tesla Ave
124 Mount Auburn St, Cambridge, Massachusetts 02138 | -71.12304 | 42.37328 | 3 University ←-
Rd, Cambridge, MA 02138 | Mount Auburn St |
950 Main Street, Worcester, MA 01610 | -71.82368 | 42.24956 | 3 Maywood St, ←-
Worcester, MA 01603 | Main St | Maywood Pl
See Also
14.2.17 Topology_Load_Tiger
Topology_Load_Tiger — Loads a defined region of tiger data into a PostGIS Topology and transforming the tiger data to spatial
reference of the topology and snapping to the precision tolerance of the topology.
Synopsis
Description
Loads a defined region of tiger data into a PostGIS Topology. The faces, nodes and edges are transformed to the spatial reference
system of the target topology and points are snapped to the tolerance of the target topology. The created faces, nodes, edges
maintain the same ids as the original Tiger data faces, nodes, edges so that datasets can be in the future be more easily reconciled
with tiger data. Returns summary details about the process.
This would be useful for example for redistricting data where you require the newly formed polygons to follow the center lines
of streets and for the resulting polygons not to overlap.
PostGIS 3.3.2 Manual 768 / 902
Note
This function relies on Tiger data as well as the installation of the PostGIS topology module. For more information, refer
to Chapter 10 and Section 2.2.3. If you have not loaded data covering the region of interest, then no topology records
will be created. This function will also fail if you have not created a topology using the topology functions.
Note
Most topology validation errors are a result of tolerance issues where after transformation the edges points don’t quite
line up or overlap. To remedy the situation you may want to increase or lower the precision if you get topology validation
failures.
Required arguments:
Availability: 2.0.0
Create a topology for Boston, Massachusetts in Mass State Plane Feet (2249) with tolerance 0.25 feet and then load in Boston
city tiger faces, edges, nodes.
SELECT topology.CreateTopology('topo_boston', 2249, 0.25);
createtopology
--------------
15
-- 60,902 ms ~ 1 minute on windows 7 desktop running 9.1 (with 5 states tiger data loaded)
SELECT tiger.topology_load_tiger('topo_boston', 'place', '2507000');
-- topology_loader_tiger --
29722 edges holding in temporary. 11108 faces added. 1875 edges of faces added. 20576 ←-
nodes added.
19962 nodes contained in a face. 0 edge start end corrected. 31597 edges added.
-- 41 ms --
SELECT topology.TopologySummary('topo_boston');
-- topologysummary--
Topology topo_boston (15), SRID 2249, precision 0.25
20576 nodes, 31597 edges, 11109 faces, 0 topogeoms in 0 layers
Create a topology for Suffolk, Massachusetts in Mass State Plane Meters (26986) with tolerance 0.25 meters and then load in
Suffolk county tiger faces, edges, nodes.
PostGIS 3.3.2 Manual 769 / 902
-- 33,606 ms to validate --
SELECT * FROM
topology.ValidateTopology('topo_suffolk');
See Also
14.2.18 Set_Geocode_Setting
Synopsis
Description
Sets value of specific setting stored in tiger.geocode_settings table. Settings allow you to toggle debugging of func-
tions. Later plans will be to control rating with settings. Current list of settings are listed in Get_Geocode_Setting.
Availability: 2.1.0
If you run Geocode when this function is true, the NOTICE log will output timing and queries.
SELECT set_geocode_setting('debug_geocode_address', 'true') As result;
result
---------
true
PostGIS 3.3.2 Manual 770 / 902
See Also
Get_Geocode_Setting
PostGIS 3.3.2 Manual 771 / 902
Chapter 15
The functions given below are spatial aggregate functions provided with PostGIS that can be used just like any other sql aggregate
function such as sum, average.
The functions given below are spatial window functions provided with PostGIS that can be used just like any other sql window
function such as row_numer(), lead(), lag(). All these require an SQL OVER() clause.
• ST_ClusterDBSCAN - Window function that returns a cluster id for each input geometry using the DBSCAN algorithm.
• ST_ClusterKMeans - Window function that returns a cluster id for each input geometry using the K-means algorithm.
PostGIS 3.3.2 Manual 772 / 902
The functions given below are PostGIS functions that conform to the SQL/MM 3 standard
• ST_3DArea - Computes area of 3D surface geometries. Will return 0 for solids. This method implements the SQL/MM
specification. SQL-MM IEC 13249-3: 8.1, 10.5
• ST_3DDWithin - Tests if two 3D geometries are within a given 3D distance This method implements the SQL/MM specifica-
tion. SQL-MM ?
• ST_3DDifference - Perform 3D difference This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1
• ST_3DDistance - Returns the 3D cartesian minimum distance (based on spatial ref) between two geometries in projected units.
This method implements the SQL/MM specification. SQL-MM ISO/IEC 13249-3
• ST_3DIntersection - Perform 3D intersection This method implements the SQL/MM specification. SQL-MM IEC 13249-3:
5.1
• ST_3DIntersects - Tests if two geometries spatially intersect in 3D - only for points, linestrings, polygons, polyhedral surface
(area). This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1
• ST_3DLength - Returns the 3D length of a linear geometry. This method implements the SQL/MM specification. SQL-MM
IEC 13249-3: 7.1, 10.3
• ST_3DPerimeter - Returns the 3D perimeter of a polygonal geometry. This method implements the SQL/MM specification.
SQL-MM ISO/IEC 13249-3: 8.1, 10.5
• ST_3DUnion - Perform 3D union. This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1
• ST_AddEdgeModFace - Add a new edge and, if in doing so it splits a face, modify the original face and add a new face. This
method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.13
• ST_AddEdgeNewFaces - Add a new edge and, if in doing so it splits a face, delete the original face and replace it with two new
faces. This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.12
• ST_AddIsoEdge - Adds an isolated edge defined by geometry alinestring to a topology connecting two existing isolated nodes
anode and anothernode and returns the edge id of the new edge. This method implements the SQL/MM specification. SQL-
MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.4
• ST_AddIsoNode - Adds an isolated node to a face in a topology and returns the nodeid of the new node. If face is null, the
node is still created. This method implements the SQL/MM specification. SQL-MM: Topo-Net Routines: X+1.3.1
• ST_Area - Returns the area of a polygonal geometry. This method implements the SQL/MM specification. SQL-MM 3: 8.1.2,
9.5.3
• ST_AsBinary - Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID
meta data. This method implements the SQL/MM specification. SQL-MM 3: 5.1.37
• ST_AsGML - Return the geometry as a GML version 2 or 3 element. This method implements the SQL/MM specification.
SQL-MM IEC 13249-3: 17.2
• ST_AsText - Return the Well-Known Text (WKT) representation of the geometry/geography without SRID metadata. This
method implements the SQL/MM specification. SQL-MM 3: 5.1.25
• ST_Boundary - Returns the boundary of a geometry. This method implements the SQL/MM specification. SQL-MM IEC
13249-3: 5.1.17
• ST_Buffer - Computes a geometry covering all points within a given distance from a geometry. This method implements the
SQL/MM specification. SQL-MM IEC 13249-3: 5.1.30
• ST_Centroid - Returns the geometric center of a geometry. This method implements the SQL/MM specification. SQL-MM 3:
8.1.4, 9.5.5
PostGIS 3.3.2 Manual 773 / 902
• ST_ChangeEdgeGeom - Changes the shape of an edge without affecting the topology structure. This method implements the
SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details X.3.6
• ST_Contains - Tests if no points of B lie in the exterior of A, and A and B have at least one interior point in common. This
method implements the SQL/MM specification. SQL-MM 3: 5.1.31
• ST_ConvexHull - Computes the convex hull of a geometry. This method implements the SQL/MM specification. SQL-MM
IEC 13249-3: 5.1.16
• ST_CoordDim - Return the coordinate dimension of a geometry. This method implements the SQL/MM specification. SQL-
MM 3: 5.1.3
• ST_CreateTopoGeo - Adds a collection of geometries to a given empty topology and returns a message detailing success. This
method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details -- X.3.18
• ST_Crosses - Tests if two geometries have some, but not all, interior points in common. This method implements the SQL/MM
specification. SQL-MM 3: 5.1.29
• ST_CurveToLine - Converts a geometry containing curves to a linear geometry. This method implements the SQL/MM speci-
fication. SQL-MM 3: 7.1.7
• ST_Difference - Computes a geometry representing the part of geometry A that does not intersect geometry B. This method
implements the SQL/MM specification. SQL-MM 3: 5.1.20
• ST_Dimension - Returns the topological dimension of a geometry. This method implements the SQL/MM specification. SQL-
MM 3: 5.1.2
• ST_Disjoint - Tests if two geometries are disjoint (they have no point in common). This method implements the SQL/MM
specification. SQL-MM 3: 5.1.26
• ST_Distance - Returns the distance between two geometry or geography values. This method implements the SQL/MM
specification. SQL-MM 3: 5.1.23
• ST_EndPoint - Returns the last point of a LineString or CircularLineString. This method implements the SQL/MM specifica-
tion. SQL-MM 3: 7.1.4
• ST_Envelope - Returns a geometry representing the bounding box of a geometry. This method implements the SQL/MM
specification. SQL-MM 3: 5.1.19
• ST_Equals - Tests if two geometries include the same set of points. This method implements the SQL/MM specification.
SQL-MM 3: 5.1.24
• ST_ExteriorRing - Returns a LineString representing the exterior ring of a Polygon. This method implements the SQL/MM
specification. SQL-MM 3: 8.2.3, 8.3.3
• ST_GMLToSQL - Return a specified ST_Geometry value from GML representation. This is an alias name for ST_GeomFromGML
This method implements the SQL/MM specification. SQL-MM 3: 5.1.50 (except for curves support).
• ST_GeomCollFromText - Makes a collection Geometry from collection WKT with the given SRID. If SRID is not given, it
defaults to 0. This method implements the SQL/MM specification.
• ST_GeomFromText - Return a specified ST_Geometry value from Well-Known Text representation (WKT). This method
implements the SQL/MM specification. SQL-MM 3: 5.1.40
• ST_GeomFromWKB - Creates a geometry instance from a Well-Known Binary geometry representation (WKB) and optional
SRID. This method implements the SQL/MM specification. SQL-MM 3: 5.1.41
• ST_GeometryFromText - Return a specified ST_Geometry value from Well-Known Text representation (WKT). This is an
alias name for ST_GeomFromText This method implements the SQL/MM specification. SQL-MM 3: 5.1.40
• ST_GeometryN - Return an element of a geometry collection. This method implements the SQL/MM specification. SQL-MM
3: 9.1.5
• ST_GeometryType - Returns the SQL-MM type of a geometry as text. This method implements the SQL/MM specification.
SQL-MM 3: 5.1.4
PostGIS 3.3.2 Manual 774 / 902
• ST_GetFaceEdges - Returns a set of ordered edges that bound aface. This method implements the SQL/MM specification.
SQL-MM 3 Topo-Geo and Topo-Net 3: Routine Details: X.3.5
• ST_GetFaceGeometry - Returns the polygon in the given topology with the specified face id. This method implements the
SQL/MM specification. SQL-MM 3 Topo-Geo and Topo-Net 3: Routine Details: X.3.16
• ST_InitTopoGeo - Creates a new topology schema and registers this new schema in the topology.topology table and details
summary of process. This method implements the SQL/MM specification. SQL-MM 3 Topo-Geo and Topo-Net 3: Routine
Details: X.3.17
• ST_InteriorRingN - Returns the Nth interior ring (hole) of a Polygon. This method implements the SQL/MM specification.
SQL-MM 3: 8.2.6, 8.3.5
• ST_Intersection - Computes a geometry representing the shared portion of geometries A and B. This method implements the
SQL/MM specification. SQL-MM 3: 5.1.18
• ST_Intersects - Tests if two geometries intersect (they have at least one point in common). This method implements the
SQL/MM specification. SQL-MM 3: 5.1.27
• ST_IsClosed - Tests if a LineStrings’s start and end points are coincident. For a PolyhedralSurface tests if it is closed (volu-
metric). This method implements the SQL/MM specification. SQL-MM 3: 7.1.5, 9.3.3
• ST_IsEmpty - Tests if a geometry is empty. This method implements the SQL/MM specification. SQL-MM 3: 5.1.7
• ST_IsRing - Tests if a LineString is closed and simple. This method implements the SQL/MM specification. SQL-MM 3:
7.1.6
• ST_IsSimple - Tests if a geometry has no points of self-intersection or self-tangency. This method implements the SQL/MM
specification. SQL-MM 3: 5.1.8
• ST_IsValid - Tests if a geometry is well-formed in 2D. This method implements the SQL/MM specification. SQL-MM 3: 5.1.9
• ST_Length - Returns the 2D length of a linear geometry. This method implements the SQL/MM specification. SQL-MM 3:
7.1.2, 9.3.4
• ST_LineFromText - Makes a Geometry from WKT representation with the given SRID. If SRID is not given, it defaults to 0.
This method implements the SQL/MM specification. SQL-MM 3: 7.2.8
• ST_LineFromWKB - Makes a LINESTRING from WKB with the given SRID This method implements the SQL/MM speci-
fication. SQL-MM 3: 7.2.9
• ST_LinestringFromWKB - Makes a geometry from WKB with the given SRID. This method implements the SQL/MM speci-
fication. SQL-MM 3: 7.2.9
• ST_LocateAlong - Returns the point(s) on a geometry that match a measure value. This method implements the SQL/MM
specification. SQL-MM IEC 13249-3: 5.1.13
• ST_LocateBetween - Returns the portions of a geometry that match a measure range. This method implements the SQL/MM
specification. SQL-MM IEC 13249-3: 5.1
• ST_M - Returns the M coordinate of a Point. This method implements the SQL/MM specification.
• ST_MLineFromText - Return a specified ST_MultiLineString value from WKT representation. This method implements the
SQL/MM specification.SQL-MM 3: 9.4.4
• ST_MPointFromText - Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0. This method
implements the SQL/MM specification. SQL-MM 3: 9.2.4
• ST_MPolyFromText - Makes a MultiPolygon Geometry from WKT with the given SRID. If SRID is not given, it defaults to
0. This method implements the SQL/MM specification. SQL-MM 3: 9.6.4
• ST_ModEdgeHeal - Heals two edges by deleting the node connecting them, modifying the first edgeand deleting the second
edge. Returns the id of the deleted node. This method implements the SQL/MM specification. SQL-MM: Topo-Geo and
Topo-Net 3: Routine Details: X.3.9
PostGIS 3.3.2 Manual 775 / 902
• ST_ModEdgeSplit - Split an edge by creating a new node along an existing edge, modifying the original edge and adding a
new edge. This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.9
• ST_MoveIsoNode - Moves an isolated node in a topology from one point to another. If new apoint geometry exists as a node
an error is thrown. Returns description of move. This method implements the SQL/MM specification. SQL-MM: Topo-Net
Routines: X.3.2
• ST_NewEdgeHeal - Heals two edges by deleting the node connecting them, deleting both edges,and replacing them with an
edge whose direction is the same as the firstedge provided. This method implements the SQL/MM specification. SQL-MM:
Topo-Geo and Topo-Net 3: Routine Details: X.3.9
• ST_NewEdgesSplit - Split an edge by creating a new node along an existing edge, deleting the original edge and replacing it
with two new edges. Returns the id of the new node created that joins the new edges. This method implements the SQL/MM
specification. SQL-MM: Topo-Net Routines: X.3.8
• ST_NumGeometries - Returns the number of elements in a geometry collection. This method implements the SQL/MM
specification. SQL-MM 3: 9.1.4
• ST_NumInteriorRings - Returns the number of interior rings (holes) of a Polygon. This method implements the SQL/MM
specification. SQL-MM 3: 8.2.5
• ST_NumPatches - Return the number of faces on a Polyhedral Surface. Will return null for non-polyhedral geometries. This
method implements the SQL/MM specification. SQL-MM ISO/IEC 13249-3: 8.5
• ST_NumPoints - Returns the number of points in a LineString or CircularString. This method implements the SQL/MM
specification. SQL-MM 3: 7.2.4
• ST_OrderingEquals - Tests if two geometries represent the same geometry and have points in the same directional order. This
method implements the SQL/MM specification. SQL-MM 3: 5.1.43
• ST_Overlaps - Tests if two geometries intersect and have the same dimension, but are not completely contained by each other.
This method implements the SQL/MM specification. SQL-MM 3: 5.1.32
• ST_PatchN - Returns the Nth geometry (face) of a PolyhedralSurface. This method implements the SQL/MM specification.
SQL-MM ISO/IEC 13249-3: 8.5
• ST_Perimeter - Returns the length of the boundary of a polygonal geometry or geography. This method implements the
SQL/MM specification. SQL-MM 3: 8.1.3, 9.5.4
• ST_Point - Creates a Point with X, Y and SRID values. This method implements the SQL/MM specification. SQL-MM 3:
6.1.2
• ST_PointFromText - Makes a point Geometry from WKT with the given SRID. If SRID is not given, it defaults to unknown.
This method implements the SQL/MM specification. SQL-MM 3: 6.1.8
• ST_PointFromWKB - Makes a geometry from WKB with the given SRID This method implements the SQL/MM specification.
SQL-MM 3: 6.1.9
• ST_PointN - Returns the Nth point in the first LineString or circular LineString in a geometry. This method implements the
SQL/MM specification. SQL-MM 3: 7.2.5, 7.3.5
• ST_PointOnSurface - Computes a point guaranteed to lie in a polygon, or on a geometry. This method implements the
SQL/MM specification. SQL-MM 3: 8.1.5, 9.5.6. The specifications define ST_PointOnSurface for surface geometries only.
PostGIS extends the function to support all common geometry types. Other databases (Oracle, DB2, ArcSDE) seem to support
this function only for surfaces. SQL Server 2008 supports all common geometry types.
• ST_Polygon - Creates a Polygon from a LineString with a specified SRID. This method implements the SQL/MM specification.
SQL-MM 3: 8.3.2
• ST_PolygonFromText - Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0. This method
implements the SQL/MM specification. SQL-MM 3: 8.3.6
• ST_Relate - Tests if two geometries have a topological relationship matching an Intersection Matrix pattern, or computes their
Intersection Matrix This method implements the SQL/MM specification. SQL-MM 3: 5.1.25
PostGIS 3.3.2 Manual 776 / 902
• ST_RemEdgeModFace - Removes an edge and, if the removed edge separated two faces,delete one of the them and modify
the other to take the space of both. This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net
3: Routine Details: X.3.15
• ST_RemEdgeNewFace - Removes an edge and, if the removed edge separated two faces,delete the original faces and replace
them with a new face. This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine
Details: X.3.14
• ST_RemoveIsoEdge - Removes an isolated edge and returns description of action. If the edge is not isolated, then an exception
is thrown. This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details:
X+1.3.3
• ST_RemoveIsoNode - Removes an isolated node and returns description of action. If the node is not isolated (is start or end
of an edge), then an exception is thrown. This method implements the SQL/MM specification. SQL-MM: Topo-Geo and
Topo-Net 3: Routine Details: X+1.3.3
• ST_SRID - Returns the spatial reference identifier for a geometry. This method implements the SQL/MM specification. SQL-
MM 3: 5.1.5
• ST_StartPoint - Returns the first point of a LineString. This method implements the SQL/MM specification. SQL-MM 3: 7.1.3
• ST_SymDifference - Computes a geometry representing the portions of geometries A and B that do not intersect. This method
implements the SQL/MM specification. SQL-MM 3: 5.1.21
• ST_Touches - Tests if two geometries have at least one point in common, but their interiors do not intersect. This method
implements the SQL/MM specification. SQL-MM 3: 5.1.28
• ST_Transform - Return a new geometry with coordinates transformed to a different spatial reference system. This method
implements the SQL/MM specification. SQL-MM 3: 5.1.6
• ST_Union - Computes a geometry representing the point-set union of the input geometries. This method implements the
SQL/MM specification. SQL-MM 3: 5.1.19 the z-index (elevation) when polygons are involved.
• ST_Volume - Computes the volume of a 3D solid. If applied to surface (even closed) geometries will return 0. This method
implements the SQL/MM specification. SQL-MM IEC 13249-3: 9.1 (same as ST_3DVolume)
• ST_WKBToSQL - Return a specified ST_Geometry value from Well-Known Binary representation (WKB). This is an alias
name for ST_GeomFromWKB that takes no srid This method implements the SQL/MM specification. SQL-MM 3: 5.1.36
• ST_WKTToSQL - Return a specified ST_Geometry value from Well-Known Text representation (WKT). This is an alias name
for ST_GeomFromText This method implements the SQL/MM specification. SQL-MM 3: 5.1.34
• ST_Within - Tests if no points of A lie in the exterior of B, and A and B have at least one interior point in common. This
method implements the SQL/MM specification. SQL-MM 3: 5.1.30
• ST_X - Returns the X coordinate of a Point. This method implements the SQL/MM specification. SQL-MM 3: 6.1.3
• ST_Y - Returns the Y coordinate of a Point. This method implements the SQL/MM specification. SQL-MM 3: 6.1.4
• ST_Z - Returns the Z coordinate of a Point. This method implements the SQL/MM specification.
• TG_ST_SRID - Returns the spatial reference identifier for a topogeometry. This method implements the SQL/MM specifica-
tion. SQL-MM 3: 14.1.5
The functions and operators given below are PostGIS functions/operators that take as input or return as output a geography data
type object.
PostGIS 3.3.2 Manual 777 / 902
Note
Functions with a (T) are not native geodetic functions, and use a ST_Transform call to and from geometry to do the
operation. As a result, they may not behave as expected when going over dateline, poles, and for large geometries or
geometry pairs that cover more than one UTM zone. Basic transform - (favoring UTM, Lambert Azimuthal (North/South),
and falling back on mercator in worst case scenario)
• ST_GeogFromWKB - Creates a geography instance from a Well-Known Binary geometry representation (WKB) or extended
Well Known Binary (EWKB).
• ST_GeographyFromText - Return a specified geography value from Well-Known Text representation or extended (WKT).
• = - Returns TRUE if the coordinates and coordinate order geometry/geography A are the same as the coordinates and coordinate
order of geometry/geography B.
• ST_Intersection - Computes a geometry representing the shared portion of geometries A and B.
• ST_Intersects - Tests if two geometries intersect (they have at least one point in common).
The functions and operators given below are PostGIS functions/operators that take as input or return as output a raster data type
object. Listed in alphabetical order.
• Box3D - Returns the box 3d representation of the enclosing box of the raster.
• @ - Returns TRUE if A’s bounding box is contained by B’s. Uses double precision bounding box.
• ~ - Returns TRUE if A’s bounding box is contains B’s. Uses double precision bounding box.
• = - Returns TRUE if A’s bounding box is the same as B’s. Uses double precision bounding box.
• && - Returns TRUE if A’s bounding box intersects B’s bounding box.
• &< - Returns TRUE if A’s bounding box is to the left of B’s.
• ST_AsHexWKB - Return the Well-Known Binary (WKB) in Hex representation of the raster.
• ST_AsJPEG - Return the raster tile selected bands as a single Joint Photographic Exports Group (JPEG) image (byte array). If
no band is specified and 1 or more than 3 bands, then only the first band is used. If only 3 bands then all 3 bands are used and
mapped to RGB.
• ST_AsPNG - Return the raster tile selected bands as a single portable network graphics (PNG) image (byte array). If 1, 3, or
4 bands in raster and no bands are specified, then all bands are used. If more 2 or more than 4 bands and no bands specified,
then only band 1 is used. Bands are mapped to RGB or RGBA space.
• ST_AsRaster - Converts a PostGIS geometry to a PostGIS raster.
• ST_AsTIFF - Return the raster selected bands as a single TIFF image (byte array). If no band is specified or any of specified
bands does not exist in the raster, then will try to use all bands.
• ST_Aspect - Returns the aspect (in degrees by default) of an elevation raster band. Useful for analyzing terrain.
• ST_Band - Returns one or more bands of an existing raster as a new raster. Useful for building new rasters from existing
rasters.
• ST_BandFileSize - Returns the file size of a band stored in file system. If no bandnum specified, 1 is assumed.
• ST_BandFileTimestamp - Returns the file timestamp of a band stored in file system. If no bandnum specified, 1 is assumed.
• ST_BandIsNoData - Returns true if the band is filled with only nodata values.
• ST_BandMetaData - Returns basic meta data for a specific raster band. band num 1 is assumed if none-specified.
• ST_BandNoDataValue - Returns the value in a given band that represents no data. If no band num 1 is assumed.
• ST_BandPath - Returns system file path to a band stored in file system. If no bandnum specified, 1 is assumed.
• ST_BandPixelType - Returns the type of pixel for given band. If no bandnum specified, 1 is assumed.
PostGIS 3.3.2 Manual 779 / 902
• ST_Clip - Returns the raster clipped by the input geometry. If band number not is specified, all bands are processed. If crop is
not specified or TRUE, the output raster is cropped.
• ST_ColorMap - Creates a new raster of up to four 8BUI bands (grayscale, RGB, RGBA) from the source raster and a specified
band. Band 1 is assumed if not specified.
• ST_Contains - Return true if no points of raster rastB lie in the exterior of raster rastA and at least one point of the interior of
rastB lies in the interior of rastA.
• ST_ContainsProperly - Return true if rastB intersects the interior of rastA but not the boundary or exterior of rastA.
• ST_Contour - Generates a set of vector contours from the provided raster band, using the GDAL contouring algorithm.
• ST_ConvexHull - Return the convex hull geometry of the raster including pixel values equal to BandNoDataValue. For regular
shaped and non-skewed rasters, this gives the same result as ST_Envelope so only useful for irregularly shaped or skewed
rasters.
• ST_Count - Returns the number of pixels in a given band of a raster or raster coverage. If no band is specified defaults to band
1. If exclude_nodata_value is set to true, will only count pixels that are not equal to the nodata value.
• ST_CountAgg - Aggregate. Returns the number of pixels in a given band of a set of rasters. If no band is specified defaults to
band 1. If exclude_nodata_value is set to true, will only count pixels that are not equal to the NODATA value.
• ST_CoveredBy - Return true if no points of raster rastA lie outside raster rastB.
• ST_Covers - Return true if no points of raster rastB lie outside raster rastA.
• ST_DFullyWithin - Return true if rasters rastA and rastB are fully within the specified distance of each other.
• ST_DWithin - Return true if rasters rastA and rastB are within the specified distance of each other.
• ST_Disjoint - Return true if raster rastA does not spatially intersect rastB.
• ST_DumpAsPolygons - Returns a set of geomval (geom,val) rows, from a given raster band. If no band number is specified,
band num defaults to 1.
• ST_DumpValues - Get the values of the specified band as a 2-dimension array.
• ST_Envelope - Returns the polygon representation of the extent of the raster.
• ST_FromGDALRaster - Returns a raster from a supported GDAL raster file.
• ST_GeoReference - Returns the georeference meta data in GDAL or ESRI format as commonly seen in a world file. Default
is GDAL.
• ST_Grayscale - Creates a new one-8BUI band raster from the source raster and specified bands representing Red, Green and
Blue
• ST_HasNoBand - Returns true if there is no band with given band number. If no band number is specified, then band number
1 is assumed.
• ST_Height - Returns the height of the raster in pixels.
• ST_HillShade - Returns the hypothetical illumination of an elevation raster band using provided azimuth, altitude, brightness
and scale inputs.
• ST_Histogram - Returns a set of record summarizing a raster or raster coverage data distribution separate bin ranges. Number
of bins are autocomputed if not specified.
• ST_InterpolateRaster - Interpolates a gridded surface based on an input set of 3-d points, using the X- and Y-values to position
the points on the grid and the Z-value of the points as the surface elevation.
• ST_Intersection - Returns a raster or a set of geometry-pixelvalue pairs representing the shared portion of two rasters or the
geometrical intersection of a vectorization of the raster and a geometry.
• ST_Intersects - Return true if raster rastA spatially intersects raster rastB.
PostGIS 3.3.2 Manual 780 / 902
• ST_IsEmpty - Returns true if the raster is empty (width = 0 and height = 0). Otherwise, returns false.
• ST_MakeEmptyCoverage - Cover georeferenced area with a grid of empty raster tiles.
• ST_MakeEmptyRaster - Returns an empty raster (having no bands) of given dimensions (width & height), upperleft X and Y,
pixel size and rotation (scalex, scaley, skewx & skewy) and reference system (srid). If a raster is passed in, returns a new raster
with the same size, alignment and SRID. If srid is left out, the spatial ref is set to unknown (0).
• ST_MapAlgebra (callback function version) - Callback function version - Returns a one-band raster given one or more input
rasters, band indexes and one user-specified callback function.
• ST_MapAlgebraExpr - 1 raster band version: Creates a new one band raster formed by applying a valid PostgreSQL algebraic
operation on the input raster band and of pixeltype provided. Band 1 is assumed if no band is specified.
• ST_MapAlgebraExpr - 2 raster band version: Creates a new one band raster formed by applying a valid PostgreSQL algebraic
operation on the two input raster bands and of pixeltype provided. band 1 of each raster is assumed if no band numbers are
specified. The resulting raster will be aligned (scale, skew and pixel corners) on the grid defined by the first raster and have its
extent defined by the "extenttype" parameter. Values for "extenttype" can be: INTERSECTION, UNION, FIRST, SECOND.
• ST_MapAlgebraFct - 1 band version - Creates a new one band raster formed by applying a valid PostgreSQL function on the
input raster band and of pixeltype prodived. Band 1 is assumed if no band is specified.
• ST_MapAlgebraFct - 2 band version - Creates a new one band raster formed by applying a valid PostgreSQL function on the
2 input raster bands and of pixeltype prodived. Band 1 is assumed if no band is specified. Extent type defaults to INTERSEC-
TION if not specified.
• ST_MapAlgebraFctNgb - 1-band version: Map Algebra Nearest Neighbor using user-defined PostgreSQL function. Return a
raster which values are the result of a PLPGSQL user function involving a neighborhood of values from the input raster band.
• ST_MapAlgebra (expression version) - Expression version - Returns a one-band raster given one or two input rasters, band
indexes and one or more user-specified SQL expressions.
• ST_MemSize - Returns the amount of space (in bytes) the raster takes.
• ST_MetaData - Returns basic meta data about a raster object such as pixel size, rotation (skew), upper, lower left, etc.
• ST_MinConvexHull - Return the convex hull geometry of the raster excluding NODATA pixels.
• ST_NearestValue - Returns the nearest non-NODATA value of a given band’s pixel specified by a columnx and rowy or a
geometric point expressed in the same spatial reference coordinate system as the raster.
• ST_Neighborhood - Returns a 2-D double precision array of the non-NODATA values around a given band’s pixel specified
by either a columnX and rowY or a geometric point expressed in the same spatial reference coordinate system as the raster.
• ST_NotSameAlignmentReason - Returns text stating if rasters are aligned and if not aligned, a reason why.
• ST_NumBands - Returns the number of bands in the raster object.
• ST_Overlaps - Return true if raster rastA and rastB intersect but one does not completely contain the other.
• ST_PixelAsCentroid - Returns the centroid (point geometry) of the area represented by a pixel.
• ST_PixelAsCentroids - Returns the centroid (point geometry) for each pixel of a raster band along with the value, the X and
the Y raster coordinates of each pixel. The point geometry is the centroid of the area represented by a pixel.
• ST_PixelAsPoint - Returns a point geometry of the pixel’s upper-left corner.
• ST_PixelAsPoints - Returns a point geometry for each pixel of a raster band along with the value, the X and the Y raster
coordinates of each pixel. The coordinates of the point geometry are of the pixel’s upper-left corner.
• ST_PixelAsPolygon - Returns the polygon geometry that bounds the pixel for a particular row and column.
• ST_PixelAsPolygons - Returns the polygon geometry that bounds every pixel of a raster band along with the value, the X and
the Y raster coordinates of each pixel.
PostGIS 3.3.2 Manual 781 / 902
• ST_PixelHeight - Returns the pixel height in geometric units of the spatial reference system.
• ST_PixelOfValue - Get the columnx, rowy coordinates of the pixel whose value equals the search value.
• ST_PixelWidth - Returns the pixel width in geometric units of the spatial reference system.
• ST_Polygon - Returns a multipolygon geometry formed by the union of pixels that have a pixel value that is not no data value.
If no band number is specified, band num defaults to 1.
• ST_Quantile - Compute quantiles for a raster or raster table coverage in the context of the sample or population. Thus, a value
could be examined to be at the raster’s 25%, 50%, 75% percentile.
• ST_RastFromHexWKB - Return a raster value from a Hex representation of Well-Known Binary (WKB) raster.
• ST_RastFromWKB - Return a raster value from a Well-Known Binary (WKB) raster.
• ST_RasterToWorldCoord - Returns the raster’s upper left corner as geometric X and Y (longitude and latitude) given a column
and row. Column and row starts at 1.
• ST_RasterToWorldCoordX - Returns the geometric X coordinate upper left of a raster, column and row. Numbering of columns
and rows starts at 1.
• ST_RasterToWorldCoordY - Returns the geometric Y coordinate upper left corner of a raster, column and row. Numbering of
columns and rows starts at 1.
• ST_Reclass - Creates a new raster composed of band types reclassified from original. The nband is the band to be changed. If
nband is not specified assumed to be 1. All other bands are returned unchanged. Use case: convert a 16BUI band to a 8BUI
and so forth for simpler rendering as viewable formats.
• ST_Resample - Resample a raster using a specified resampling algorithm, new dimensions, an arbitrary grid corner and a set
of raster georeferencing attributes defined or borrowed from another raster.
• ST_Rescale - Resample a raster by adjusting only its scale (or pixel size). New pixel values are computed using the Nearest-
Neighbor (english or american spelling), Bilinear, Cubic, CubicSpline or Lanczos resampling algorithm. Default is Nearest-
Neighbor.
• ST_Resize - Resize a raster to a new width/height
• ST_Reskew - Resample a raster by adjusting only its skew (or rotation parameters). New pixel values are computed using the
NearestNeighbor (english or american spelling), Bilinear, Cubic, CubicSpline or Lanczos resampling algorithm. Default is
NearestNeighbor.
• ST_Rotation - Returns the rotation of the raster in radian.
• ST_Roughness - Returns a raster with the calculated "roughness" of a DEM.
• ST_SRID - Returns the spatial reference identifier of the raster as defined in spatial_ref_sys table.
• ST_SameAlignment - Returns true if rasters have same skew, scale, spatial ref, and offset (pixels can be put on same grid
without cutting into pixels) and false if they don’t with notice detailing issue.
• ST_ScaleX - Returns the X component of the pixel width in units of coordinate reference system.
• ST_ScaleY - Returns the Y component of the pixel height in units of coordinate reference system.
• ST_SetBandIndex - Update the external band number of an out-db band
• ST_SetBandIsNoData - Sets the isnodata flag of the band to TRUE.
• ST_SetBandNoDataValue - Sets the value for the given band that represents no data. Band 1 is assumed if no band is specified.
To mark a band as having no nodata value, set the nodata value = NULL.
• ST_SetBandPath - Update the external path and band number of an out-db band
• ST_SetGeoReference - Set Georeference 6 georeference parameters in a single call. Numbers should be separated by white
space. Accepts inputs in GDAL or ESRI format. Default is GDAL.
PostGIS 3.3.2 Manual 782 / 902
• ST_SetM - Returns a geometry with the same X/Y coordinates as the input geometry, and values from the raster copied into
the Z dimension using the requested resample algorithm.
• ST_SetRotation - Set the rotation of the raster in radian.
• ST_SetSRID - Sets the SRID of a raster to a particular integer srid defined in the spatial_ref_sys table.
• ST_SetScale - Sets the X and Y size of pixels in units of coordinate reference system. Number units/pixel width/height.
• ST_SetSkew - Sets the georeference X and Y skew (or rotation parameter). If only one is passed in, sets X and Y to the same
value.
• ST_SetUpperLeft - Sets the value of the upper left corner of the pixel of the raster to projected X and Y coordinates.
• ST_SetValue - Returns modified raster resulting from setting the value of a given band in a given columnx, rowy pixel or the
pixels that intersect a particular geometry. Band numbers start at 1 and assumed to be 1 if not specified.
• ST_SetValues - Returns modified raster resulting from setting the values of a given band.
• ST_SetZ - Returns a geometry with the same X/Y coordinates as the input geometry, and values from the raster copied into the
Z dimension using the requested resample algorithm.
• ST_SkewX - Returns the georeference X skew (or rotation parameter).
• ST_SkewY - Returns the georeference Y skew (or rotation parameter).
• ST_Slope - Returns the slope (in degrees by default) of an elevation raster band. Useful for analyzing terrain.
• ST_SnapToGrid - Resample a raster by snapping it to a grid. New pixel values are computed using the NearestNeighbor
(english or american spelling), Bilinear, Cubic, CubicSpline or Lanczos resampling algorithm. Default is NearestNeighbor.
• ST_Summary - Returns a text summary of the contents of the raster.
• ST_SummaryStats - Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster band of a raster
or raster coverage. Band 1 is assumed is no band is specified.
• ST_SummaryStatsAgg - Aggregate. Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster
band of a set of raster. Band 1 is assumed is no band is specified.
• ST_Touches - Return true if raster rastA and rastB have at least one point in common but their interiors do not intersect.
• ST_Transform - Reprojects a raster in a known spatial reference system to another known spatial reference system using
specified resampling algorithm. Options are NearestNeighbor, Bilinear, Cubic, CubicSpline, Lanczos defaulting to Nearest-
Neighbor.
• ST_Union - Returns the union of a set of raster tiles into a single raster composed of 1 or more bands.
• ST_UpperLeftX - Returns the upper left X coordinate of raster in projected spatial ref.
• ST_UpperLeftY - Returns the upper left Y coordinate of raster in projected spatial ref.
• ST_Value - Returns the value of a given band in a given columnx, rowy pixel or at a particular geometric point. Band numbers
start at 1 and assumed to be 1 if not specified. If exclude_nodata_value is set to false, then all pixels include nodata pixels are
considered to intersect and return value. If exclude_nodata_value is not passed in then reads it from metadata of raster.
• ST_ValueCount - Returns a set of records containing a pixel band value and count of the number of pixels in a given band of a
raster (or a raster coverage) that have a given set of values. If no band is specified defaults to band 1. By default nodata value
pixels are not counted. and all other values in the pixel are output and pixel band values are rounded to the nearest integer.
PostGIS 3.3.2 Manual 783 / 902
• ST_WorldToRasterCoord - Returns the upper left corner as column and row given geometric X and Y (longitude and latitude)
or a point geometry expressed in the spatial reference coordinate system of the raster.
• ST_WorldToRasterCoordX - Returns the column in the raster of the point geometry (pt) or a X and Y world coordinate (xw,
yw) represented in world spatial reference system of raster.
• ST_WorldToRasterCoordY - Returns the row in the raster of the point geometry (pt) or a X and Y world coordinate (xw, yw)
represented in world spatial reference system of raster.
• UpdateRasterSRID - Change the SRID of all rasters in the user-specified column and table.
The functions given below are PostGIS functions that take as input or return as output a set of or single geometry_dump or
geomval data type object.
• ST_DumpAsPolygons - Returns a set of geomval (geom,val) rows, from a given raster band. If no band number is specified,
band num defaults to 1.
• ST_Intersection - Returns a raster or a set of geometry-pixelvalue pairs representing the shared portion of two rasters or the
geometrical intersection of a vectorization of the raster and a geometry.
• ST_Dump - Returns a set of geometry_dump rows for the components of a geometry.
The functions given below are PostGIS functions that take as input or return as output the box* family of PostGIS spatial types.
The box family of types consists of box2d, and box3d
• ST_Expand - Returns a bounding box expanded from another bounding box or a geometry.
• ST_Extent - Aggregate function that returns the bounding box of geometries.
• ST_MakeBox2D - Creates a BOX2D defined by two 2D point geometries.
• ~(geometry,box2df) - Returns TRUE if a geometry’s 2D bonding box contains a 2D float precision bounding box (GIDX).
• @(box2df,box2df) - Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into another 2D float precision
bounding box.
• @(box2df,geometry) - Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into a geometry’s 2D
bounding box.
• @(geometry,box2df) - Returns TRUE if a geometry’s 2D bounding box is contained into a 2D float precision bounding box
(BOX2DF).
• &&(box2df,box2df) - Returns TRUE if two 2D float precision bounding boxes (BOX2DF) intersect each other.
• &&(box2df,geometry) - Returns TRUE if a 2D float precision bounding box (BOX2DF) intersects a geometry’s (cached) 2D
bounding box.
• &&(geometry,box2df) - Returns TRUE if a geometry’s (cached) 2D bounding box intersects a 2D float precision bounding box
(BOX2DF).
The functions given below are PostGIS functions that do not throw away the Z-Index.
• ST_3DDistance - Returns the 3D cartesian minimum distance (based on spatial ref) between two geometries in projected units.
• ST_3DExtent - Aggregate function that returns the 3D bounding box of geometries.
• ST_3DIntersection - Perform 3D intersection
• ST_3DIntersects - Tests if two geometries spatially intersect in 3D - only for points, linestrings, polygons, polyhedral surface
(area).
• ST_3DLength - Returns the 3D length of a linear geometry.
• ST_3DLineInterpolatePoint - Returns a point interpolated along a 3D line at a fractional location.
• ST_AsEWKB - Return the Extended Well-Known Binary (EWKB) representation of the geometry with SRID meta data.
• ST_AsEWKT - Return the Well-Known Text (WKT) representation of the geometry with SRID meta data.
• ST_AsGML - Return the geometry as a GML version 2 or 3 element.
• ST_PointN - Returns the Nth point in the first LineString or circular LineString in a geometry.
• ST_PointOnSurface - Computes a point guaranteed to lie in a polygon, or on a geometry.
• ST_Points - Returns a MultiPoint containing the coordinates of a geometry.
• ST_Polygon - Creates a Polygon from a LineString with a specified SRID.
• ST_RemovePoint - Remove a point from a linestring.
• ST_RemoveRepeatedPoints - Returns a version of a geometry with duplicate points removed.
• ST_Reverse - Return the geometry with vertex order reversed.
• ST_Rotate - Rotates a geometry about an origin point.
• ST_RotateX - Rotates a geometry about the X axis.
• ST_RotateY - Rotates a geometry about the Y axis.
• ST_RotateZ - Rotates a geometry about the Z axis.
• ST_Scale - Scales a geometry by given factors.
• ST_Scroll - Change start point of a closed LineString.
• ST_SetPoint - Replace point of a linestring with a given point.
• ST_Shift_Longitude - Shifts the longitude coordinates of a geometry between -180..180 and 0..360.
• ST_SnapToGrid - Snap all points of the input geometry to a regular grid.
• ST_StartPoint - Returns the first point of a LineString.
• ST_StraightSkeleton - Compute a straight skeleton from a geometry
• ST_SwapOrdinates - Returns a version of the given geometry with given ordinate values swapped.
• ST_SymDifference - Computes a geometry representing the portions of geometries A and B that do not intersect.
• ST_Tesselate - Perform surface Tesselation of a polygon or polyhedralsurface and returns as a TIN or collection of TINS
• ST_TransScale - Translates and scales a geometry by given offsets and factors.
• ST_Translate - Translates a geometry by given offsets.
• ST_UnaryUnion - Computes the union of the components of a single geometry.
• ST_Union - Computes a geometry representing the point-set union of the input geometries.
• ST_Volume - Computes the volume of a 3D solid. If applied to surface (even closed) geometries will return 0.
• ST_WrapX - Wrap a geometry around an X value.
• ST_X - Returns the X coordinate of a Point.
• ST_XMax - Returns the X maxima of a 2D or 3D bounding box or a geometry.
• ST_XMin - Returns the X minima of a 2D or 3D bounding box or a geometry.
• ST_Y - Returns the Y coordinate of a Point.
• ST_YMax - Returns the Y maxima of a 2D or 3D bounding box or a geometry.
• ST_YMin - Returns the Y minima of a 2D or 3D bounding box or a geometry.
• ST_Z - Returns the Z coordinate of a Point.
• ST_ZMax - Returns the Z maxima of a 2D or 3D bounding box or a geometry.
PostGIS 3.3.2 Manual 789 / 902
The functions given below are PostGIS functions that can use CIRCULARSTRING, CURVEPOLYGON, and other curved
geometry types
• ST_Force3D - Force the geometries into XYZ mode. This is an alias for ST_Force3DZ.
• ST_Force3DM - Force the geometries into XYM mode.
• ST_Force3DZ - Force the geometries into XYZ mode.
• ST_GeomFromWKB - Creates a geometry instance from a Well-Known Binary geometry representation (WKB) and optional
SRID.
• ST_GeometryN - Return an element of a geometry collection.
• = - Returns TRUE if the coordinates and coordinate order geometry/geography A are the same as the coordinates and coordinate
order of geometry/geography B.
• &<| - Returns TRUE if A’s bounding box overlaps or is below B’s.
• ST_HasArc - Tests if a geometry contains a circular arc
• ST_Intersects - Tests if two geometries intersect (they have at least one point in common).
• ST_IsClosed - Tests if a LineStrings’s start and end points are coincident. For a PolyhedralSurface tests if it is closed (volu-
metric).
• ST_IsCollection - Tests if a geometry is a geometry collection type.
• ST_IsEmpty - Tests if a geometry is empty.
• ST_Transform - Return a new geometry with coordinates transformed to a different spatial reference system.
• ST_Translate - Translates a geometry by given offsets.
• ST_XMax - Returns the X maxima of a 2D or 3D bounding box or a geometry.
• ST_XMin - Returns the X minima of a 2D or 3D bounding box or a geometry.
• ~(box2df,geometry) - Returns TRUE if a 2D float precision bounding box (BOX2DF) contains a geometry’s 2D bonding box.
• ~(geometry,box2df) - Returns TRUE if a geometry’s 2D bonding box contains a 2D float precision bounding box (GIDX).
• && - Returns TRUE if A’s 2D bounding box intersects B’s 2D bounding box.
• &&& - Returns TRUE if A’s n-D bounding box intersects B’s n-D bounding box.
• @(box2df,box2df) - Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into another 2D float precision
bounding box.
• @(box2df,geometry) - Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into a geometry’s 2D
bounding box.
• @(geometry,box2df) - Returns TRUE if a geometry’s 2D bounding box is contained into a 2D float precision bounding box
(BOX2DF).
• &&(box2df,box2df) - Returns TRUE if two 2D float precision bounding boxes (BOX2DF) intersect each other.
PostGIS 3.3.2 Manual 792 / 902
• &&(box2df,geometry) - Returns TRUE if a 2D float precision bounding box (BOX2DF) intersects a geometry’s (cached) 2D
bounding box.
• &&(geometry,box2df) - Returns TRUE if a geometry’s (cached) 2D bounding box intersects a 2D float precision bounding box
(BOX2DF).
• &&&(geometry,gidx) - Returns TRUE if a geometry’s (cached) n-D bounding box intersects a n-D float precision bounding
box (GIDX).
• &&&(gidx,geometry) - Returns TRUE if a n-D float precision bounding box (GIDX) intersects a geometry’s (cached) n-D
bounding box.
• &&&(gidx,gidx) - Returns TRUE if two n-D float precision bounding boxes (GIDX) intersect each other.
The functions given below are PostGIS functions that can use POLYHEDRALSURFACE, POLYHEDRALSURFACEM geome-
tries
• ST_3DDistance - Returns the 3D cartesian minimum distance (based on spatial ref) between two geometries in projected units.
• ST_3DExtent - Aggregate function that returns the 3D bounding box of geometries.
• ST_3DIntersection - Perform 3D intersection
• ST_3DIntersects - Tests if two geometries spatially intersect in 3D - only for points, linestrings, polygons, polyhedral surface
(area).
• ST_3DLongestLine - Returns the 3D longest line between two geometries
• ST_3DMaxDistance - Returns the 3D cartesian maximum distance (based on spatial ref) between two geometries in projected
units.
• ST_AsEWKB - Return the Extended Well-Known Binary (EWKB) representation of the geometry with SRID meta data.
• ST_AsEWKT - Return the Well-Known Text (WKT) representation of the geometry with SRID meta data.
• ST_AsGML - Return the geometry as a GML version 2 or 3 element.
• ST_AsX3D - Returns a Geometry in X3D xml node element format: ISO-IEC-19776-1.2-X3DEncodings-XML
• ST_CoordDim - Return the coordinate dimension of a geometry.
• ST_Dimension - Returns the topological dimension of a geometry.
• ST_Dump - Returns a set of geometry_dump rows for the components of a geometry.
• ST_DumpPoints - Returns a set of geometry_dump rows for the coordinates in a geometry.
• ST_Expand - Returns a bounding box expanded from another bounding box or a geometry.
• ST_Extent - Aggregate function that returns the bounding box of geometries.
• ST_Extrude - Extrude a surface to a related volume
• ST_FlipCoordinates - Returns a version of a geometry with X and Y axis flipped.
• ST_Force2D - Force the geometries into a "2-dimensional mode".
• ST_ForceLHR - Force LHR orientation
• ST_ForceRHR - Force the orientation of the vertices in a polygon to follow the Right-Hand-Rule.
• ST_ForceSFS - Force the geometries to use SFS 1.1 geometry types only.
• ST_Force3D - Force the geometries into XYZ mode. This is an alias for ST_Force3DZ.
• ST_Force3DZ - Force the geometries into XYZ mode.
• ST_ForceCollection - Convert the geometry into a GEOMETRYCOLLECTION.
• ST_GeomFromEWKB - Return a specified ST_Geometry value from Extended Well-Known Binary representation (EWKB).
• ST_GeomFromEWKT - Return a specified ST_Geometry value from Extended Well-Known Text representation (EWKT).
• ST_GeomFromGML - Takes as input GML representation of geometry and outputs a PostGIS geometry object
• ST_GeometryN - Return an element of a geometry collection.
• ST_GeometryType - Returns the SQL-MM type of a geometry as text.
• = - Returns TRUE if the coordinates and coordinate order geometry/geography A are the same as the coordinates and coordinate
order of geometry/geography B.
• &<| - Returns TRUE if A’s bounding box overlaps or is below B’s.
• ~= - Returns TRUE if A’s bounding box is the same as B’s.
• ST_IsClosed - Tests if a LineStrings’s start and end points are coincident. For a PolyhedralSurface tests if it is closed (volu-
metric).
• ST_IsPlanar - Check if a surface is or not planar
• ST_IsSolid - Test if the geometry is a solid. No validity check is performed.
• ST_MakeSolid - Cast the geometry into a solid. No check is performed. To obtain a valid solid, the input geometry must be a
closed Polyhedral Surface or a closed TIN.
• ST_MemSize - Returns the amount of memory space a geometry takes.
• ST_NPoints - Returns the number of points (vertices) in a geometry.
PostGIS 3.3.2 Manual 794 / 902
Below is an alphabetical listing of spatial specific functions in PostGIS and the kinds of spatial types they work with or OGC/SQL
compliance they try to conform to.
• A means it works but with a transform cast built-in using cast to geometry, transform to a "best srid" spatial ref and then
cast back. Results may not be as expected for large areas or areas at poles and may accumulate floating point junk.
• A means the function works with the type because of a auto-cast to another such as to box3d rather than direct type
support.
• A means the function only available if PostGIS compiled with SFCGAL support.
• A means the function support is provided by SFCGAL if PostGIS compiled with SFCGAL support, otherwise GEOS/built-
in support.
• geom - Basic 2D geometry support (x,y).
ST_3DConvexHull
ST_3DDifference
ST_3DDistance
ST_3DExtent
ST_3DIntersection
ST_3DLength
ST_3DLineInterpolatePoint
ST_3DLongestLine
ST_3DMakeBox
ST_3DMaxDistance
ST_3DPerimeter
ST_3DShortestLine
ST_3DUnion
ST_AddMeasure
ST_AddPoint
ST_Affine
ST_AlphaShape
ST_Angle
ST_ApproximateMedialAxis
ST_Area
ST_Azimuth
ST_Boundary
ST_BoundingDiagonal
ST_Buffer
ST_BuildArea
ST_CPAWithin
ST_Centroid
ST_ChaikinSmoothing
ST_ClipByBox2D
ST_ClosestPoint
PostGIS 3.3.2 Manual 797 / 902
ST_ConstrainedDelaunayTriangles
ST_ConvexHull
ST_CoordDim
ST_CurveToLine
ST_DelaunayTriangles
ST_Difference
ST_Dimension
ST_Distance
ST_DistanceCPA
ST_DistanceSphere
ST_DistanceSpheroid
ST_Dump
ST_DumpPoints
ST_DumpRings
ST_DumpSegments
ST_EndPoint
ST_Envelope
ST_EstimatedExtent
ST_Expand
ST_Extent
ST_ExteriorRing
ST_Extrude
ST_FilterByM
ST_FlipCoordinates
PostGIS 3.3.2 Manual 798 / 902
ST_ForceLHR
ST_ForcePolygonCCW
ST_ForcePolygonCW
ST_ForceRHR
ST_ForceSFS
ST_Force3D
ST_Force3DM
ST_Force3DZ
ST_Force4D
ST_ForceCollection
ST_FrechetDistance
ST_GeneratePoints
ST_GeometricMedian
ST_GeometryN
ST_GeometryType
ST_HasArc
ST_HausdorffDistance
ST_Hexagon
ST_HexagonGrid
ST_InteriorRingN
ST_InterpolatePoint
ST_Intersection
ST_IsClosed
ST_IsCollection
ST_IsEmpty
ST_IsPlanar
ST_IsPolygonCCW
ST_IsPolygonCW
ST_IsRing
ST_IsSimple
ST_IsSolid
PostGIS 3.3.2 Manual 799 / 902
ST_Length
ST_Length2D
ST_LengthSpheroid
ST_Letters
ST_LineFromMultiPoint
ST_LineInterpolatePoint
ST_LineInterpolatePoints
ST_LineLocatePoint
ST_LineMerge
ST_LineSubstring
ST_LineToCurve
ST_LocateAlong
ST_LocateBetween
ST_LocateBetweenElevations
ST_LongestLine
ST_M
ST_MakeBox2D
ST_MakeEnvelope
ST_MakeLine
ST_MakePoint
ST_MakePointM
ST_MakePolygon
ST_MakeSolid
ST_MakeValid
ST_MaxDistance
ST_MaximumInscribedCircle
ST_MemSize
ST_MemUnion
ST_MinimumBoundingCircle
PostGIS 3.3.2 Manual 800 / 902
ST_MinkowskiSum
ST_Multi
ST_NDims
ST_NPoints
ST_NRings
ST_Node
ST_Normalize
ST_NumGeometries
ST_NumInteriorRing
ST_NumInteriorRings
ST_NumPatches
ST_NumPoints
ST_OffsetCurve
ST_OptimalAlphaShape
ST_Orientation
ST_OrientedEnvelope
ST_PatchN
ST_Perimeter
ST_Perimeter2D
ST_Point
ST_PointM
ST_PointN
ST_PointOnSurface
ST_PointZ
ST_PointZM
ST_Points
ST_Polygon
ST_Polygonize
ST_Project
ST_QuantizeCoordinates
PostGIS 3.3.2 Manual 801 / 902
ST_StraightSkeleton
ST_Subdivide
ST_Summary
ST_SwapOrdinates
ST_SymDifference
PostGIS 3.3.2 Manual 802 / 902
ST_TileEnvelope
ST_TransScale
ST_Transform
ST_Translate
ST_TriangulatePolygon
ST_UnaryUnion
ST_Union
ST_Volume
ST_VoronoiLines
ST_VoronoiPolygons
ST_WrapX
ST_X
ST_XMax
ST_XMin
ST_Y
ST_YMax
ST_YMin
ST_Z
ST_ZMax
ST_ZMin
ST_Zmflag
postgis.backend
postgis.enable_outdb_rasters
postgis.gdal_datapath
postgis.gdal_enabled_drivers
postgis.gdal_config_options
postgis_sfcgal_full_version
postgis_sfcgal_version
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 3.3
PostGIS 3.3.2 Manual 803 / 902
• RemoveUnusedPrimitives - Availability: 3.3.0 Removes topology primitives which not needed to define existing TopoGeome-
try objects.
• ST_3DConvexHull - Availability: 3.3.0 Computes the 3D convex hull of a geometry.
• ST_3DUnion - Availability: 3.3.0 aggregate variant was added Perform 3D union.
• ST_AlphaShape - Availability: 3.3.0 - requires SFCGAL >= 1.4.1. Computes a possible concave geometry using the CGAL
Alpha Shapes algorithm.
• ST_AsMARC21 - Availability: 3.3.0 Returns geometry as a MARC21/XML record with a geographic datafield (034).
• ST_GeomFromMARC21 - Availability: 3.3.0, requires libxml2 2.6+ Takes MARC21/XML geographic data as input and
returns a PostGIS geometry object.
• ST_Letters - Availability: 3.3.0 Returns the input letters rendered as geometry with a default start position at the origin and
default text height of 100.
• ST_OptimalAlphaShape - Availability: 3.3.0 - requires SFCGAL >= 1.4.1. Computes a possible concave geometry using the
CGAL Alpha Shapes algorithm after have computed the "optimal" alpha value.
• ST_SimplifyPolygonHull - Availability: 3.3.0 - requires GEOS >= 3.11.0 Computes a simplifed topology-preserving outer or
inner hull of a polygonal geometry.
• ST_TriangulatePolygon - Availability: 3.3.0 Computes the constrained Delaunay triangulation of polygons
• postgis_sfcgal_full_version - Availability: 3.3.0 Returns the full version of SFCGAL in use including CGAL and Boost ver-
sions
• ST_ConcaveHull - Enhanced: 3.3.0, GEOS native implementation enabled for GEOS 3.11+ Computes a possibly concave
geometry that encloses all input geometry vertices
• ST_LineMerge - Enhanced: 3.3.0 accept a directed parameter - requires GEOS >= 3.11.0 Return the lines formed by sewing
together a MultiLineString.
• PostGIS_Extensions_Upgrade - Changed: 3.3.0 support for upgrades from any PostGIS version. Does not work on all systems.
Packages and upgrades PostGIS extensions (e.g. postgis_raster,postgis_topology, postgis_sfcgal) to latest available version.
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 3.2
• ST_FromFlatGeobufToTable - Availability: 3.2.0 Creates a table based on the structure of FlatGeobuf data.
• ST_InterpolateRaster - Availability: 3.2.0 Interpolates a gridded surface based on an input set of 3-d points, using the X- and
Y-values to position the points on the grid and the Z-value of the points as the surface elevation.
• ST_SRID - Availability: 3.2.0 Returns the spatial reference identifier for a topogeometry.
• ST_Scroll - Availability: 3.2.0 Change start point of a closed LineString.
• ST_SetM - Availability: 3.2.0 Returns a geometry with the same X/Y coordinates as the input geometry, and values from the
raster copied into the Z dimension using the requested resample algorithm.
• ST_SetZ - Availability: 3.2.0 Returns a geometry with the same X/Y coordinates as the input geometry, and values from the
raster copied into the Z dimension using the requested resample algorithm.
• TopoGeom_addTopoGeom - Availability: 3.2 Adds element of a TopoGeometry to the definition of another TopoGeometry.
• ValidateTopologyRelation - Availability: 3.2.0 Returns info about invalid topology relation records
• postgis.gdal_config_options - Availability: 3.2.0 A string configuration to set options used when working with an out-db raster.
• GetFaceByPoint - Enhanced: 3.2.0 more efficient implementation and clearer contract, stops working with invalid topologies.
Finds face intersecting a given point.
• ST_ClusterKMeans - Enhanced: 3.2.0 Support for max_radius Window function that returns a cluster id for each input geom-
etry using the K-means algorithm.
• ST_MakeValid - Enhanced: 3.2.0, added algorithm options, ’linework’ and ’structure’ which requires GEOS >= 3.10.0. At-
tempts to make an invalid geometry valid without losing vertices.
• ST_MoveIsoNode - Enhanced: 3.2.0 ensures the nod cannot be moved in a different face Moves an isolated node in a topology
from one point to another. If new apoint geometry exists as a node an error is thrown. Returns description of move.
• ST_PixelAsCentroid - Enhanced: 3.2.0 Faster now implemented in C. Returns the centroid (point geometry) of the area repre-
sented by a pixel.
• ST_PixelAsCentroids - Enhanced: 3.2.0 Faster now implemented in C. Returns the centroid (point geometry) for each pixel of
a raster band along with the value, the X and the Y raster coordinates of each pixel. The point geometry is the centroid of the
area represented by a pixel.
• ST_Point - Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID
to mark the srid on the geometry. Creates a Point with X, Y and SRID values.
• ST_PointM - Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID
to mark the srid on the geometry. Creates a Point with X, Y, M and SRID values.
• ST_PointZ - Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID
to mark the srid on the geometry. Creates a Point with X, Y, Z and SRID values.
• ST_PointZM - Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID
to mark the srid on the geometry. Creates a Point with X, Y, Z, M and SRID values.
• ST_RemovePoint - Enhanced: 3.2.0 Remove a point from a linestring.
• ST_RemoveRepeatedPoints - Enhanced: 3.2.0 Returns a version of a geometry with duplicate points removed.
• ST_StartPoint - Enhanced: 3.2.0 returns a point for all geometries. Prior behavior returns NULLs if input was not a LineString.
Returns the first point of a LineString.
• ST_Value - Enhanced: 3.2.0 resample optional argument was added. Returns the value of a given band in a given columnx,
rowy pixel or at a particular geometric point. Band numbers start at 1 and assumed to be 1 if not specified. If exclude_nodata_value
is set to false, then all pixels include nodata pixels are considered to intersect and return value. If exclude_nodata_value is not
passed in then reads it from metadata of raster.
PostGIS 3.3.2 Manual 805 / 902
• ST_Boundary - Changed: 3.2.0 support for TIN, does not use geos, does not linearize curves Returns the boundary of a
geometry.
• ValidateTopology - Changed: 3.2.0 added optional bbox parameter, perform face labeling and edge linking checks. Returns a
set of validatetopology_returntype objects detailing issues with topology.
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 3.1
• ST_Hexagon - Availability: 3.1.0 Returns a single hexagon, using the provided edge size and cell coordinate within the hexagon
grid space.
• ST_HexagonGrid - Availability: 3.1.0 Returns a set of hexagons and cell indices that completely cover the bounds of the
geometry argument.
• ST_MaximumInscribedCircle - Availability: 3.1.0 - requires GEOS >= 3.9.0. Computes the largest circle contained within a
geometry.
• ST_ReducePrecision - Availability: 3.1.0 - requires GEOS >= 3.9.0. Returns a valid geometry with points rounded to a grid
tolerance.
• ST_Square - Availability: 3.1.0 Returns a single square, using the provided edge size and cell coordinate within the square grid
space.
• ST_SquareGrid - Availability: 3.1.0 Returns a set of grid squares and cell indices that completely cover the bounds of the
geometry argument.
• ST_AsEWKT - Enhanced: 3.1.0 support for optional precision parameter. Return the Well-Known Text (WKT) representation
of the geometry with SRID meta data.
• ST_ClusterKMeans - Enhanced: 3.1.0 Support for 3D geometries and weights Window function that returns a cluster id for
each input geometry using the K-means algorithm.
• ST_Difference - Enhanced: 3.1.0 accept a gridSize parameter - requires GEOS >= 3.9.0 Computes a geometry representing
the part of geometry A that does not intersect geometry B.
• ST_Intersection - Enhanced: 3.1.0 accept a gridSize parameter - requires GEOS >= 3.9.0 Computes a geometry representing
the shared portion of geometries A and B.
• ST_MakeValid - Enhanced: 3.1.0, added removal of Coordinates with NaN values. Attempts to make an invalid geometry
valid without losing vertices.
• ST_Subdivide - Enhanced: 3.1.0 accept a gridSize parameter, requires GEOS >= 3.9.0 to use this new feature. Computes a
rectilinear subdivision of a geometry.
• ST_SymDifference - Enhanced: 3.1.0 accept a gridSize parameter - requires GEOS >= 3.9.0 Computes a geometry representing
the portions of geometries A and B that do not intersect.
• ST_TileEnvelope - Enhanced: 3.1.0 Added margin parameter. Creates a rectangular Polygon in Web Mercator (SRID:3857)
using the XYZ tile system.
• ST_UnaryUnion - Enhanced: 3.1.0 accept a gridSize parameter - requires GEOS >= 3.9.0 Computes the union of the compo-
nents of a single geometry.
PostGIS 3.3.2 Manual 806 / 902
• ST_Union - Enhanced: 3.1.0 accept a gridSize parameter - requires GEOS >= 3.9.0 Computes a geometry representing the
point-set union of the input geometries.
• ST_Count - Changed: 3.1.0 - The ST_Count(rastertable, rastercolumn, ...) variants removed. Use instead. Returns the number
of pixels in a given band of a raster or raster coverage. If no band is specified defaults to band 1. If exclude_nodata_value is
set to true, will only count pixels that are not equal to the nodata value.
• ST_Force3D - Changed: 3.1.0. Added support for supplying a non-zero Z value. Force the geometries into XYZ mode. This
is an alias for ST_Force3DZ.
• ST_Force3DM - Changed: 3.1.0. Added support for supplying a non-zero M value. Force the geometries into XYM mode.
• ST_Force3DZ - Changed: 3.1.0. Added support for supplying a non-zero Z value. Force the geometries into XYZ mode.
• ST_Force4D - Changed: 3.1.0. Added support for supplying non-zero Z and M values. Force the geometries into XYZM
mode.
• ST_Histogram - Changed: 3.1.0 Removed ST_Histogram(table_name, column_name) variant. Returns a set of record summa-
rizing a raster or raster coverage data distribution separate bin ranges. Number of bins are autocomputed if not specified.
• ST_Quantile - Changed: 3.1.0 Removed ST_Quantile(table_name, column_name) variant. Compute quantiles for a raster or
raster table coverage in the context of the sample or population. Thus, a value could be examined to be at the raster’s 25%,
50%, 75% percentile.
• ST_SummaryStats - Changed: 3.1.0 ST_SummaryStats(rastertable, rastercolumn, ...) variants are removed. Use instead.
Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster band of a raster or raster coverage.
Band 1 is assumed is no band is specified.
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 3.0
• ST_3DLineInterpolatePoint - Availability: 3.0.0 Returns a point interpolated along a 3D line at a fractional location.
• ST_ConstrainedDelaunayTriangles - Availability: 3.0.0 Return a constrained Delaunay triangulation around the given input
geometry.
• ST_TileEnvelope - Availability: 3.0.0 Creates a rectangular Polygon in Web Mercator (SRID:3857) using the XYZ tile system.
• ST_AsMVT - Enhanced: 3.0 - added support for Feature ID. Aggregate function returning a MVT representation of a set of
rows.
• ST_Contains - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if no points of B lie in the exterior of
A, and A and B have at least one interior point in common.
• ST_ContainsProperly - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if B intersects the interior of
A but not the boundary or exterior.
• ST_CoveredBy - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if no point in A is outside B
• ST_Covers - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if no point in B is outside A
• ST_Crosses - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if two geometries have some, but not
all, interior points in common.
PostGIS 3.3.2 Manual 807 / 902
• ST_CurveToLine - Enhanced: 3.0.0 implemented a minimum number of segments per linearized arc to prevent topological
collapse. Converts a geometry containing curves to a linear geometry.
• ST_Disjoint - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if two geometries are disjoint (they have
no point in common).
• ST_Equals - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if two geometries include the same set
of points.
• ST_GeneratePoints - Enhanced: 3.0.0, added seed parameter Generates random points contained in a Polygon or MultiPolygon.
• ST_GeomFromGeoJSON - Enhanced: 3.0.0 parsed geometry defaults to SRID=4326 if not specified otherwise. Takes as input
a geojson representation of a geometry and outputs a PostGIS geometry object
• ST_LocateBetween - Enhanced: 3.0.0 - added support for POLYGON, TIN, TRIANGLE. Returns the portions of a geometry
that match a measure range.
• ST_LocateBetweenElevations - Enhanced: 3.0.0 - added support for POLYGON, TIN, TRIANGLE. Returns the portions of a
geometry that lie in an elevation (Z) range.
• ST_Overlaps - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if two geometries intersect and have
the same dimension, but are not completely contained by each other.
• ST_Relate - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if two geometries have a topological
relationship matching an Intersection Matrix pattern, or computes their Intersection Matrix
• ST_Segmentize - Enhanced: 3.0.0 Segmentize geometry now uses equal length segments Return a modified geometry/geogra-
phy having no segment longer than the given distance.
• ST_Touches - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if two geometries have at least one
point in common, but their interiors do not intersect.
• ST_Within - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if no points of A lie in the exterior of B,
and A and B have at least one interior point in common.
• PostGIS_Extensions_Upgrade - Changed: 3.0.0 to repackage loose extensions and support postgis_raster. Packages and up-
grades PostGIS extensions (e.g. postgis_raster,postgis_topology, postgis_sfcgal) to latest available version.
• ST_3DDistance - Changed: 3.0.0 - SFCGAL version removed Returns the 3D cartesian minimum distance (based on spatial
ref) between two geometries in projected units.
• ST_3DIntersects - Changed: 3.0.0 SFCGAL backend removed, GEOS backend supports TINs. Tests if two geometries spatially
intersect in 3D - only for points, linestrings, polygons, polyhedral surface (area).
• ST_Area - Changed: 3.0.0 - does not depend on SFCGAL anymore. Returns the area of a polygonal geometry.
• ST_AsGeoJSON - Changed: 3.0.0 support records as input Return a geometry as a GeoJSON element.
• ST_AsGeoJSON - Changed: 3.0.0 output SRID if not EPSG:4326. Return a geometry as a GeoJSON element.
• ST_AsKML - Changed: 3.0.0 - Removed the "versioned" variant signature Return the geometry as a KML element.
• ST_Distance - Changed: 3.0.0 - does not depend on SFCGAL anymore. Returns the distance between two geometry or
geography values.
• ST_Intersection - Changed: 3.0.0 does not depend on SFCGAL. Computes a geometry representing the shared portion of
geometries A and B.
• ST_Intersects - Changed: 3.0.0 SFCGAL version removed and native support for 2D TINS added. Tests if two geometries
intersect (they have at least one point in common).
• ST_Union - Changed: 3.0.0 does not depend on SFCGAL. Computes a geometry representing the point-set union of the input
geometries.
PostGIS 3.3.2 Manual 808 / 902
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 2.5
• ST_Angle - Availability: 2.5.0 Returns the angle between two vectors defined by 3 or 4 points, or 2 lines.
• ST_AsHexWKB - Availability: 2.5.0 Return the Well-Known Binary (WKB) in Hex representation of the raster.
• ST_BandFileSize - Availability: 2.5.0 Returns the file size of a band stored in file system. If no bandnum specified, 1 is
assumed.
• ST_BandFileTimestamp - Availability: 2.5.0 Returns the file timestamp of a band stored in file system. If no bandnum
specified, 1 is assumed.
• ST_ChaikinSmoothing - Availability: 2.5.0 Returns a smoothed version of a geometry, using the Chaikin algorithm
• ST_FilterByM - Availability: 2.5.0 Removes vertices based on their M value
• ST_Grayscale - Availability: 2.5.0 Creates a new one-8BUI band raster from the source raster and specified bands representing
Red, Green and Blue
• ST_LineInterpolatePoints - Availability: 2.5.0 Returns points interpolated along a line at a fractional interval.
• ST_OrientedEnvelope - Availability: 2.5.0 Returns a minimum-area rectangle containing a geometry.
• ST_RastFromHexWKB - Availability: 2.5.0 Return a raster value from a Hex representation of Well-Known Binary (WKB)
raster.
• ST_RastFromWKB - Availability: 2.5.0 Return a raster value from a Well-Known Binary (WKB) raster.
• ST_SetBandIndex - Availability: 2.5.0 Update the external band number of an out-db band
• ST_SetBandPath - Availability: 2.5.0 Update the external path and band number of an out-db band
• ST_GeometricMedian - Enhanced: 2.5.0 Added support for M as weight of points. Returns the geometric median of a Multi-
Point.
• ST_AsBinary/ST_AsWKB - Enhanced: 2.5.0 Addition of ST_AsWKB Return the Well-Known Binary (WKB) representation
of the raster.
• ST_AsMVT - Enhanced: 2.5.0 - added support parallel query. Aggregate function returning a MVT representation of a set of
rows.
• ST_AsText - Enhanced: 2.5 - optional parameter precision introduced. Return the Well-Known Text (WKT) representation of
the geometry/geography without SRID metadata.
• ST_BandMetaData - Enhanced: 2.5.0 to include outdbbandnum, filesize and filetimestamp for outdb rasters. Returns basic
meta data for a specific raster band. band num 1 is assumed if none-specified.
• ST_Buffer - Enhanced: 2.5.0 - ST_Buffer geometry support was enhanced to allow for side buffering specification side=both|left|right.
Computes a geometry covering all points within a given distance from a geometry.
• ST_GeomFromGeoJSON - Enhanced: 2.5.0 can now accept json and jsonb as inputs. Takes as input a geojson representation
of a geometry and outputs a PostGIS geometry object
PostGIS 3.3.2 Manual 809 / 902
• ST_Intersects - Enhanced: 2.5.0 Supports GEOMETRYCOLLECTION. Tests if two geometries intersect (they have at least
one point in common).
• ST_OffsetCurve - Enhanced: 2.5 - added support for GEOMETRYCOLLECTION and MULTILINESTRING Returns an offset
line at a given distance and side from an input line.
• ST_Scale - Enhanced: 2.5.0 support for scaling relative to a local origin (origin parameter) was introduced. Scales a geometry
by given factors.
• ST_Split - Enhanced: 2.5.0 support for splitting a polygon by a multiline was introduced. Returns a collection of geometries
created by splitting a geometry by another geometry.
• ST_Subdivide - Enhanced: 2.5.0 reuses existing points on polygon split, vertex count is lowered from 8 to 5. Computes a
rectilinear subdivision of a geometry.
• ST_GDALDrivers - Changed: 2.5.0 - add can_read and can_write columns. Returns a list of raster formats supported by
PostGIS through GDAL. Only those formats with can_write=True can be used by ST_AsGDALRaster
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 2.4
• ST_ForcePolygonCCW - Availability: 2.4.0 Orients all exterior rings counter-clockwise and all interior rings clockwise.
• ST_ForcePolygonCW - Availability: 2.4.0 Orients all exterior rings clockwise and all interior rings counter-clockwise.
• ST_IsPolygonCCW - Availability: 2.4.0 Tests if Polygons have exterior rings oriented counter-clockwise and interior rings
oriented clockwise.
• ST_IsPolygonCW - Availability: 2.4.0 Tests if Polygons have exterior rings oriented clockwise and interior rings oriented
counter-clockwise.
• ST_AsGeobuf - Availability: 2.4.0 Return a Geobuf representation of a set of rows.
• ST_AsMVT - Availability: 2.4.0 Aggregate function returning a MVT representation of a set of rows.
• ST_AsMVTGeom - Availability: 2.4.0 Transforms a geometry into the coordinate space of a MVT tile.
• ST_Centroid - Availability: 2.4.0 support for geography was introduced. Returns the geometric center of a geometry.
• ST_FrechetDistance - Availability: 2.4.0 - requires GEOS >= 3.7.0 Returns the Fréchet distance between two geometries.
• ST_MakeEmptyCoverage - Availability: 2.4.0 Cover georeferenced area with a grid of empty raster tiles.
• Loader_Generate_Nation_Script - Enhanced: 2.4.1 zip code 5 tabulation area (zcta5) load step was fixed and when enabled,
zcta5 data is loaded as a single table called zcta5_all as part of the nation script load. Generates a shell script for the specified
platform that loads in the county and state lookup tables.
• Normalize_Address - Enhanced: 2.4.0 norm_addy object includes additional fields zip4 and address_alphanumeric. Given a
textual street address, returns a composite norm_addy type that has road suffix, prefix and type standardized, street, streetname
etc. broken into separate fields. This function will work with just the lookup data packaged with the tiger_geocoder (no need
for tiger census data).
PostGIS 3.3.2 Manual 810 / 902
• Pagc_Normalize_Address - Enhanced: 2.4.0 norm_addy object includes additional fields zip4 and address_alphanumeric.
Given a textual street address, returns a composite norm_addy type that has road suffix, prefix and type standardized, street,
streetname etc. broken into separate fields. This function will work with just the lookup data packaged with the tiger_geocoder
(no need for tiger census data). Requires address_standardizer extension.
• Reverse_Geocode - Enhanced: 2.4.1 if optional zcta5 dataset is loaded, the reverse_geocode function can resolve to state and
zip even if the specific state data is not loaded. Refer to for details on loading zcta5 data. Takes a geometry point in a known
spatial ref sys and returns a record containing an array of theoretically possible addresses and an array of cross streets. If
include_strnum_range = true, includes the street range in the cross streets.
• ST_AsTWKB - Enhanced: 2.4.0 memory and speed improvements. Returns the geometry as TWKB, aka "Tiny Well-Known
Binary"
• ST_Covers - Enhanced: 2.4.0 Support for polygon in polygon and line in polygon added for geography type Tests if no point
in B is outside A
• ST_CurveToLine - Enhanced: 2.4.0 added support for max-deviation and max-angle tolerance, and for symmetric output.
Converts a geometry containing curves to a linear geometry.
• ST_Project - Enhanced: 2.4.0 Allow negative distance and non-normalized azimuth. Returns a point projected from a start
point by a distance and bearing (azimuth).
• ST_Reverse - Enhanced: 2.4.0 support for curves was introduced. Return the geometry with vertex order reversed.
• = - Changed: 2.4.0, in prior versions this was bounding box equality not a geometric equality. If you need bounding box
equality, use instead. Returns TRUE if the coordinates and coordinate order geometry/geography A are the same as the
coordinates and coordinate order of geometry/geography B.
• ST_Node - 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. Nodes a collection of lines.
The functions given below are PostGIS functions that were added or enhanced.
Note
PostGIS 2.3.0: PostgreSQL 9.6+ support for parallel queries.
Note
PostGIS 2.3.0: PostGIS extension, all functions schema qualified to reduce issues in database restore.
Note
PostGIS 2.3.0: PostgreSQL 9.4+ support for BRIN indexes. Refer to Section 4.9.2.
PostGIS 3.3.2 Manual 811 / 902
Note
PostGIS 2.3.0: Tiger Geocoder upgraded to work with TIGER 2016 data.
The functions given below are PostGIS functions that are enhanced in PostGIS 2.3.
• ST_Contains - Enhanced: 2.3.0 Enhancement to PIP short-circuit extended to support MultiPoints with few points. Prior
versions only supported point in polygon.
• ST_Covers - Enhanced: 2.3.0 Enhancement to PIP short-circuit for geometry extended to support MultiPoints with few points.
Prior versions only supported point in polygon.
• ST_Expand - Enhanced: 2.3.0 support was added to expand a box by different amounts in different dimensions.
• ST_Intersects - Enhanced: 2.3.0 Enhancement to PIP short-circuit extended to support MultiPoints with few points. Prior
versions only supported point in polygon.
• ST_Segmentize - Enhanced: 2.3.0 Segmentize geography now uses equal length segments
• ST_Transform - Enhanced: 2.3.0 support for direct PROJ.4 text was introduced.
• ST_Within - Enhanced: 2.3.0 Enhancement to PIP short-circuit for geometry extended to support MultiPoints with few points.
Prior versions only supported point in polygon.
The functions given below are PostGIS functions that were added or enhanced.
Note
postgis_sfcgal now can be installed as an extension using CREATE EXTENSION postgis_sfcgal;
Note
PostGIS 2.2.0: Tiger Geocoder upgraded to work with TIGER 2015 data.
Note
address_standardizer, address_standardizer_data_us extensions for standardizing address data refer to Section 14.1
for details.
Note
Many functions in topology rewritten as C functions for increased performance.
PostGIS 3.3.2 Manual 813 / 902
• <<#>> - Availability: 2.2.0 -- KNN only available for PostgreSQL 9.1+ Returns the n-D distance between A and B bounding
boxes.
• <<->> - Availability: 2.2.0 -- KNN only available for PostgreSQL 9.1+ Returns the n-D distance between the centroids of A
and B boundingboxes.
• ST_ClipByBox2D - Availability: 2.2.0 Computes the portion of a geometry falling within a rectangle.
• ST_ClosestPointOfApproach - Availability: 2.2.0 Returns a measure at the closest point of approach of two trajectories.
• ST_ClusterIntersecting - Availability: 2.2.0 Aggregate function that clusters the input geometries into connected sets.
• ST_ClusterWithin - Availability: 2.2.0 Aggregate function that clusters the input geometries by separation distance.
• ST_CountAgg - Availability: 2.2.0 Aggregate. Returns the number of pixels in a given band of a set of rasters. If no band is
specified defaults to band 1. If exclude_nodata_value is set to true, will only count pixels that are not equal to the NODATA
value.
• ST_CreateOverview - Availability: 2.2.0 Create an reduced resolution version of a given raster coverage.
• ST_DistanceCPA - Availability: 2.2.0 Returns the distance between the closest point of approach of two trajectories.
• ST_ForceCurve - Availability: 2.2.0 Upcast a geometry into its curved type, if applicable.
• ST_IsPlanar - Availability: 2.2.0: This was documented in 2.1.0 but got accidentally left out in 2.1 release. Check if a surface
is or not planar
• ST_IsSolid - Availability: 2.2.0 Test if the geometry is a solid. No validity check is performed.
• ST_IsValidTrajectory - Availability: 2.2.0 Tests if the geometry is a valid trajectory.
• ST_LineFromEncodedPolyline - Availability: 2.2.0 Creates a LineString from an Encoded Polyline.
• ST_MakeSolid - Availability: 2.2.0 Cast the geometry into a solid. No check is performed. To obtain a valid solid, the input
geometry must be a closed Polyhedral Surface or a closed TIN.
• ST_MapAlgebra (callback function version) - Availability: 2.2.0: Ability to add a mask Callback function version - Returns a
one-band raster given one or more input rasters, band indexes and one user-specified callback function.
• ST_MemSize - Availability: 2.2.0 Returns the amount of space (in bytes) the raster takes.
• ST_RemoveRepeatedPoints - Availability: 2.2.0 Returns a version of a geometry with duplicate points removed.
• ST_Retile - Availability: 2.2.0 Return a set of configured tiles from an arbitrarily tiled raster coverage.
• ST_SetEffectiveArea - Availability: 2.2.0 Sets the effective area for each vertex, using the Visvalingam-Whyatt algorithm.
• ST_SimplifyVW - Availability: 2.2.0 Returns a simplified version of a geometry, using the Visvalingam-Whyatt algorithm
• ST_Subdivide - Availability: 2.2.0 Computes a rectilinear subdivision of a geometry.
PostGIS 3.3.2 Manual 814 / 902
• ST_SummaryStatsAgg - Availability: 2.2.0 Aggregate. Returns summarystats consisting of count, sum, mean, stddev, min,
max for a given raster band of a set of raster. Band 1 is assumed is no band is specified.
• ST_SwapOrdinates - Availability: 2.2.0 Returns a version of the given geometry with given ordinate values swapped.
• ST_Volume - Availability: 2.2.0 Computes the volume of a 3D solid. If applied to surface (even closed) geometries will return
0.
• parse_address - Availability: 2.2.0 Takes a 1 line address and breaks into parts
• postgis.enable_outdb_rasters - Availability: 2.2.0 A boolean configuration option to enable access to out-db raster bands.
• postgis.gdal_datapath - Availability: 2.2.0 A configuration option to assign the value of GDAL’s GDAL_DATA option. If not
set, the environmentally set GDAL_DATA variable is used.
• postgis.gdal_enabled_drivers - Availability: 2.2.0 A configuration option to set the enabled GDAL drivers in the PostGIS
environment. Affects the GDAL configuration variable GDAL_SKIP.
• standardize_address - Availability: 2.2.0 Returns an stdaddr form of an input address utilizing lex, gaz, and rule tables.
• |=| - Availability: 2.2.0. Index-supported only available for PostgreSQL 9.5+ Returns the distance between A and B trajectories
at their closest point of approach.
The functions given below are PostGIS functions that are enhanced in PostGIS 2.2.
The functions given below are PostGIS functions that have possibly breaking changes in PostGIS 2.2. If you use any of these,
you may need to check your existing code.
• Get_Geocode_Setting - Changed: 2.2.0 : default settings are now kept in a table called geocode_settings_default. Use cus-
tomized settingsa are in geocode_settings and only contain those that have been set by user.
• ST_3DClosestPoint - Changed: 2.2.0 - if 2 2D geometries are input, a 2D point is returned (instead of old behavior assuming
0 for missing Z). In case of 2D and 3D, Z is no longer assumed to be 0 for missing Z.
• ST_3DDistance - Changed: 2.2.0 - In case of 2D and 3D, Z is no longer assumed to be 0 for missing Z.
• ST_3DLongestLine - Changed: 2.2.0 - if 2 2D geometries are input, a 2D point is returned (instead of old behavior assuming
0 for missing Z). In case of 2D and 3D, Z is no longer assumed to be 0 for missing Z.
PostGIS 3.3.2 Manual 815 / 902
• ST_3DMaxDistance - Changed: 2.2.0 - In case of 2D and 3D, Z is no longer assumed to be 0 for missing Z.
• ST_3DShortestLine - Changed: 2.2.0 - if 2 2D geometries are input, a 2D point is returned (instead of old behavior assuming
0 for missing Z). In case of 2D and 3D, Z is no longer assumed to be 0 for missing Z.
• ST_DistanceSphere - Changed: 2.2.0 In prior versions this used to be called ST_Distance_Sphere
• ST_DistanceSpheroid - Changed: 2.2.0 In prior versions this was called ST_Distance_Spheroid
• ST_Equals - Changed: 2.2.0 Returns true even for invalid geometries if they are binary equal
• ST_LengthSpheroid - Changed: 2.2.0 In prior versions this was called ST_Length_Spheroid and had the alias ST_3DLength_Spheroid
• ST_MemSize - Changed: 2.2.0 name changed to ST_MemSize to follow naming convention.
• ST_PointInsideCircle - Changed: 2.2.0 In prior versions this was called ST_Point_Inside_Circle
• ValidateTopology - Changed: 2.2.0 values for id1 and id2 were swapped for ’edge crosses node’ to be consistent with error
description.
• <-> - Changed: 2.2.0 -- For PostgreSQL 9.5 users, old Hybrid syntax may be slower, so you’ll want to get rid of that hack if
you are running your code only on PostGIS 2.2+ 9.5+. See examples below.
The functions given below are PostGIS functions that were added or enhanced.
Note
More Topology performance Improvements. Please refer to Chapter 10 for more details.
Note
Bug fixes (particularly with handling of out-of-band rasters), many new functions (often shortening code you have to
write to accomplish a common task) and massive speed improvements to raster functionality. Refer to Chapter 12 for
more details.
Note
PostGIS 2.1.0: Tiger Geocoder upgraded to work with TIGER 2012 census data. geocode_settings added for
debugging and tweaking rating preferences, loader made less greedy, now only downloads tables to be loaded. PostGIS
2.1.1: Tiger Geocoder upgraded to work with TIGER 2013 data. Please refer to Section 14.2 for more details.
• ST_3DArea - Availability: 2.1.0 Computes area of 3D surface geometries. Will return 0 for solids.
• ST_3DIntersection - Availability: 2.1.0 Perform 3D intersection
• ST_Box2dFromGeoHash - Availability: 2.1.0 Return a BOX2D from a GeoHash string.
• ST_ColorMap - Availability: 2.1.0 Creates a new raster of up to four 8BUI bands (grayscale, RGB, RGBA) from the source
raster and a specified band. Band 1 is assumed if not specified.
• ST_Contains - Availability: 2.1.0 Return true if no points of raster rastB lie in the exterior of raster rastA and at least one point
of the interior of rastB lies in the interior of rastA.
• ST_ContainsProperly - Availability: 2.1.0 Return true if rastB intersects the interior of rastA but not the boundary or exterior
of rastA.
• ST_CoveredBy - Availability: 2.1.0 Return true if no points of raster rastA lie outside raster rastB.
• ST_Covers - Availability: 2.1.0 Return true if no points of raster rastB lie outside raster rastA.
• ST_DFullyWithin - Availability: 2.1.0 Return true if rasters rastA and rastB are fully within the specified distance of each
other.
• ST_DWithin - Availability: 2.1.0 Return true if rasters rastA and rastB are within the specified distance of each other.
• ST_DelaunayTriangles - Availability: 2.1.0 Returns the Delaunay triangulation of the vertices of a geometry.
• ST_Disjoint - Availability: 2.1.0 Return true if raster rastA does not spatially intersect rastB.
• ST_DumpValues - Availability: 2.1.0 Get the values of the specified band as a 2-dimension array.
• ST_Extrude - Availability: 2.1.0 Extrude a surface to a related volume
• ST_MinConvexHull - Availability: 2.1.0 Return the convex hull geometry of the raster excluding NODATA pixels.
• ST_MinDist4ma - Availability: 2.1.0 Raster processing function that returns the minimum distance (in number of pixels)
between the pixel of interest and a neighboring pixel with value.
• ST_MinkowskiSum - Availability: 2.1.0 Performs Minkowski sum
• ST_NearestValue - Availability: 2.1.0 Returns the nearest non-NODATA value of a given band’s pixel specified by a columnx
and rowy or a geometric point expressed in the same spatial reference coordinate system as the raster.
• ST_Neighborhood - Availability: 2.1.0 Returns a 2-D double precision array of the non-NODATA values around a given band’s
pixel specified by either a columnX and rowY or a geometric point expressed in the same spatial reference coordinate system
as the raster.
• ST_NotSameAlignmentReason - Availability: 2.1.0 Returns text stating if rasters are aligned and if not aligned, a reason why.
• ST_Orientation - Availability: 2.1.0 Determine surface orientation
• ST_Overlaps - Availability: 2.1.0 Return true if raster rastA and rastB intersect but one does not completely contain the other.
PostGIS 3.3.2 Manual 817 / 902
• ST_PixelAsCentroid - Availability: 2.1.0 Returns the centroid (point geometry) of the area represented by a pixel.
• ST_PixelAsCentroids - Availability: 2.1.0 Returns the centroid (point geometry) for each pixel of a raster band along with the
value, the X and the Y raster coordinates of each pixel. The point geometry is the centroid of the area represented by a pixel.
• ST_PixelAsPoint - Availability: 2.1.0 Returns a point geometry of the pixel’s upper-left corner.
• ST_PixelAsPoints - Availability: 2.1.0 Returns a point geometry for each pixel of a raster band along with the value, the X and
the Y raster coordinates of each pixel. The coordinates of the point geometry are of the pixel’s upper-left corner.
• ST_PixelOfValue - Availability: 2.1.0 Get the columnx, rowy coordinates of the pixel whose value equals the search value.
• ST_Roughness - Availability: 2.1.0 Returns a raster with the calculated "roughness" of a DEM.
• ST_SetValues - Availability: 2.1.0 Returns modified raster resulting from setting the values of a given band.
• ST_Simplify - Availability: 2.1.0 Returns a "simplified" geometry version of the given TopoGeometry using the Douglas-
Peucker algorithm.
• ST_TRI - Availability: 2.1.0 Returns a raster with the calculated Terrain Ruggedness Index.
• ST_Tesselate - Availability: 2.1.0 Perform surface Tesselation of a polygon or polyhedralsurface and returns as a TIN or
collection of TINS
• ST_Tile - Availability: 2.1.0 Returns a set of rasters resulting from the split of the input raster based upon the desired dimen-
sions of the output rasters.
• ST_Touches - Availability: 2.1.0 Return true if raster rastA and rastB have at least one point in common but their interiors do
not intersect.
• ST_Union - Availability: 2.1.0 ST_Union(rast, unionarg) variant was introduced. Returns the union of a set of raster tiles into
a single raster composed of 1 or more bands.
• ST_Within - Availability: 2.1.0 Return true if no points of raster rastA lie in the exterior of raster rastB and at least one point
of the interior of rastA lies in the interior of rastB.
• ST_WorldToRasterCoord - Availability: 2.1.0 Returns the upper left corner as column and row given geometric X and Y
(longitude and latitude) or a point geometry expressed in the spatial reference coordinate system of the raster.
• Set_Geocode_Setting - Availability: 2.1.0 Sets a setting that affects behavior of geocoder functions.
• UpdateRasterSRID - Availability: 2.1.0 Change the SRID of all rasters in the user-specified column and table.
• clearTopoGeom - Availability: 2.1 Clears the content of a topo geometry.
• postgis.backend - Availability: 2.1.0 The backend to service a function where GEOS and SFCGAL overlap. Options: geos or
sfcgal. Defaults to geos.
• postgis_sfcgal_version - Availability: 2.1.0 Returns the version of SFCGAL in use
The functions given below are PostGIS functions that are enhanced in PostGIS 2.1.
PostGIS 3.3.2 Manual 818 / 902
The functions given below are PostGIS functions that have possibly breaking changes in PostGIS 2.1. If you use any of these,
you may need to check your existing code.
• ST_Aspect - Changed: 2.1.0 In prior versions, return values were in radians. Now, return values default to degrees
• ST_HillShade - Changed: 2.1.0 In prior versions, azimuth and altitude were expressed in radians. Now, azimuth and altitude
are expressed in degrees
• ST_Intersects - Changed: 2.1.0 The behavior of the ST_Intersects(raster, geometry) variants changed to match that of ST_Intersects(geo
raster).
• ST_PixelAsCentroids - Changed: 2.1.1 Changed behavior of exclude_nodata_value.
The functions given below are PostGIS functions that were added, enhanced, or have Section 15.12.13 breaking changes in 2.0
releases.
New geometry types: TIN and Polyhedral surfaces was introduced in 2.0
Note
Greatly improved support for Topology. Please refer to Chapter 10 for more details.
Note
In PostGIS 2.0, raster type and raster functionality has been integrated. There are way too many new raster functions to
list here and all are new so please refer to Chapter 12 for more details of the raster functions available. Earlier pre-2.0
versions had raster_columns/raster_overviews as real tables. These were changed to views before release. Functions
such as ST_AddRasterColumn were removed and replaced with AddRasterConstraints, DropRasterConstraints as
a result some apps that created raster tables may need changing.
Note
Tiger Geocoder upgraded to work with TIGER 2010 census data and now included in the core PostGIS documentation.
A reverse geocoder function was also added. Please refer to Section 14.2 for more details.
• && - Availability: 2.0.0 Returns TRUE if A’s bounding box intersects B’s bounding box.
• &&& - Availability: 2.0.0 Returns TRUE if A’s n-D bounding box intersects B’s n-D bounding box.
• <#> - Availability: 2.0.0 -- KNN only available for PostgreSQL 9.1+ Returns the 2D distance between A and B bounding
boxes.
• <-> - Availability: 2.0.0 -- Weak KNN provides nearest neighbors based on geometry centroid distances instead of true dis-
tances. Exact results for points, inexact for all other types. Available for PostgreSQL 9.1+ Returns the 2D distance between A
and B.
• AddEdge - Availability: 2.0.0 Adds a linestring edge to the edge table and associated start and end points to the point nodes
table of the specified topology schema using the specified linestring geometry and returns the edgeid of the new (or existing)
edge.
• AddFace - Availability: 2.0.0 Registers a face primitive to a topology and gets its identifier.
• AddNode - Availability: 2.0.0 Adds a point node to the node table in the specified topology schema and returns the nodeid of
new node. If point already exists as node, the existing nodeid is returned.
• AddOverviewConstraints - Availability: 2.0.0 Tag a raster column as being an overview of another.
• AddRasterConstraints - Availability: 2.0.0 Adds raster constraints to a loaded raster table for a specific column that constrains
spatial ref, scaling, blocksize, alignment, bands, band type and a flag to denote if raster column is regularly blocked. The table
must be loaded with data for the constraints to be inferred. Returns true if the constraint setting was accomplished and issues
a notice otherwise.
• AsGML - Availability: 2.0.0 Returns the GML representation of a topogeometry.
• CopyTopology - Availability: 2.0.0 Makes a copy of a topology structure (nodes, edges, faces, layers and TopoGeometries).
• DropOverviewConstraints - Availability: 2.0.0 Untag a raster column from being an overview of another.
PostGIS 3.3.2 Manual 821 / 902
• DropRasterConstraints - Availability: 2.0.0 Drops PostGIS raster constraints that refer to a raster table column. Useful if you
need to reload data or update your raster column data.
• Drop_Indexes_Generate_Script - Availability: 2.0.0 Generates a script that drops all non-primary key and non-unique indexes
on tiger schema and user specified schema. Defaults schema to tiger_data if no schema is specified.
• Drop_State_Tables_Generate_Script - Availability: 2.0.0 Generates a script that drops all tables in the specified schema that
are prefixed with the state abbreviation. Defaults schema to tiger_data if no schema is specified.
• Geocode_Intersection - Availability: 2.0.0 Takes in 2 streets that intersect and a state, city, zip, and outputs a set of possible
locations on the first cross street that is at the intersection, also includes a geomout as the point location in NAD 83 long lat,
a normalized_address (addy) for each location, and the rating. The lower the rating the more likely the match. Results are
sorted by lowest rating first. Can optionally pass in maximum results, defaults to 10. Uses Tiger data (edges, faces, addr),
PostgreSQL fuzzy string matching (soundex, levenshtein).
• GetEdgeByPoint - Availability: 2.0.0 Finds the edge-id of an edge that intersects a given point.
• GetTopoGeomElements - Availability: 2.0.0 Returns a set of topoelement objects containing the topological element_id,element_type
of the given TopoGeometry (primitive elements).
• GetTopologySRID - Availability: 2.0.0 Returns the SRID of a topology in the topology.topology table given the name of the
topology.
• Get_Tract - Availability: 2.0.0 Returns census tract or field from tract table of where the geometry is located. Default to
returning short name of tract.
• Install_Missing_Indexes - Availability: 2.0.0 Finds all tables with key columns used in geocoder joins and filter conditions that
are missing used indexes on those columns and will add them.
• Loader_Generate_Census_Script - Availability: 2.0.0 Generates a shell script for the specified platform for the specified states
that will download Tiger census state tract, bg, and tabblocks data tables, stage and load into tiger_data schema. Each state
script is returned as a separate record.
• Loader_Generate_Script - Availability: 2.0.0 to support Tiger 2010 structured data and load census tract (tract), block groups
(bg), and blocks (tabblocks) tables . Generates a shell script for the specified platform for the specified states that will download
Tiger data, stage and load into tiger_data schema. Each state script is returned as a separate record. Latest version supports
Tiger 2010 structural changes and also loads census tract, block groups, and blocks tables.
• Missing_Indexes_Generate_Script - Availability: 2.0.0 Finds all tables with key columns used in geocoder joins that are
missing indexes on those columns and will output the SQL DDL to define the index for those tables.
• Polygonize - Availability: 2.0.0 Finds and registers all faces defined by topology edges.
• Reverse_Geocode - Availability: 2.0.0 Takes a geometry point in a known spatial ref sys and returns a record containing an
array of theoretically possible addresses and an array of cross streets. If include_strnum_range = true, includes the street range
in the cross streets.
• ST_3DClosestPoint - Availability: 2.0.0 Returns the 3D point on g1 that is closest to g2. This is the first point of the 3D
shortest line.
• ST_3DDFullyWithin - Availability: 2.0.0 Tests if two 3D geometries are entirely within a given 3D distance
• ST_3DDWithin - Availability: 2.0.0 Tests if two 3D geometries are within a given 3D distance
• ST_3DDistance - Availability: 2.0.0 Returns the 3D cartesian minimum distance (based on spatial ref) between two geometries
in projected units.
PostGIS 3.3.2 Manual 822 / 902
• ST_3DIntersects - Availability: 2.0.0 Tests if two geometries spatially intersect in 3D - only for points, linestrings, polygons,
polyhedral surface (area).
• ST_3DLongestLine - Availability: 2.0.0 Returns the 3D longest line between two geometries
• ST_3DMaxDistance - Availability: 2.0.0 Returns the 3D cartesian maximum distance (based on spatial ref) between two
geometries in projected units.
• ST_3DShortestLine - Availability: 2.0.0 Returns the 3D shortest line between two geometries
• ST_AddEdgeModFace - Availability: 2.0 Add a new edge and, if in doing so it splits a face, modify the original face and add
a new face.
• ST_AddEdgeNewFaces - Availability: 2.0 Add a new edge and, if in doing so it splits a face, delete the original face and
replace it with two new faces.
• ST_AsGDALRaster - Availability: 2.0.0 - requires GDAL >= 1.6.0. Return the raster tile in the designated GDAL Raster
format. Raster formats are one of those supported by your compiled library. Use ST_GDALDrivers() to get a list of formats
supported by your library.
• ST_AsJPEG - Availability: 2.0.0 - requires GDAL >= 1.6.0. Return the raster tile selected bands as a single Joint Photographic
Exports Group (JPEG) image (byte array). If no band is specified and 1 or more than 3 bands, then only the first band is used.
If only 3 bands then all 3 bands are used and mapped to RGB.
• ST_AsLatLonText - Availability: 2.0 Return the Degrees, Minutes, Seconds representation of the given point.
• ST_AsPNG - Availability: 2.0.0 - requires GDAL >= 1.6.0. Return the raster tile selected bands as a single portable network
graphics (PNG) image (byte array). If 1, 3, or 4 bands in raster and no bands are specified, then all bands are used. If more 2
or more than 4 bands and no bands specified, then only band 1 is used. Bands are mapped to RGB or RGBA space.
• ST_AsRaster - Availability: 2.0.0 - requires GDAL >= 1.6.0. Converts a PostGIS geometry to a PostGIS raster.
• ST_AsTIFF - Availability: 2.0.0 - requires GDAL >= 1.6.0. Return the raster selected bands as a single TIFF image (byte
array). If no band is specified or any of specified bands does not exist in the raster, then will try to use all bands.
• ST_AsX3D - Availability: 2.0.0: ISO-IEC-19776-1.2-X3DEncodings-XML Returns a Geometry in X3D xml node element
format: ISO-IEC-19776-1.2-X3DEncodings-XML
• ST_Aspect - Availability: 2.0.0 Returns the aspect (in degrees by default) of an elevation raster band. Useful for analyzing
terrain.
• ST_Band - Availability: 2.0.0 Returns one or more bands of an existing raster as a new raster. Useful for building new rasters
from existing rasters.
• ST_BandIsNoData - Availability: 2.0.0 Returns true if the band is filled with only nodata values.
• ST_Clip - Availability: 2.0.0 Returns the raster clipped by the input geometry. If band number not is specified, all bands are
processed. If crop is not specified or TRUE, the output raster is cropped.
• ST_CollectionHomogenize - Availability: 2.0.0 Returns the simplest representation of a geometry collection.
• ST_ConcaveHull - Availability: 2.0.0 Computes a possibly concave geometry that encloses all input geometry vertices
• ST_Count - Availability: 2.0.0 Returns the number of pixels in a given band of a raster or raster coverage. If no band is
specified defaults to band 1. If exclude_nodata_value is set to true, will only count pixels that are not equal to the nodata value.
• ST_CreateTopoGeo - Availability: 2.0 Adds a collection of geometries to a given empty topology and returns a message
detailing success.
• ST_Distinct4ma - Availability: 2.0.0 Raster processing function that calculates the number of unique pixel values in a neigh-
borhood.
• ST_FlipCoordinates - Availability: 2.0.0 Returns a version of a geometry with X and Y axis flipped.
PostGIS 3.3.2 Manual 823 / 902
• ST_GDALDrivers - Availability: 2.0.0 - requires GDAL >= 1.6.0. Returns a list of raster formats supported by PostGIS
through GDAL. Only those formats with can_write=True can be used by ST_AsGDALRaster
• ST_GeomFromGeoJSON - Availability: 2.0.0 requires - JSON-C >= 0.9 Takes as input a geojson representation of a geometry
and outputs a PostGIS geometry object
• ST_GetFaceEdges - Availability: 2.0 Returns a set of ordered edges that bound aface.
• ST_HasNoBand - Availability: 2.0.0 Returns true if there is no band with given band number. If no band number is specified,
then band number 1 is assumed.
• ST_HillShade - Availability: 2.0.0 Returns the hypothetical illumination of an elevation raster band using provided azimuth,
altitude, brightness and scale inputs.
• ST_Histogram - Availability: 2.0.0 Returns a set of record summarizing a raster or raster coverage data distribution separate
bin ranges. Number of bins are autocomputed if not specified.
• ST_InterpolatePoint - Availability: 2.0.0 Returns the interpolated measure of a geometry closest to a point.
• ST_IsEmpty - Availability: 2.0.0 Returns true if the raster is empty (width = 0 and height = 0). Otherwise, returns false.
• ST_IsValidDetail - Availability: 2.0.0 Returns a valid_detail row stating if a geometry is valid or if not a reason and a location.
• ST_IsValidReason - Availability: 2.0 version taking flags. Returns text stating if a geometry is valid, or a reason for invalidity.
• ST_MakeLine - Availability: 2.0.0 - Support for LineString input elements was introduced Creates a LineString from Point,
MultiPoint, or LineString geometries.
• ST_MakeValid - Availability: 2.0.0 Attempts to make an invalid geometry valid without losing vertices.
• ST_MapAlgebraExpr - Availability: 2.0.0 1 raster band version: Creates a new one band raster formed by applying a valid
PostgreSQL algebraic operation on the input raster band and of pixeltype provided. Band 1 is assumed if no band is specified.
• ST_MapAlgebraExpr - Availability: 2.0.0 2 raster band version: Creates a new one band raster formed by applying a valid
PostgreSQL algebraic operation on the two input raster bands and of pixeltype provided. band 1 of each raster is assumed if no
band numbers are specified. The resulting raster will be aligned (scale, skew and pixel corners) on the grid defined by the first
raster and have its extent defined by the "extenttype" parameter. Values for "extenttype" can be: INTERSECTION, UNION,
FIRST, SECOND.
• ST_MapAlgebraFct - Availability: 2.0.0 1 band version - Creates a new one band raster formed by applying a valid PostgreSQL
function on the input raster band and of pixeltype prodived. Band 1 is assumed if no band is specified.
• ST_MapAlgebraFct - Availability: 2.0.0 2 band version - Creates a new one band raster formed by applying a valid PostgreSQL
function on the 2 input raster bands and of pixeltype prodived. Band 1 is assumed if no band is specified. Extent type defaults
to INTERSECTION if not specified.
• ST_MapAlgebraFctNgb - Availability: 2.0.0 1-band version: Map Algebra Nearest Neighbor using user-defined PostgreSQL
function. Return a raster which values are the result of a PLPGSQL user function involving a neighborhood of values from the
input raster band.
• ST_Max4ma - Availability: 2.0.0 Raster processing function that calculates the maximum pixel value in a neighborhood.
• ST_Mean4ma - Availability: 2.0.0 Raster processing function that calculates the mean pixel value in a neighborhood.
• ST_Min4ma - Availability: 2.0.0 Raster processing function that calculates the minimum pixel value in a neighborhood.
• ST_ModEdgeHeal - Availability: 2.0 Heals two edges by deleting the node connecting them, modifying the first edgeand
deleting the second edge. Returns the id of the deleted node.
• ST_MoveIsoNode - Availability: 2.0.0 Moves an isolated node in a topology from one point to another. If new apoint geometry
exists as a node an error is thrown. Returns description of move.
• ST_NewEdgeHeal - Availability: 2.0 Heals two edges by deleting the node connecting them, deleting both edges,and replacing
them with an edge whose direction is the same as the firstedge provided.
PostGIS 3.3.2 Manual 824 / 902
• ST_Sum4ma - Availability: 2.0.0 Raster processing function that calculates the sum of all pixel values in a neighborhood.
• ST_SummaryStats - Availability: 2.0.0 Returns summarystats consisting of count, sum, mean, stddev, min, max for a given
raster band of a raster or raster coverage. Band 1 is assumed is no band is specified.
• ST_Transform - Availability: 2.0.0 Requires GDAL 1.6.1+ Reprojects a raster in a known spatial reference system to an-
other known spatial reference system using specified resampling algorithm. Options are NearestNeighbor, Bilinear, Cubic,
CubicSpline, Lanczos defaulting to NearestNeighbor.
• ST_UnaryUnion - Availability: 2.0.0 Computes the union of the components of a single geometry.
• ST_Union - Availability: 2.0.0 Returns the union of a set of raster tiles into a single raster composed of 1 or more bands.
• ST_ValueCount - Availability: 2.0.0 Returns a set of records containing a pixel band value and count of the number of pixels
in a given band of a raster (or a raster coverage) that have a given set of values. If no band is specified defaults to band 1. By
default nodata value pixels are not counted. and all other values in the pixel are output and pixel band values are rounded to
the nearest integer.
• TopoElementArray_Agg - Availability: 2.0.0 Returns a topoelementarray for a set of element_id, type arrays (topoelements).
• TopoGeo_AddLineString - Availability: 2.0.0 Adds a linestring to an existing topology using a tolerance and possibly splitting
existing edges/faces. Returns edge identifiers.
• TopoGeo_AddPoint - Availability: 2.0.0 Adds a point to an existing topology using a tolerance and possibly splitting an
existing edge.
• TopoGeo_AddPolygon - Availability: 2.0.0 Adds a polygon to an existing topology using a tolerance and possibly splitting
existing edges/faces. Returns face identifiers.
• TopologySummary - Availability: 2.0.0 Takes a topology name and provides summary totals of types of objects in topology.
• Topology_Load_Tiger - Availability: 2.0.0 Loads a defined region of tiger data into a PostGIS Topology and transforming the
tiger data to spatial reference of the topology and snapping to the precision tolerance of the topology.
• toTopoGeom - Availability: 2.0 Converts a simple Geometry into a topo geometry.
• ~= - Availability: 2.0.0 Returns TRUE if A’s bounding box is the same as B’s.
The functions given below are PostGIS functions that are enhanced in PostGIS 2.0.
• AddGeometryColumn - Enhanced: 2.0.0 use_typmod argument introduced. Defaults to creating typmod geometry column
instead of constraint-based.
• Box2D - Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
• Box3D - Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
• Geocode - Enhanced: 2.0.0 to support Tiger 2010 structured data and revised some logic to improve speed, accuracy of
geocoding, and to offset point from centerline to side of street address is located on. The new parameter max_results useful for
specifying number of best results or just returning the best result.
• GeometryType - Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
• Populate_Geometry_Columns - Enhanced: 2.0.0 use_typmod optional argument was introduced that allows controlling if
columns are created with typmodifiers or with check constraints.
• ST_Intersection - Enhanced: 2.0.0 - Intersection in the raster space was introduced. In earlier pre-2.0.0 versions, only intersec-
tion performed in vector space were supported.
• ST_Intersects - Enhanced: 2.0.0 support raster/raster intersects was introduced.
• ST_Value - Enhanced: 2.0.0 exclude_nodata_value optional argument was added.
• ST_3DExtent - Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
PostGIS 3.3.2 Manual 826 / 902
• ST_Affine - Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
• ST_Area - Enhanced: 2.0.0 - support for 2D polyhedral surfaces was introduced.
• ST_AsBinary - Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
• ST_AsBinary - Enhanced: 2.0.0 support for higher coordinate dimensions was introduced.
• ST_AsBinary - Enhanced: 2.0.0 support for specifying endian with geography was introduced.
• ST_AsEWKB - Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
• ST_AsEWKT - Enhanced: 2.0.0 support for Geography, Polyhedral surfaces, Triangles and TIN was introduced.
• ST_AsGML - Enhanced: 2.0.0 prefix support was introduced. Option 4 for GML3 was introduced to allow using LineString
instead of Curve tag for lines. GML3 Support for Polyhedral surfaces and TINS was introduced. Option 32 was introduced to
output the box.
• ST_AsKML - Enhanced: 2.0.0 - Add prefix namespace, use default and named args
• ST_Azimuth - Enhanced: 2.0.0 support for geography was introduced.
• ST_ChangeEdgeGeom - Enhanced: 2.0.0 adds topological consistency enforcement
• ST_Dimension - Enhanced: 2.0.0 support for Polyhedral surfaces and TINs was introduced. No longer throws an exception if
given empty geometry.
• ST_Dump - Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
• ST_DumpPoints - Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
• ST_Expand - Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
• ST_Extent - Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
• ST_Force2D - Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.
• ST_ForceRHR - Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.
• ST_Force3D - Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.
• ST_Force3DZ - Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.
• ST_ForceCollection - Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.
• ST_GMLToSQL - Enhanced: 2.0.0 support for Polyhedral surfaces and TIN was introduced.
• ST_GMLToSQL - Enhanced: 2.0.0 default srid optional parameter added.
• ST_GeomFromEWKB - Enhanced: 2.0.0 support for Polyhedral surfaces and TIN was introduced.
• ST_GeomFromEWKT - Enhanced: 2.0.0 support for Polyhedral surfaces and TIN was introduced.
• ST_GeomFromGML - Enhanced: 2.0.0 support for Polyhedral surfaces and TIN was introduced.
• ST_GeomFromGML - Enhanced: 2.0.0 default srid optional parameter added.
• ST_GeometryN - Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
• ST_GeometryType - Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.
• ST_IsClosed - Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.
• ST_MakeEnvelope - Enhanced: 2.0: Ability to specify an envelope without specifying an SRID was introduced.
• ST_MakeValid - Enhanced: 2.0.1, speed improvements
• ST_NPoints - Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.
PostGIS 3.3.2 Manual 827 / 902
• ST_NumGeometries - Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
• ST_Relate - Enhanced: 2.0.0 - added support for specifying boundary node rule.
• ST_Rotate - Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
• ST_Rotate - Enhanced: 2.0.0 additional parameters for specifying the origin of rotation were added.
• ST_RotateX - Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
• ST_RotateY - Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
• ST_RotateZ - Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
• ST_Scale - Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.
• ST_ShiftLongitude - Enhanced: 2.0.0 support for Polyhedral surfaces and TIN was introduced.
• ST_Summary - Enhanced: 2.0.0 added support for geography
The functions given below are PostGIS functions that have changed behavior in PostGIS 2.0 and may require application changes.
Note
Most deprecated functions have been removed. These are functions that haven’t been documented since 1.2 or some
internal functions that were never documented. If you are using a function that you don’t see documented, it’s probably
deprecated, about to be deprecated, or internal and should be avoided. If you have applications or tools that rely on
deprecated functions, please refer to [?qandaentry] for more details.
Note
Bounding boxes of geometries have been changed from float4 to double precision (float8). This has an impact on
answers you get using bounding box operators and casting of bounding boxes to geometries. E.g ST_SetSRID(abbox)
will often return a different more accurate answer in PostGIS 2.0+ than it did in prior versions which may very well
slightly change answers to view port queries.
Note
The arguments hasnodata was replaced with exclude_nodata_value which has the same meaning as the older hasno-
data but clearer in purpose.
• AddGeometryColumn - Changed: 2.0.0 This function no longer updates geometry_columns since geometry_columns is a
view that reads from system catalogs. It by default also does not create constraints, but instead uses the built in type modifier
behavior of PostgreSQL. So for example building a wgs84 POINT column with this function is now equivalent to: ALTER
TABLE some_table ADD COLUMN geom geometry(Point,4326);
• AddGeometryColumn - Changed: 2.0.0 If you require the old behavior of constraints use the default use_typmod, but set it to
false.
PostGIS 3.3.2 Manual 828 / 902
• AddGeometryColumn - Changed: 2.0.0 Views can no longer be manually registered in geometry_columns, however views built
against geometry typmod tables geometries and used without wrapper functions will register themselves correctly because they
inherit the typmod behavior of their parent table column. Views that use geometry functions that output other geometries will
need to be cast to typmod geometries for these view geometry columns to be registered correctly in geometry_columns. Refer
to .
• DropGeometryColumn - Changed: 2.0.0 This function is provided for backward compatibility. Now that since geome-
try_columns is now a view against the system catalogs, you can drop a geometry column like any other table column using
ALTER TABLE
• DropGeometryTable - Changed: 2.0.0 This function is provided for backward compatibility. Now that since geometry_columns
is now a view against the system catalogs, you can drop a table with geometry columns like any other table using DROP TABLE
• Populate_Geometry_Columns - Changed: 2.0.0 By default, now uses type modifiers instead of check constraints to constrain
geometry types. You can still use check constraint behavior instead by using the new use_typmod and setting it to false.
• Box3D - Changed: 2.0.0 In pre-2.0 versions, there used to be a box2d instead of box3d. Since box2d is a deprecated type, this
was changed to box3d.
• ST_GDALDrivers - Changed: 2.0.6, 2.1.3 - by default no drivers are enabled, unless GUC or Environment variable gdal_enabled_driver
is set.
• ST_ScaleX - Changed: 2.0.0. In WKTRaster versions this was called ST_PixelSizeX.
• ST_EndPoint - Changed: 2.0.0 no longer works with single geometry MultiLineStrings. In older versions of PostGIS a
single-line MultiLineString would work with this function and return the end point. In 2.0.0 it returns NULL like any other
MultiLineString. The old behavior was an undocumented feature, but people who assumed they had their data stored as
LINESTRING may experience these returning NULL in 2.0.0.
The functions given below are PostGIS functions that were introduced or enhanced in this minor release.
• PostGIS_LibXML_Version - Availability: 1.5 Returns the version number of the libxml2 library.
• ST_AddMeasure - Availability: 1.5.0 Interpolates measures along a linear geometry.
• ST_AsBinary - Availability: 1.5.0 geography support was introduced. Return the OGC/ISO Well-Known Binary (WKB)
representation of the geometry/geography without SRID meta data.
• ST_AsGML - Availability: 1.5.0 geography support was introduced. Return the geometry as a GML version 2 or 3 element.
• ST_AsGeoJSON - Availability: 1.5.0 geography support was introduced. Return a geometry as a GeoJSON element.
• ST_AsText - Availability: 1.5 - support for geography was introduced. Return the Well-Known Text (WKT) representation of
the geometry/geography without SRID metadata.
• ST_Buffer - Availability: 1.5 - ST_Buffer was enhanced to support different endcaps and join types. These are useful for
example to convert road linestrings into polygon roads with flat or square edges instead of rounded edges. Thin wrapper for
geography was added. Computes a geometry covering all points within a given distance from a geometry.
• ST_ClosestPoint - Availability: 1.5.0 Returns the 2D point on g1 that is closest to g2. This is the first point of the shortest line
from one geometry to the other.
• ST_CollectionExtract - Availability: 1.5.0 Given a geometry collection, returns a multi-geometry containing only elements of
a specified type.
• ST_Covers - Availability: 1.5 - support for geography was introduced. Tests if no point in B is outside A
• ST_DFullyWithin - Availability: 1.5.0 Tests if two geometries are entirely within a given distance
• ST_DWithin - Availability: 1.5.0 support for geography was introduced Tests if two geometries are within a given distance
• ST_Distance - Availability: 1.5.0 geography support was introduced in 1.5. Speed improvements for planar to better handle
large or many vertex geometries Returns the distance between two geometry or geography values.
• ST_DistanceSphere - Availability: 1.5 - support for other geometry types besides points was introduced. Prior versions only
work with points. Returns minimum distance in meters between two lon/lat geometries using a spherical earth model.
• ST_DistanceSpheroid - Availability: 1.5 - support for other geometry types besides points was introduced. Prior versions only
work with points. Returns the minimum distance between two lon/lat geometries using a spheroidal earth model.
PostGIS 3.3.2 Manual 830 / 902
• ST_DumpPoints - Availability: 1.5.0 Returns a set of geometry_dump rows for the coordinates in a geometry.
• ST_Envelope - Availability: 1.5.0 behavior changed to output double precision instead of float4 Returns a geometry represent-
ing the bounding box of a geometry.
• ST_Expand - Availability: 1.5.0 behavior changed to output double precision instead of float4 coordinates. Returns a bounding
box expanded from another bounding box or a geometry.
• ST_GMLToSQL - Availability: 1.5, requires libxml2 1.6+ Return a specified ST_Geometry value from GML representation.
This is an alias name for ST_GeomFromGML
• ST_GeomFromGML - Availability: 1.5, requires libxml2 1.6+ Takes as input GML representation of geometry and outputs a
PostGIS geometry object
• ST_GeomFromKML - Availability: 1.5, requires libxml2 2.6+ Takes as input KML representation of geometry and outputs a
PostGIS geometry object
• ~= - Availability: 1.5.0 changed behavior Returns TRUE if A’s bounding box is the same as B’s.
• ST_HausdorffDistance - Availability: 1.5.0 Returns the Hausdorff distance between two geometries.
• ST_Intersection - Availability: 1.5 support for geography data type was introduced. Computes a geometry representing the
shared portion of geometries A and B.
• ST_Intersects - Availability: 1.5 support for geography was introduced. Tests if two geometries intersect (they have at least
one point in common).
• ST_Length - Availability: 1.5.0 geography support was introduced in 1.5. Returns the 2D length of a linear geometry.
• ST_LongestLine - Availability: 1.5.0 Returns the 2D longest line between two geometries.
• ST_MakeEnvelope - Availability: 1.5 Creates a rectangular Polygon from minimum and maximum coordinates.
• ST_MaxDistance - Availability: 1.5.0 Returns the 2D largest distance between two geometries in projected units.
• ST_ShortestLine - Availability: 1.5.0 Returns the 2D shortest line between two geometries
• && - Availability: 1.5.0 support for geography was introduced. Returns TRUE if A’s 2D bounding box intersects B’s 2D
bounding box.
The functions given below are PostGIS functions that were introduced or enhanced in the 1.4 release.
• Populate_Geometry_Columns - Ensures geometry columns are defined with type modifiers or have appropriate spatial con-
straints. Availability: 1.4.0
• ST_AsSVG - Returns SVG path data for a geometry. Availability: 1.2.2. Availability: 1.4.0 Changed in PostGIS 1.4.0 to
include L command in absolute path to conform to http://www.w3.org/TR/SVG/paths.html#PathDataBNF
• ST_Collect - Creates a GeometryCollection or Multi* geometry from a set of geometries. Availability: 1.4.0 - ST_Collect(geomarray)
was introduced. ST_Collect was enhanced to handle more geometries faster.
• ST_ContainsProperly - Tests if B intersects the interior of A but not the boundary or exterior. Availability: 1.4.0
• ST_GeoHash - Return a GeoHash representation of the geometry. Availability: 1.4.0
• ST_IsValidReason - Returns text stating if a geometry is valid, or a reason for invalidity. Availability: 1.4
• ST_LineCrossingDirection - Returns a number indicating the crossing behavior of two LineStrings. Availability: 1.4
• ST_LocateBetweenElevations - Returns the portions of a geometry that lie in an elevation (Z) range. Availability: 1.4.0
PostGIS 3.3.2 Manual 831 / 902
• ST_MakeLine - Creates a LineString from Point, MultiPoint, or LineString geometries. Availability: 1.4.0 - ST_MakeLine(geomarray)
was introduced. ST_MakeLine aggregate functions was enhanced to handle more points faster.
• ST_MinimumBoundingCircle - Returns the smallest circle polygon that contains a geometry. Availability: 1.4.0
• ST_Union - Computes a geometry representing the point-set union of the input geometries. Availability: 1.4.0 - ST_Union
was enhanced. ST_Union(geomarray) was introduced and also faster aggregate collection in PostgreSQL.
The functions given below are PostGIS functions that were introduced in the 1.3 release.
Chapter 16
Reporting Problems
Reporting bugs effectively is a fundamental way to help PostGIS development. The most effective bug report is that enabling
PostGIS developers to reproduce it, so it would ideally contain a script triggering it and every information regarding the envi-
ronment in which it was detected. Good enough info can be extracted running SELECT postgis_full_version() [for
PostGIS] and SELECT version() [for postgresql].
If you aren’t using the latest release, it’s worth taking a look at its release changelog first, to find out if your bug has already been
fixed.
Using the PostGIS bug tracker will ensure your reports are not discarded, and will keep you informed on its handling process.
Before reporting a new bug please query the database to see if it is a known one, and if it is please add any new information you
have about it.
You might want to read Simon Tatham’s paper about How to Report Bugs Effectively before filing a new report.
The documentation should accurately reflect the features and behavior of the software. If it doesn’t, it could be because of a
software bug or because the documentation is in error or deficient.
Documentation issues can also be reported to the PostGIS bug tracker.
If your revision is trivial, just describe it in a new bug tracker issue, being specific about its location in the documentation.
If your changes are more extensive, a patch is definitely preferred. This is a four step process on Unix (assuming you already
have git installed):
Appendix A
Appendix
This version requires PostgreSQL 11-15, GEOS 3.6 or higher, and Proj 4.9+ Additional features are enabled if you are running
GEOS 3.9+ (and ST_MakeValid enhancements with 3.10+), Proj 6.1+, and PostgreSQL 15+.
2022/09/09
This version requires PostgreSQL 11 - 15, GEOS 3.6 or higher, and Proj 5.2+. Additional features are enabled if you are
running GEOS 3.9+ ST_MakeValid enhancements with 3.10+, numerouse additional enhancements with GEOS 3.11+. Requires
SFCGAL 1.4.1+ for ST_AlphaShape and ST_OptimalAlphaShape.
PostGIS 3.3.2 Manual 834 / 902
2022/08/26
This version requires PostgreSQL 11 or higher, GEOS 3.6 or higher, and Proj 5.2+. Additional features are enabled if you are
running GEOS 3.9+ ST_MakeValid enhancements with 3.10+, numerouse additional enhancements with GEOS 3.11+. Requires
SFCGAL 1.4.1+ for ST_AlphaShape and ST_OptimalAlphaShape.
NOTE: GEOS 3.11.0 details at GEOS 3.11.0 release notes
The new configure --enable-lto flag improves speed of math computations. This new feature is disabled by default because on
some platforms, causes compilation errors (BSD and MingW64 issues have been raised)
A.3.3 Enhancements
2861, Add index on topology.node(containing_face) speeding up splitting and merging of faces (Sandro Santilli)
2083, Speed up ST_RemEdge topology functions adding index on relation(element_id) and edge_data(abs_next*) (Sandro San-
tilli)
5118, Allow dropping topologies with missing topogeometry sequences (Sandro Santilli)
5111, faster topology face MBR computation (Sandro Santilli)
postgis_extensions_upgrade() support for upgrades from any PostGIS version, including yet to be released ones (Sandro Santilli)
PostGIS 3.3.2 Manual 835 / 902
2022/08/22
This version requires PostgreSQL 11 or higher, GEOS 3.6 or higher, and Proj 5.2+. Additional features are enabled if you are
running GEOS 3.9+ ST_MakeValid enhancements with 3.10+, numerouse additional enhancements with GEOS 3.11+. Requires
SFCGAL 1.4.1+ for ST_AlphaShape and ST_OptimalAlphaShape.
NOTE: GEOS 3.11.0 was recently released, details at GEOS 3.11.0 release notes
The new --enable-lto flag improves speed of math computations. This new feature is disabled by default because on some
platforms, causes compilation errors (BSD and MingW64 issues have been raised)
2022/08/08
This version requires PostgreSQL 11 or higher, GEOS 3.6 or higher, and Proj 5.2+. Additional features are enabled if you are
running GEOS 3.9+ ST_MakeValid enhancements with 3.10+, numerous additional enhancements with GEOS 3.11+. Requires
SFCGAL 1.4.1+ for ST_AlphaShape and ST_OptimalAlphaShape.
NOTE: GEOS 3.11.0 was recently released, details at GEOS 3.11.0 release notes
The new --enable-lto flag improves speed of math computations. This new feature is disabled by default because on some
platforms, causes compilation errors (BSD and MingW64 issues have been raised)
Use below to enable it.
./configure --enable-lto
2022/07/13
This version requires PostgreSQL 11 or higher, GEOS 3.6 or higher, and Proj 5.2+. Additional features are enabled if you are
running GEOS 3.9+ ST_MakeValid enhancements with 3.10+, numerous additional enhancements with GEOS 3.11+. Requires
SFCGAL 1.4.1+ for ST_AlphaShape and ST_OptimalAlphaShape.
NOTE: GEOS 3.11.0 was recently released, details at GEOS 3.11.0 release notes
The new --enable-lto flag improves speed of math computations. This new feature is disabled by default because on some
platforms, causes compilation errors (BSD and MingW64 issues have been raised)
Use below to enable it.
./configure --enable-lto
A.6.2 Enhancements
2022/07/03
This version requires PostgreSQL 11 or higher, GEOS 3.6 or higher, and Proj 5.2+. Additional features are enabled if you are
running GEOS 3.9+ ST_MakeValid enhancements with 3.10+, numerouse additional enhancements with GEOS 3.11+.
Requires SFCGAL 1.4.1+ for ST_AlphaShape and ST_OptimalAlphaShape.
NOTE: GEOS 3.11.0 was recently released, details at GEOS 3.11.0 release notes
The new --enable-lto flag improves math computations. This new feature is disabled by default because on some platforms,
causes compilation errors (BSD and MingW64 issues have been raised)
Use below to enable it.
./configure --enable-lto
A.7.1 Enhancements
2022/05/21
This version requires PostgreSQL 11 or higher, GEOS 3.6 or higher, and Proj 4.9+. Additional features are enabled if you are
running GEOS 3.9+ (precision feature of many processing functions) ST_MakeValid enhancements with 3.10+, ST_ConcaveHull
native GEOS implementation with GEOS 3.11+
Requires SFCGAL 1.4.1+ for ST_AlphaShape and ST_OptimalAlphaShape.
The new --enable-lto flag improves math computations. This new feature is disabled by default because on some platforms,
causes compilation errors (BSD and MingW64 issues have been raised)
Use below to enable it.
./configure --enable-lto
A.8.2 Enhancements
2861, Add index on topology.node(containing_face) speeding up splitting and merging of faces (Sandro Santilli)
2083, Speed up ST_RemEdge topology functions adding index on relation(element_id) and edge_data(abs_next*) (Sandro San-
tilli)
5118, Allow dropping topologies with missing topogeometry sequences (Sandro Santilli)
5111, faster topology face MBR computation (Sandro Santilli)
postgis_extensions_upgrade() support for upgrades from any PostGIS version, including yet to be released ones (Sandro Santilli)
5040, add postgis_sfcgal_full_version (Loïc Bartoletti)
GH655, GiST: balance the tree splits better in recursive calls (Darafei Praliaskouski)
GH657, GiST: do not call no-op decompress function (Aliaksandr Kalenik)
4912, GiST: fix crash on STORAGE EXTERNAL for geography (Aliaksandr Kalenik)
ST_ConcaveHull GEOS 3.11+ native implementation (Paul Ramsey, Martin Davis)
4574, GH678, #5121 Enable Link-Time Optimizations using --enable-lto (Sergei Shoulbakov)
GH676, faster ST_Clip (Aliaksandr Kalenik)
5135, Fast GiST index build is enabled by default for PostgreSQL 15+ (Sergei Shoulbakov)
2021/12/18
This version requires PostgreSQL 9.6 or higher, GEOS 3.6 or higher, and Proj 4.9+ Additional features are enabled if you are
running GEOS 3.9+ (and ST_MakeValid enhancements with 3.10+), Proj 6.1+, and PostgreSQL 14+.
Due to some query performance degradation with the new PG14 fast index build , we have decided to disable the feature by
default until we get more user testing as to the true impact of real-world queries. If you are running PG14+, you can reenable it
by doing:
ALTER OPERATOR FAMILY gist_geometry_ops_2d USING gist
ADD FUNCTION 11 (geometry)
geometry_gist_sortsupport_2d (internal);
5008, Empty geometries are not reported as being within Infinite distance by ST_DWithin (Sandro Santilli)
4824, Removed --without-wagyu build option. Using Wagyu is now mandatory to build with MVT support.
4933, topology.GetFaceByPoint will not work with topologies having invalid edge linking.
4981, ST_StartPoint support any geometry. No longer returns null for non-linestrings.
4149, ST_AsMVTGeom now preserves more of original geometry’s details at scale close to target extent. If you need previous
simplifying behaviour, you can ST_Simplify the geometry in advance. (Darafei Praliaskouski)
- Proj 4.9 or higher is required
5000, Turn off Window support in ST_AsMVT aggregate as no real use-case for it and it crashes with random input (Paul
Ramsey)
A.9.2 Enhancements
2021/12/04
This version requires PostgreSQL 9.6 or higher, GEOS 3.6 or higher, and Proj 4.9+ Additional features are enabled if you are
running GEOS 3.9+ (and ST_MakeValid enhancements with 3.10+), Proj 6.1+, and PostgreSQL 14+.
Due to some query performance degradation with the new PG14 fast index build , we have decided to disable the feature by
default until we get more user testing as to the true impact of real-world queries. If you are running PG14+, you can reenable it
by doing:
ALTER OPERATOR FAMILY gist_geometry_ops_2d USING gist
ADD FUNCTION 11 (geometry)
geometry_gist_sortsupport_2d (internal);
A.11.2 Enhancements
5018, pgsql2shp basic support for WITH CTE clause (Regina Obe)
5019, address_standardizer: Add support for pcre2 (Paul Ramsey)
GH647, ST_AsMVTGeom now uses faster clipping (Aliaksandr Kalenik)
GH648, ST_PixelAsCentroids, ST_PixelAsCentroid reimplemented on top of a C function (Sergei Shoulbakov)
5012, Clean regress against released GEOS 3.10.0 (Regina Obe, Paul Ramsey)
5000, Turn off Window support in ST_AsMVT aggregate as no real use-case for it and it crashes with random input (Paul
Ramsey)
4994, shp2pgsql is sometimes missing the INSERT statements (Sandro Santilli)
4990, getfacecontainingpoint fails on i386 (Sandro Santilli)
5008, Have ST_DWithin with EMPTY operand always return false (Sandro Santilli)
5002, liblwgeom should build with warning flags by default (Sandro Santilli)
A.12.2 Enhancements
#4824, Removed `--without-wagyu` build option. Using Wagyu is now mandatory to build with MVT support.
#4933, topology.GetFaceByPoint will not work with topologies having invalid edge linking.
#4981, ST_StartPoint support any geometry. No longer returns null for non-linestrings.
#4149, ST_AsMVTGeom now preserves more of original geometry’s details at scale close to target extent. If you need previous
simplifying behaviour, you can ST_Simplify the geometry in advance. (Darafei Praliaskouski)
Proj 4.9 or higher is required.
PostGIS 3.3.2 Manual 843 / 902
A.13.2 Enhancements
#2592, Do not allow CreateTopology to define topologies with SRID > 0 (Sandro Santilli)
#3232, Prevent moving an isolated node to different face (Sandro Santilli)
Consider collection TopoGeometries while editing topology primitives. (Sandro Santilli)
#3248, Prevent removing isolated edges if used in a TopoGeometry (Sandro Santilli)
#3231, Prevent removing isolated nodes if used in a TopoGeometry (Sandro Santilli)
#3239, Prevent headling topology edges if the connecting node is used in the definition of a TopoGeometry (Sandro Santilli)
#4950, Speed up checking containing_face for nodes in ValidateTopology (Sandro Santilli)
#4945, Multi-shell face check in ValidateTopology (Sandro Santilli)
#4944, Side-location conflict check in ValidateTopology (Sandro Santilli)
#3042, ValidateTopology check for edge linking (Sandro Santilli)
#3276, ValidateTopology check for face’s mbr (Sandro Santilli)
#4936, Bounding box limited ValidateTopology (Sandro Santilli)
#4933, Speed up topology building in presence of big faces (Sandro Santilli)
#3233, ValidateTopology check for node’s containing_face (Sandro Santilli)
#4830, ValidateTopology check for edges side face containment (Sandro Santilli)
#4827, Allow NaN coordinates in WKT input (Paul Ramsey)
ST_Value() accepts resample parameter to add bilinear option (Paul Ramsey)
#3778, #4401, ST_Boundary now works for TIN and does not linearize curves (Aliaksandr Kalenik)
#4881, #4884, Store sign of edge_id for lineal TopoGeometry in relation table to retain direction (Sandro Santilli)
#4628, Add an option to disable ANALYZE when loading shapefiles (Stefan Corneliu Petrea)
#4924, Faster ST_RemoveRepeatedPoints on large multipoints, O(NlogN) instead of O(Nˆ2) (Aliaksandr Kalenik, Darafei
Praliaskouski)
#4925, fix ST_DumpPoints to not overlook points (Aliaksandr Kalenik)
ST_SRID(topogeometry) override, to speedup lookups (Sandro Santilli)
#2175, Avoid creating additional nodes when adding same closed line to topology (Sandro Santilli)
#4974, Upgrade path for address_standardizer_data_us (Jan Katins of Aiven, Regina Obe)
#4975, PostGIS upgrade change to not use temp tables (Jan Katins of Aiven)
#4981, ST_StartPoint support any geometry (Aliaksandr Kalenik)
#4799, Include srs in GeoJSON where it exists in spatial_ref_sys.
#4986, GIST indexes on Postgres 14 are now created faster using Hilbert-sorting method. (Han Wang, Aliaksandr Kalenik,
Darafei Praliaskouski, Giuseppe Broccolo)
#4949, Use proj_normalize_for_visualization to hand "axis swap" decisions (Paul Ramsey)
A.14.2 Enhancements
4737, Bump minimum protobuf-c requirement to 1.1.0 (Raúl Marín) The configure step will now fail if the requirement isn’t met
or explicitly disabled (--without-protobuf)
4258, Untangle postgis_sfcgal from postgis into its own lib file (Regina Obe)
PostGIS 3.3.2 Manual 845 / 902
A.15.3 Enhancements
4789, Speed up TopoJSON output for areal TopoGeometry with many holes (Sandro Santilli)
4758, Improve topology noding robustness (Sandro Santilli)
Make ST_Subdivide interruptable (Sandro Santilli)
4660, Changes in double / coordinate printing (Raúl Marín) - Use the shortest representation (enough to guarantee roundtrip).
- Uses scientific notation for absolute numbers smaller than 1e-8. The previous behaviour was to output 0 for absolute values
smaller than 1e-12 and fixed notation for anything bigger than that. - Uses scientific notation for absolute numbers greater than
1e+15 (same behaviour). - The precision parameter now also affects the scientific notation (before it was fixed [5-8]). - All
output functions now respect the requested precision (without any limits). - The default precision is the same (9 for GeoJSON,
15 for everything else).
4729, WKT/KML: Print doubles directly into stringbuffers (Raúl Marín)
4533, Use the standard coordinate printing system for box types (Raúl Marín)
4686, Avoid decompressing geographies when possible (Raúl Marín) Affects ANALYZE, _ST_PointOutside, postgis_geobbox,
ST_CombineBbox(box2d, geometry), ST_ClipByBox2D when the geometry is fully inside or outside the bbox and ST_BoundingDiagon
4741, Don’t use ST_PointInsideCircle if you need indexes, use ST_DWithin instead. Documentation adjusted (Darafei Praliask-
ouski)
4737, Improve performance and reduce memory usage in ST_AsMVT, especially in queries involving parallelism (Raúl Marín)
4746, Micro optimizations to the serialization process (Raúl Marín)
4719, Fail fast when srids don’t match ST_Intersection(geometry,raster) Also schema qualify calls in function. (Regina Obe)
4784, Add ST_CollectionExtract(geometry) with default behaviour of extracting the components of highest coordinate dimen-
sion. (Paul Ramsey)
4691, Fix segfault during gist index creation with empty geometries (Raúl Marín)
Fix handling of bad WKB inputs (Oracle types) and unit tests for malformed WKB. Remove memory leaks in malformed WKB
cases. (Paul Ramsey)
4740, Round values in geography_distance_tree as we do on geography_distance (Raúl Marín, Paul Ramsey, Regina Obe)
4739, Ensure all functions using postgis_oid initialize the internal cache (Raúl Marín)
4767, #4768, #4771, #4772, Fix segfault when parsing invalid WKB (Raúl Marín)
4769, Fix segfault in st_addband (Raúl Marín)
4790, Fix ST_3dintersects calculations with identical vertices (Nicklas Avén)
4742, tiger geocoder reverted to 2018 version on tiger upgrade (Regina Obe)
3372, TopoElementArray cannot be null - change domain constraint (Regina Obe)
A.16.2 Enhancements
svn number replaced by git hash in version output (Sandro Santilli, Raúl Marín)
4577, Drop support for PostgreSQL 9.5 (Raúl Marín)
4579, Drop postgis_proc_set_search_path.pl (Raúl Marín)
4601, ST_TileEnvelope signature changed.
3057, ST_Force3D, ST_Force3DZ, ST_Force3DM and ST_Force4D signatures changed.
PostGIS 3.3.2 Manual 847 / 902
A.17.3 Enhancements
4267, Bump minimum GEOS version to 3.6 (Regina Obe, Darafei Praliaskouski)
3888, Raster support now available as a separate extension (Sandro Santilli)
3807, Extension library files no longer include the minor version. Use New configure switch --with-library-minor-version if you
need the old behavior (Regina Obe)
4230, ND box operators (overlaps, contains, within, equals) now don’t look on dimensions that aren’t present in both operands.
Please REINDEX your ND indexes after upgrade. (Darafei Praliaskouski)
4229, Dropped support for PostgreSQL < 9.5. (Darafei Praliaskouski)
4260, liblwgeom headers are not installed anymore. If your project depends on them available, please use librttopo instead.
(Darafei Praliaskouski)
4258, Remove SFCGAL support for ST_Area, ST_Distance, ST_Intersection, ST_Difference, ST_Union, ST_Intersects, ST_3DIntersect
ST_3DDistance and postgis.backend switch (Darafei Praliaskouski)
4267, Enable Proj 6 deprecated APIs (Darafei Praliaskouski, Raúl Marín)
4268, Bump minimum SFCGAL version to 1.3.1 (Darafei Praliaskouski)
4331, ST_3DMakeBox now returns error instead of a miniscule box (Regina Obe)
4342, Removed "versioned" variants of ST_AsGeoJSON and ST_AsKML (Paul Ramsey)
4356, ST_Accum removed. Use array_agg instead. (Darafei Praliaskouski)
4414, Include version number in address_standardizer lib (Raúl Marín)
4334, Fix upgrade issues related to renamed function parameters (Raúl Marín)
4442, raster2pgsql now skips NODATA tiles. Use -k option if you still want them in database for some reason. (Darafei
Praliaskouski)
4433, 32-bit hash fix (requires reindexing hash(geometry) indexes) (Raúl Marín)
3383, Sorting now uses Hilbert curve and Postgres Abbreviated Compare. You need to REINDEX your btree indexes if you had
them. (Darafei Praliaskouski)
A.18.3 Enhancements
4341, Using "support function" API in PgSQL 12+ to replace SQL inlining as the mechanism for providing index support under
ST_Intersects, et al
4330, postgis_restore OOM when output piped to an intermediate process (Hugh Ranalli)
4322, Support for Proj 6+ API, bringing more accurate datum transforms and support for WKT projections
4153, ST_Segmentize now splits segments proportionally (Darafei Praliaskouski).
4162, ST_DWithin documentation examples for storing geometry and radius in table (Darafei Praliaskouski, github user Boscop).
4161 and #4294, ST_AsMVTGeom: Shortcut geometries smaller than the resolution (Raúl Marín)
4176, ST_Intersects supports GEOMETRYCOLLECTION (Darafei Praliaskouski)
4181, ST_AsMVTGeom: Avoid type changes due to validation (Raúl Marín)
4183, ST_AsMVTGeom: Drop invalid geometries after simplification (Raúl Marín)
4196, Have postgis_extensions_upgrade() package unpackaged extensions (Sandro Santilli)
4215, Use floating point compare in ST_DumpAsPolygons (Darafei Praliaskouski)
4155, Support for GEOMETRYCOLLECTION, POLYGON, TIN, TRIANGLE in ST_LocateBetween and ST_LocateBetweenElevation
(Darafei Praliaskouski)
2767, Documentation for AddRasterConstraint optional parameters (Sunveer Singh)
PostGIS 3.3.2 Manual 849 / 902
4492, Fix ST_Simplify ignoring the value of the 3rd parameter (Raúl Marín)
4494, Fix ST_Simplify output having an outdated bbox (Raúl Marín)
4493, Fix ST_RemoveRepeatedPoints output having an outdated bbox (Raúl Marín)
4495, Fix ST_SnapToGrid output having an outdated bbox (Raúl Marín)
4496, Make ST_Simplify(TRIANGLE) collapse if requested (Raúl Marín)
4501, Allow postgis_tiger_geocoder to be installable by non-super users (Regina Obe)
4503, Speed up the calculation of cartesian bbox (Raúl Marín)
4504, shp2pgsql -D not working with schema qualified tables (Regina Obe)
4505, Speed up conversion of geometries to/from GEOS (Dan Baston)
4507, Use GEOSMakeValid and GEOSBuildArea for GEOS 3.8+ (Dan Baston)
4491, Speed up ST_RemoveRepeatedPoints (Raúl Marín)
4509, Update geocoder for tiger 2019 (Regina Obe)
4338, Census block level data (tabblock table) not loading (Regina Obe)
PostGIS 3.3.2 Manual 851 / 902
4433, 32-bit hash fix (requires reindexing hash(geometry) indexes) (Raúl Marín)
4445, Fix a bug in geometry_le (Raúl Marín)
4451, Fix the calculation of gserialized_max_header_size (Raúl Marín)
4450, Speed up ST_GeometryType (Raúl Marín)
4452, Add ST_TileEnvelope() (Paul Ramsey)
4403, Support for shp2pgsql ability to reproject with copy mode (-D) (Regina Obe)
4417, Update spatial_ref_sys with new entries (Paul Ramsey)
4449, Speed up ST_X, ST_Y, ST_Z and ST_M (Raúl Marín)
4454, Speed up _ST_OrderingEquals (Raúl Marín)
4453, Speed up ST_IsEmpty (Raúl Marín)
4271, postgis_extensions_upgrade() also updates after pg_upgrade (Raúl Marín)
4466, Fix undefined behaviour in _postgis_gserialized_stats (Raúl Marín)
4209, Handle NULL geometry values in pgsql2shp (Paul Ramsey)
4419, Use protobuf version to enable/disable mvt/geobuf (Paul Ramsey)
4437, Handle POINT EMPTY in shape loader/dumper (Paul Ramsey)
4456, add Rasbery Pi 32-bit jenkins bot for testing (Bruce Rindahl,Regina Obe)
4420, update path does not exists for address_standardizer extension (Regina Obe)
#1847, spgist 2d and 3d support for PG 11+ (Esteban Zimányi and Arthur Lesuisse from Université Libre de Bruxelles (ULB),
Darafei Praliaskouski)
#4056, ST_FilterByM (Nicklas Avén)
#4050, ST_ChaikinSmoothing (Nicklas Avén)
#3989, ST_Buffer single sided option (Stephen Knox)
#3876, ST_Angle function (Rémi Cura)
#3564, ST_LineInterpolatePoints (Dan Baston)
#3896, PostGIS_Extensions_Upgrade() (Regina Obe)
#3913, Upgrade when creating extension from unpackaged (Sandro Santilli)
#2256, _postgis_index_extent() for extent from index (Paul Ramsey)
#3176, Add ST_OrientedEnvelope (Dan Baston)
#4029, Add ST_QuantizeCoordinates (Dan Baston)
#4063, Optional false origin point for ST_Scale (Paul Ramsey)
#4082, Add ST_BandFileSize and ST_BandFileTimestamp, extend ST_BandMetadata (Even Rouault)
#2597, Add ST_Grayscale (Bborie Park)
#4007, Add ST_SetBandPath (Bborie Park)
#4008, Add ST_SetBandIndex (Bborie Park)
Upgrade scripts from multiple old versions are now all symlinks to a single upgrade script (Sandro Santilli)
#3944, Update to EPSG register v9.2 (Even Rouault)
#3927, Parallel implementation of ST_AsMVT
#3925, Simplify geometry using map grid cell size before generating MVT
#3899, BTree sort order is now defined on collections of EMPTY and same-prefix geometries (Darafei Praliaskouski)
#3864, Performance improvement for sorting POINT geometries (Darafei Praliaskouski)
#3900, GCC warnings fixed, make -j is now working (Darafei Praliaskouski) - TopoGeo_addLinestring robustness improvements
(Sandro Santilli) #1855, #1946, #3718, #3838
#3234, Do not accept EMPTY points as topology nodes (Sandro Santilli)
#1014, Hashable geometry, allowing direct use in CTE signatures (Paul Ramsey)
#3097, Really allow MULTILINESTRING blades in ST_Split() (Paul Ramsey)
#3942, geojson: Do not include private header for json-c >= 0.13 (Björn Esser)
#3954, ST_GeometricMedian now supports point weights (Darafei Praliaskouski)
#3965, #3971, #3977, #4071 ST_ClusterKMeans rewritten: better initialization, faster convergence, K=2 even faster (Darafei
Praliaskouski)
#3982, ST_AsEncodedPolyline supports LINESTRING EMPTY and MULTIPOINT EMPTY (Darafei Praliaskouski)
#3986, ST_AsText now has second argument to limit decimal digits (Marc Ducobu, Darafei Praliaskouski)
#4020, Casting from box3d to geometry now returns correctly connected PolyhedralSurface (Matthias Bay)
#2508, ST_OffsetCurve now works with collections (Darafei Praliaskouski)
PostGIS 3.3.2 Manual 854 / 902
#4006, ST_GeomFromGeoJSON support for json and jsonb as input (Paul Ramsey, Regina Obe)
#4038, ST_Subdivide now selects pivot for geometry split that reuses input vertices. (Darafei Praliaskouski)
#4025, #4032 Fixed precision issue in ST_ClosestPointOfApproach, ST_DistanceCPA, and ST_CPAWithin (Paul Ramsey,
Darafei Praliaskouski)
#4076, Reduce use of GEOS in topology implementation (Björn Harrtell)
#4080, Add external raster band index to ST_BandMetaData - Add Raster Tips section to Documentation for information about
Raster behavior (e.g. Out-DB performance, maximum open files)
#4084: Fixed wrong code-comment regarding front/back of BOX3D (Matthias Bay)
#4060, #4094, PostgreSQL JIT support (Raúl Marín, Laurenz Albe)
#3960, ST_Centroid now uses lwgeom_centroid (Darafei Praliaskouski)
#4027, Remove duplicated code in lwgeom_geos (Darafei Praliaskouski, Daniel Baston)
#4115, Fix a bug that created MVTs with incorrect property values under parallel plans (Raúl Marín).
#4120, ST_AsMVTGeom: Clip using tile coordinates (Raúl Marín).
#4132, ST_Intersection on Raster now works without throwing TopologyException (Vinícius A.B. Schmidt, Darafei Praliask-
ouski)
#4177, #4180 Support for PostgreSQL 12 dev branch (Laurenz Albe, Raúl Marín)
#4156, ST_ChaikinSmoothing: also smooth start/end point of polygon by default (Darafei Praliaskouski)
#3055, [raster] ST_Clip() on a raster without band crashes the server (Regina Obe)
#3942, geojson: Do not include private header for json-c >= 0.13 (Björn Esser)
#3952, ST_Transform fails in parallel mode (Paul Ramsey)
#3978, Fix KNN when upgrading from 2.1 or older (Sandro Santilli)
#4003, lwpoly_construct_circle: Avoid division by zero (Raúl Marín Rodríguez)
#4004, Avoid memory exhaustion when building a btree index (Edmund Horner)
#4016, proj 5.0.0 support (Raúl Marín Rodríguez)
#4017, lwgeom lexer memory corruption (Peter E)
#4020, Casting from box3d to geometry now returns correctly connected PolyhedralSurface (Matthias Bay)
#4025, #4032 Incorrect answers for temporally "almost overlapping" ranges (Paul Ramsey, Darafei Praliaskouski)
#4052, schema qualify several functions in geography (Regina Obe)
#4055, ST_ClusterIntersecting drops SRID (Daniel Baston)
A.28.2 Enhancements
#3822, Have postgis_full_version() also show and check version of PostgreSQL the scripts were built against (Sandro Santilli)
#2411, curves support in ST_Reverse (Sandro Santilli)
#2951, ST_Centroid for geography (Danny Götte)
#3788, Allow postgis_restore.pl to work on directory-style (-Fd) dumps (Roger Crew)
#3772, Direction agnostic ST_CurveToLine output (Sandro Santilli / KKGeo)
#2464, ST_CurveToLine with MaxError tolerance (Sandro Santilli / KKGeo)
#3599, Geobuf output support via ST_AsGeobuf (Björn Harrtell)
#3661, Mapbox vector tile output support via ST_AsMVT (Björn Harrtell / CartoDB)
#3689, Add orientation checking and forcing functions (Dan Baston)
#3753, Gist penalty speed improvements for 2D and ND points (Darafei Praliaskouski, Andrey Borodin)
#3677, ST_FrechetDistance (Shinichi Sugiyama)
Most aggregates (raster and geometry), and all stable / immutable (raster and geometry) marked as parallel safe
#2249, ST_MakeEmptyCoverage for raster (David Zwarg, ainomieli)
#3709, Allow signed distance for ST_Project (Darafei Praliaskouski)
#524, Covers support for polygon on polygon, line on line, point on line for geography (Danny Götte)
Many corrections to docs and several translations almost complete. Andreas Schild who provided many corrections to core docs.
PostGIS Japanese translation team first to reach completion of translation.
Support for PostgreSQL 10
Preliminary support for PostgreSQL 11
#3645, Avoid loading logically deleted records from shapefiles
#3747, Add zip4 and address_alphanumeric as attributes to norm_addy tiger_geocoder type.
#3748, address_standardizer lookup tables update so pagc_normalize_address better standardizes abbreviations
#3647, better handling of noding in ST_Node using GEOSNode (Wouter Geraedts)
#3684, Update to EPSG register v9 (Even Rouault)
#3830, Fix initialization of incompatible type (>=9.6) address_standardizer
#3662, Make shp2pgsql work in debug mode by sending debug to stderr
#3405, Fixed memory leak in lwgeom_to_points
#3832, Support wide integer fields as int8 in shp2pgsql
#3841, Deterministic sorting support for empty geometries in btree geography
#3844, Make = operator a strict equality test, and < > to rough "spatial sorting"
#3855, ST_AsTWKB memory and speed improvements
PostGIS 3.3.2 Manual 858 / 902
#3418, KNN recheck in 9.5+ fails with index returned tuples in wrong order
#3675, Relationship functions not using an index in some cases
#3680, PostGIS upgrade scripts missing GRANT for views
#3683, Unable to update postgis after postgres pg_upgrade going from < 9.5 to pg > 9.4
#3688, ST_AsLatLonText: round minutes
PostGIS 3.3.2 Manual 859 / 902
#1973, st_concavehull() returns sometimes empty geometry collection Fix from gde
#3501, add raster constraint max extent exceeds array size limit for large tables
#3643, PostGIS not building on latest OSX XCode
#3644, Deadlock on interrupt
#3650, Mark ST_Extent, ST_3DExtent and ST_Mem* agg functions as parallel safe so they can be parallelized
#3652, Crash on Collection(MultiCurve())
#3656, Fix upgrade of aggregates from 2.2 or lower version
#3659, Crash caused by raster GUC define after CREATE EXTENSION using wrong memory context. (manaeem)
#3665, Index corruption and memory leak in BRIN indexes patch from Julien Rouhaud (Dalibo)
#3667, geography ST_Segmentize bug patch from Hugo Mercier (Oslandia)
#3466, Casting from box3d to geometry now returns a 3D geometry (Julien Rouhaud of Dalibo)
#3396, ST_EstimatedExtent, throw WARNING instead of ERROR (Regina Obe)
#3407, Fix crash on splitting a face or an edge defining multiple TopoGeometry objects
#3411, Clustering functions not using spatial index
#3412, Improve robustness of snapping step in TopoGeo_addLinestring
#3415, Fix OSX 10.9 build under pkgsrc
Fix memory leak in lwt_ChangeEdgeGeom [liblwgeom]
A.39.2 Enhancements
A.42.1 Enhancements
A.43.1 Enhancements
A.44.1 Enhancements
Starting with this version offline raster access and use of GDAL drivers are disabled by default.
An environment variable is introduced to allow for enabling specific GDAL drivers: POSTGIS_GDAL_ENABLED_DRIVERS.
By default, all GDAL drivers are disabled
An environment variable is introduced to allow for enabling out-db raster bands: POSTGIS_ENABLE_OUTDB_RASTERS. By
default, out-db raster bands are disabled
The environment variables must be set for the PostgreSQL process, and determines the behavior of the whole cluster.
PostGIS 3.3.2 Manual 867 / 902
A.46.2 Enhancements
#2514, Change raster license from GPL v3+ to v2+, allowing distribution of PostGIS Extension as GPLv2.
A.47.3 Enhancements
#1653, Removed srid parameter from ST_Resample(raster) and variants with reference raster no longer apply reference raster’s
SRID.
#1962 ST_Segmentize - As a result of the introduction of geography support, The construct: SELECT ST_Segmentize(’LINESTRI
2, 3 4)’,0.5); will result in ambiguous function error
#2026, ST_Union(raster) now unions all bands of all rasters
#2089, liblwgeom: lwgeom_set_handlers replaces lwgeom_init_allocators.
#2150, regular_blocking is no longer a constraint. column of same name in raster_columns now checks for existance of spa-
tially_unique and coverage_tile constraints
PostGIS 3.3.2 Manual 869 / 902
#1856, reverse geocoder rating setting for prefer numbered highway name
ST_PixelOfValue (Bborie Park / UC Davis)
Casts to/from PostgreSQL geotypes (point/path/polygon).
Added geomval array variant of ST_SetValues() to set many pixel values of a band using a set of geometries and corresponding
values in one call (Bborie Park / UC Davis)
ST_Tile(raster) to break up a raster into tiles (Bborie Park / UC Davis)
#1895, new r-tree node splitting algorithm (Alex Korotkov)
#2011, ST_DumpValues to output raster as array (Bborie Park / UC Davis)
#2018, ST_Distance support for CircularString, CurvePolygon, MultiCurve, MultiSurface, CompoundCurve
#2030, n-raster (and n-band) ST_MapAlgebra (Bborie Park / UC Davis)
#2193, Utilize PAGC parser as drop in replacement for tiger normalizer (Steve Woodbridge, Regina Obe)
#2210, ST_MinConvexHull(raster)
lwgeom_from_geojson in liblwgeom (Sandro Santilli / Vizzuality)
#1687, ST_Simplify for TopoGeometry (Sandro Santilli / Vizzuality)
#2228, TopoJSON output for TopoGeometry (Sandro Santilli / Vizzuality)
#2123, ST_FromGDALRaster
#613, ST_SetGeoReference with numerical parameters instead of text
#2276, ST_AddBand(raster) variant for out-db bands
#2280, ST_Summary(raster)
#2163, ST_TPI for raster (Nathaniel Clay)
#2164, ST_TRI for raster (Nathaniel Clay)
#2302, ST_Roughness for raster (Nathaniel Clay)
#2290, ST_ColorMap(raster) to generate RGBA bands
#2254, Add SFCGAL backend support. (Backend selection throught postgis.backend var) Functions available both throught
GEOS or SFCGAL: ST_Intersects, ST_3DIntersects, ST_Intersection, ST_Area, ST_Distance, ST_3DDistance New functions
available only with SFCGAL backend: ST_3DIntersection, ST_Tesselate, ST_3DArea, ST_Extrude, ST_ForceLHR ST_Orientation,
ST_Minkowski, ST_StraightSkeleton postgis_sfcgal_version New function available in PostGIS: ST_ForceSFS (Olivier Courtin
and Hugo Mercier / Oslandia)
A.48.3 Enhancements
For detail of new functions and function improvements, please refer to Section 15.12.10.
Much faster raster ST_Union, ST_Clip and many more function additions operations
For geometry/geography better planner selectivity and a lot more functions.
#823, tiger geocoder: Make loader_generate_script download portion less greedy
#826, raster2pgsql no longer defaults to padding tiles. Flag -P can be used to pad tiles
#1363, ST_AddBand(raster, ...) array version rewritten in C
#1364, ST_Union(raster, ...) aggregate function rewritten in C
#1655, Additional default values for parameters of ST_Slope
#1661, Add aggregate variant of ST_SameAlignment
#1719, Add support for Point and GeometryCollection ST_MakeValid inputs
PostGIS 3.3.2 Manual 871 / 902
A.48.4 Fixes
#2111, Raster bands can only reference the first 256 bands of out-db rasters
##2514, Change raster license from GPL v3+ to v2+, allowing distribution of PostGIS Extension as GPLv2.
A.50.2 Enhancements
#2111, Raster bands can only reference the first 256 bands of out-db rasters
A.51.2 Enhancements
#2141, More verbose output when constraints fail to be added to a raster column
Speedup ST_ChangeEdgeGeom
#1287, Drop of "gist_geometry_ops" broke a few clients package of legacy_gist.sql for these cases
#1391, Errors during upgrade from 1.5
#1828, Poor selectivity estimate on ST_DWithin
#1838, error importing tiger/line data
#1869, ST_AsBinary is not unique added to legacy_minor/legacy.sql scripts
#1885, Missing field from tabblock table in tiger2010 census_loader.sql
#1891, Use LDFLAGS environment when building liblwgeom
#1900, Fix pgsql2shp for big-endian systems
#1932, Fix raster2pgsql for invalid syntax for setting index tablespace
#1936, ST_GeomFromGML on CurvePolygon causes server crash
#1955, ST_ModEdgeHeal and ST_NewEdgeHeal for doubly connected edges
#1957, ST_Distance to a one-point LineString returns NULL
#1976, Geography point-in-ring code overhauled for more reliability
#1978, wrong answer calculating length of closed circular arc (circle)
#1981, Remove unused but set variables as found with gcc 4.6+
PostGIS 3.3.2 Manual 876 / 902
A.52.2 Enhancements
#1581, ST_Clip(raster, ...) no longer imposes NODATA on a band if the corresponding band from the source raster did not have
NODATA
#1928, Accept array properties in GML input multi-geom input (Kashif Rasul and Shoaib Burq / SpacialDB)
#2082, Add indices on start_node and end_node of topology edge tables
#2087, Speedup topology.GetRingEdges using a recursive CTE
A.53.2 Enhancements
We are most indebted to the numerous members in the PostGIS community who were brave enough to test out the new features
in this release. No major release can be successful without these folk.
Below are those who have been most valiant, provided very detailed and thorough bug reports, and detailed analysis.
Andrea Peri - Lots of testing on topology, checking for correctness
Andreas Forø Tollefsen - raster testing
Chris English - topology stress testing loader functions
Salvatore Larosa - topology robustness testing
Brian Hamlin - Benchmarking (also experimental experimental branches before they are folded into core) , general testing of various p
Mike Pease - Tiger geocoder testing - very detailed reports of issues
Tom van Tilburg - raster testing
#722, #302, Most deprecated functions removed (over 250 functions) (Regina Obe, Paul Ramsey)
Unknown SRID changed from -1 to 0. (Paul Ramsey)
-- (most deprecated in 1.2) removed non-ST variants buffer, length, intersects (and internal functions renamed) etc.
-- If you have been using deprecated functions CHANGE your apps or suffer the consequences. If you don’t see a function
documented -- it ain’t supported or it is an internal function. Some constraints in older tables were built with deprecated functions.
If you restore you may need to rebuild table constraints with populate_geometry_columns(). If you have applications or tools
that rely on deprecated functions, please refer to [?qandaentry] for more details.
#944 geometry_columns is now a view instead of a table (Paul Ramsey, Regina Obe) for tables created the old way reads (srid,
type, dims) constraints for geometry columns created with type modifiers reads rom column definition
#1081, #1082, #1084, #1088 - Mangement functions support typmod geometry column creation functions now default to typmod
creation (Regina Obe)
#1083 probe_geometry_columns(), rename_geometry_table_constraints(), fix_geometry_columns(); removed - now obsolete
with geometry_column view (Regina Obe)
#817 Renaming old 3D functions to the convention ST_3D (Nicklas Avén)
#548 (sorta), ST_NumGeometries,ST_GeometryN now returns 1 (or the geometry) instead of null for single geometries (Sandro
Santilli, Maxime van Noppen)
PostGIS 3.3.2 Manual 879 / 902
KNN Gist index based centroid (<->) and box (<#>) distance operators (Paul Ramsey / funded by Vizzuality)
Support for TIN and PolyHedralSurface and enhancement of many functions to support 3D (Olivier Courtin / Oslandia)
Raster support integrated and documented (Pierre Racine, Jorge Arévalo, Mateusz Loskot, Sandro Santilli, David Zwarg, Regina
Obe, Bborie Park) (Company developer and funding: University Laval, Deimos Space, CadCorp, Michigan Tech Research
Institute, Azavea, Paragon Corporation, UC Davis Center for Vectorborne Diseases)
Making spatial indexes 3D aware - in progress (Paul Ramsey, Mark Cave-Ayland)
Topology support improved (more functions), documented, testing (Sandro Santilli / Faunalia for RT-SIGTA), Andrea Peri,
Regina Obe, Jose Carlos Martinez Llari
3D relationship and measurement support functions (Nicklas Avén)
ST_3DDistance, ST_3DClosestPoint, ST_3DIntersects, ST_3DShortestLine and more...
N-Dimensional spatial indexes (Paul Ramsey / OpenGeo)
ST_Split (Sandro Santilli / Faunalia for RT-SIGTA)
ST_IsValidDetail (Sandro Santilli / Faunalia for RT-SIGTA)
ST_MakeValid (Sandro Santilli / Faunalia for RT-SIGTA)
ST_RemoveRepeatedPoints (Sandro Santilli / Faunalia for RT-SIGTA)
ST_GeometryN and ST_NumGeometries support for non-collections (Sandro Santilli)
ST_IsCollection (Sandro Santilli, Maxime van Noppen)
ST_SharedPaths (Sandro Santilli / Faunalia for RT-SIGTA)
ST_Snap (Sandro Santilli)
ST_RelateMatch (Sandro Santilli / Faunalia for RT-SIGTA)
ST_ConcaveHull (Regina Obe and Leo Hsu / Paragon Corporation)
ST_UnaryUnion (Sandro Santilli / Faunalia for RT-SIGTA)
ST_AsX3D (Regina Obe / Arrival 3D funding)
ST_OffsetCurve (Sandro Santilli, Rafal Magda)
ST_GeomFromGeoJSON (Kashif Rasul, Paul Ramsey / Vizzuality funding)
A.54.4 Enhancements
Made shape file loader tolerant of truncated multibyte values found in some free worldwide shapefiles (Sandro Santilli)
Lots of bug fixes and enhancements to shp2pgsql Beefing up regression tests for loaders Reproject support for both geometry
and geography during import (Jeff Adams / Azavea, Mark Cave-Ayland)
pgsql2shp conversion from predefined list (Loic Dachary / Mark Cave-Ayland)
Shp-pgsql GUI loader - support loading multiple files at a time. (Mark Leslie)
Extras - upgraded tiger_geocoder from using old TIGER format to use new TIGER shp and file structure format (Stephen Frost)
Extras - revised tiger_geocoder to work with TIGER census 2010 data, addition of reverse geocoder function, various bug
fixes, accuracy enhancements, limit max result return, speed improvements, loading routines. (Regina Obe, Leo Hsu / Paragon
Corporation / funding provided by Hunter Systems Group)
Overall Documentation proofreading and corrections. (Kasif Rasul)
Cleanup PostGIS JDBC classes, revise to use Maven build. (Maria Arias de Reyna, Sandro Santilli)
PostGIS 3.3.2 Manual 880 / 902
We thank U.S Department of State Human Information Unit (HIU) and Vizzuality for general monetary support to get PostGIS
2.0 out the door.
#1056, produce correct bboxes for arc geometries, fixes index errors (Paul Ramsey)
#1007, ST_IsValid crash fix requires GEOS 3.3.0+ or 3.2.3+ (Sandro Santilli, reported by Birgit Laggner)
#940, support for PostgreSQL 9.1 beta 1 (Regina Obe, Paul Ramsey, patch submitted by stl)
#845, ST_Intersects precision error (Sandro Santilli, Nicklas Avén) Reported by cdestigter
#884, Unstable results with ST_Within, ST_Intersects (Chris Hodgson)
#779, shp2pgsql -S option seems to fail on points (Jeff Adams)
#666, ST_DumpPoints is not null safe (Regina Obe)
#631, Update NZ projections for grid transformation support (jpalmer)
#630, Peculiar Null treatment in arrays in ST_Collect (Chris Hodgson) Reported by David Bitner
#624, Memory leak in ST_GeogFromText (ryang, Paul Ramsey)
#609, Bad source code in manual section 5.2 Java Clients (simoc, Regina Obe)
#604, shp2pgsql usage touchups (Mike Toews, Paul Ramsey)
#573 ST_Union fails on a group of linestrings Not a PostGIS bug, fixed in GEOS 3.3.0
#457 ST_CollectionExtract returns non-requested type (Nicklas Avén, Paul Ramsey)
#441 ST_AsGeoJson Bbox on GeometryCollection error (Olivier Courtin)
#411 Ability to backup invalid geometries (Sando Santilli) Reported by Regione Toscana
#409 ST_AsSVG - degraded (Olivier Courtin) Reported by Sdikiy
#373 Documentation syntax error in hard upgrade (Paul Ramsey) Reported by psvensso
#507, Fix wrong OGC URN in GeoJSON and GML output (Olivier Courtin)
spatial_ref_sys.sql Add datum conversion for projection SRID 3021 (Paul Ramsey)
Geography - remove crash for case when all geographies are out of the estimate (Paul Ramsey)
#469, Fix for array_aggregation error (Greg Stark, Paul Ramsey)
#532, Temporary geography tables showing up in other user sessions (Paul Ramsey)
#562, ST_Dwithin errors for large geographies (Paul Ramsey)
#513, shape loading GUI tries to make spatial index when loading DBF only mode (Paul Ramsey)
#527, shape loading GUI should always append log messages (Mark Cave-Ayland)
#504, shp2pgsql should rename xmin/xmax fields (Sandro Santilli)
#458, postgis_comments being installed in contrib instead of version folder (Mark Cave-Ayland)
#474, Analyzing a table with geography column crashes server (Paul Ramsey)
#581, LWGEOM-expand produces inconsistent results (Mark Cave-Ayland)
#513, Add dbf filter to shp2pgsql-gui and allow uploading dbf only (Paul Ramsey)
Fix further build issues against PostgreSQL 9.0 (Mark Cave-Ayland)
#572, Password whitespace for Shape File (Mark Cave-Ayland)
#603, shp2pgsql: "-w" produces invalid WKT for MULTI* objects. (Mark Cave-Ayland)
#410, update embedded bbox when applying ST_SetPoint, ST_AddPoint ST_RemovePoint to a linestring (Paul Ramsey)
#411, allow dumping tables with invalid geometries (Sandro Santilli, for Regione Toscana-SIGTA)
#414, include geography_columns view when running upgrade scripts (Paul Ramsey)
#419, allow support for multilinestring in ST_Line_Substring (Paul Ramsey, for Lidwala Consulting Engineers)
#421, fix computed string length in ST_AsGML() (Olivier Courtin)
#441, fix GML generation with heterogeneous collections (Olivier Courtin)
#443, incorrect coordinate reversal in GML 3 generation (Olivier Courtin)
#450, #451, wrong area calculation for geography features that cross the date line (Paul Ramsey)
Ensure support for upcoming 9.0 PgSQL release (Paul Ramsey)
The public API of PostGIS will not change during minor (0.0.X) releases.
The definition of the =~ operator has changed from an exact geometric equality check to a bounding box equality check.
A.59.2 Compatibility
Section 15.12.14
Added Hausdorff distance calculations (#209) (Vincent Picavet)
Added parameters argument to ST_Buffer operation to support one-sided buffering and other buffering styles (Sandro Santilli)
Addition of other Distance related visualization and analysis functions (Nicklas Aven)
• ST_ClosestPoint
• ST_DFullyWithin
• ST_LongestLine
• ST_MaxDistance
• ST_ShortestLine
A.59.4 Enhancements
http://trac.osgeo.org/postgis/query?status=closed&milestone=PostGIS+1.5.0&order=priority
As of the 1.4 release series, the public API of PostGIS will not change during minor releases.
A.60.2 Compatibility
The versions below are the *minimum* requirements for PostGIS 1.4
PostgreSQL 8.2 and higher on all platforms
GEOS 3.0 and higher only
PROJ4 4.5 and higher only
ST_Union() uses high-speed cascaded union when compiled against GEOS 3.1+ (Paul Ramsey)
ST_ContainsProperly() requires GEOS 3.1+
ST_Intersects(), ST_Contains(), ST_Within() use high-speed cached prepared geometry against GEOS 3.1+ (Paul Ramsey /
funded by Zonar Systems)
Vastly improved documentation and reference manual (Regina Obe & Kevin Neufeld)
Figures and diagram examples in the reference manual (Kevin Neufeld)
ST_IsValidReason() returns readable explanations for validity failures (Paul Ramsey)
ST_GeoHash() returns a geohash.org signature for geometries (Paul Ramsey)
GTK+ multi-platform GUI for shape file loading (Paul Ramsey)
ST_LineCrossingDirection() returns crossing directions (Paul Ramsey)
ST_LocateBetweenElevations() returns sub-string based on Z-ordinate. (Paul Ramsey)
PostGIS 3.3.2 Manual 885 / 902
Geometry parser returns explicit error message about location of syntax errors (Mark Cave-Ayland)
ST_AsGeoJSON() return JSON formatted geometry (Olivier Courtin)
Populate_Geometry_Columns() -- automatically add records to geometry_columns for TABLES and VIEWS (Kevin Neufeld)
ST_MinimumBoundingCircle() -- returns the smallest circle polygon that can encompass a geometry (Bruce Rindahl)
A.60.4 Enhancements
Core geometry system moved into independent library, liblwgeom. (Mark Cave-Ayland)
New build system uses PostgreSQL "pgxs" build bootstrapper. (Mark Cave-Ayland)
Debugging framework formalized and simplified. (Mark Cave-Ayland)
All build-time #defines generated at configure time and placed in headers for easier cross-platform support (Mark Cave-Ayland)
Logging framework formalized and simplified (Mark Cave-Ayland)
Expanded and more stable support for CIRCULARSTRING, COMPOUNDCURVE and CURVEPOLYGON, better parsing,
wider support in functions (Mark Leslie & Mark Cave-Ayland)
Improved support for OpenSolaris builds (Paul Ramsey)
Improved support for MSVC builds (Mateusz Loskot)
Updated KML support (Olivier Courtin)
Unit testing framework for liblwgeom (Paul Ramsey)
New testing framework to comprehensively exercise every PostGIS function (Regine Obe)
Performance improvements to all geometry aggregate functions (Paul Ramsey)
Support for the upcoming PostgreSQL 8.4 (Mark Cave-Ayland, Talha Bin Rizwan)
Shp2pgsql and pgsql2shp re-worked to depend on the common parsing/unparsing code in liblwgeom (Mark Cave-Ayland)
Use of PDF DbLatex to build PDF docs and preliminary instructions for build (Jean David Techer)
Automated User documentation build (PDF and HTML) and Developer Doxygen Documentation (Kevin Neufeld)
Automated build of document images using ImageMagick from WKT geometry text files (Kevin Neufeld)
More attractive CSS for HTML documentation (Dane Springmeyer)
http://trac.osgeo.org/postgis/query?status=closed&milestone=PostGIS+1.4.0&order=priority
Added cached and indexed point-in-polygon short-circuits for the functions ST_Contains, ST_Intersects, ST_Within and ST_Disjoint
Added inline index support for relational functions (except ST_Disjoint)
PostGIS 3.3.2 Manual 887 / 902
Extended curved geometry support into the geometry accessor and some processing functions
Began migration of functions to the SQL-MM naming convention; using a spatial type (ST) prefix.
Added initial support for PostgreSQL 8.3
A.68.1 Changes
A.69.1 Changes
A.70.1 Upgrading
If you are upgrading from release 1.0.3 or later follow the soft upgrade procedure.
If you are upgrading from a release between 1.0.0RC6 and 1.0.2 (inclusive) and really want a live upgrade read the upgrade
section of the 1.0.3 release notes chapter.
Upgrade from any release prior to 1.0.0RC6 requires an hard upgrade.
PostGIS 3.3.2 Manual 888 / 902
A.71.1 Upgrading
If you are upgrading from release 1.0.3 or later follow the soft upgrade procedure.
If you are upgrading from a release between 1.0.0RC6 and 1.0.2 (inclusive) and really want a live upgrade read the upgrade
section of the 1.0.3 release notes chapter.
Upgrade from any release prior to 1.0.0RC6 requires an hard upgrade.
Fixed MingW link error that was causing pgsql2shp to segfault on Win32 when compiled for PostgreSQL 8.2
fixed nullpointer Exception in Geometry.equals() method in Java
Added EJB3Spatial.odt to fulfill the GPL requirement of distributing the "preferred form of modification"
Removed obsolete synchronization from JDBC Jts code.
Updated heavily outdated README files for shp2pgsql/pgsql2shp by merging them with the manpages.
Fixed version tag in jdbc code that still said "1.1.3" in the "1.1.4" release.
A.72.1 Upgrading
If you are upgrading from release 1.0.3 or later follow the soft upgrade procedure.
If you are upgrading from a release between 1.0.0RC6 and 1.0.2 (inclusive) and really want a live upgrade read the upgrade
section of the 1.0.3 release notes chapter.
Upgrade from any release prior to 1.0.0RC6 requires an hard upgrade.
reworked JTS support to reflect new upstream JTS developers’ attitude to SRID handling. Simplifies code and drops build depend
on GNU trove.
Added EJB2 support generously donated by the "Geodetix s.r.l. Company"
Added EJB3 tutorial / examples donated by Norman Barker <nbarker@ittvis.com>
Reorganized java directory layout a little.
A.73.1 Upgrading
If you are upgrading from release 1.0.3 or later follow the soft upgrade procedure.
If you are upgrading from a release between 1.0.0RC6 and 1.0.2 (inclusive) and really want a live upgrade read the upgrade
section of the 1.0.3 release notes chapter.
Upgrade from any release prior to 1.0.0RC6 requires an hard upgrade.
A.74.1 Upgrading
If you are upgrading from release 1.0.3 or later follow the soft upgrade procedure.
If you are upgrading from a release between 1.0.0RC6 and 1.0.2 (inclusive) and really want a live upgrade read the upgrade
section of the 1.0.3 release notes chapter.
Upgrade from any release prior to 1.0.0RC6 requires an hard upgrade.
A.75.1 Upgrading
If you are upgrading from release 1.0.3 or later follow the soft upgrade procedure.
If you are upgrading from a release between 1.0.0RC6 and 1.0.2 (inclusive) and really want a live upgrade read the upgrade
section of the 1.0.3 release notes chapter.
Upgrade from any release prior to 1.0.0RC6 requires an hard upgrade.
A.76.1 Credits
This release includes code from Mark Cave Ayland for caching of proj4 objects. Markus Schaber added many improvements in
his JDBC2 code. Alex Bodnaru helped with PostgreSQL source dependency relief and provided Debian specfiles. Michael Fuhr
tested new things on Solaris arch. David Techer and Gerald Fenoy helped testing GEOS C-API connector. Hartmut Tschauner
provided code for the azimuth() function. Devrim GUNDUZ provided RPM specfiles. Carl Anderson helped with the new area
building functions. See the credits section for more names.
A.76.2 Upgrading
If you are upgrading from release 1.0.3 or later you DO NOT need a dump/reload. Simply sourcing the new lwpostgis_upgrade.sql
script in all your existing databases will work. See the soft upgrade chapter for more information.
If you are upgrading from a release between 1.0.0RC6 and 1.0.2 (inclusive) and really want a live upgrade read the upgrade
section of the 1.0.3 release notes chapter.
Upgrade from any release prior to 1.0.0RC6 requires an hard upgrade.
Makefile improvements
JTS support improvements
Improved regression test system
Basic consistency check method for geometry collections
Support for (Hex)(E)wkb
Autoprobing DriverWrapper for HexWKB / EWKT switching
fix compile problems in ValueSetter for ancient jdk releases.
fix EWKT constructors to accept SRID=4711; representation
added preliminary read-only support for java2d geometries
A.77.1 Upgrading
If you are upgrading from release 1.0.3 or later you DO NOT need a dump/reload.
If you are upgrading from a release between 1.0.0RC6 and 1.0.2 (inclusive) and really want a live upgrade read the upgrade
section of the 1.0.3 release notes chapter.
Upgrade from any release prior to 1.0.0RC6 requires an hard upgrade.
Fixed palloc(0) call in collection deserializer (only gives problem with --enable-cassert)
Fixed bbox cache handling bugs
Fixed geom_accum(NULL, NULL) segfault
Fixed segfault in addPoint()
Fixed short-allocation in lwcollection_clone()
Fixed bug in segmentize()
Fixed bbox computation of SnapToGrid output
A.77.3 Improvements
Note
Return code of shp2pgsql changed from previous releases to conform to unix standards (return 0 on success).
A.78.1 Upgrading
If you are upgrading from release 1.0.3 or later you DO NOT need a dump/reload.
If you are upgrading from a release between 1.0.0RC6 and 1.0.2 (inclusive) and really want a live upgrade read the upgrade
section of the 1.0.3 release notes chapter.
Upgrade from any release prior to 1.0.0RC6 requires an hard upgrade.
PostGIS 3.3.2 Manual 895 / 902
A.79.1 Upgrading
If you are upgrading from release 1.0.3 you DO NOT need a dump/reload.
If you are upgrading from a release between 1.0.0RC6 and 1.0.2 (inclusive) and really want a live upgrade read the upgrade
section of the 1.0.3 release notes chapter.
Upgrade from any release prior to 1.0.0RC6 requires an hard upgrade.
A.79.3 Improvements
Documentation improvements
More robust selectivity estimator
Minor speedup in distance()
Minor cleanups
GiST indexing cleanup
Looser syntax acceptance in box3d parser
A.80.1 Upgrading
Due to a bug in a bounding box computation routine, the upgrade procedure requires special attention, as bounding boxes cached
in the database could be incorrect.
An hard upgrade procedure (dump/reload) will force recomputation of all bounding boxes (not included in dumps). This is
required if upgrading from releases prior to 1.0.0RC6.
If you are upgrading from versions 1.0.0RC6 or up, this release includes a perl script (utils/rebuild_bbox_caches.pl) to force
recomputation of geometries’ bounding boxes and invoke all operations required to propagate eventual changes in them (ge-
ometry statistics update, reindexing). Invoke the script after a make install (run with no args for syntax help). Optionally run
utils/postgis_proc_upgrade.pl to refresh postgis procedures and functions signatures (see Soft upgrade).
A.80.3 Improvements
A.81.1 Upgrading
If you are upgrading from release 1.0.0RC6 or up you DO NOT need a dump/reload.
Upgrading from older releases requires a dump/reload. See the upgrading chapter for more informations.
A.81.3 Improvements
A.82.1 Upgrading
If you are upgrading from release 1.0.0RC6 or up you DO NOT need a dump/reload.
Upgrading from older releases requires a dump/reload. See the upgrading chapter for more informations.
A.83.1 Upgrading
If you are upgrading from release 1.0.0RC6 you DO NOT need a dump/reload.
Upgrading from any other precedent release requires a dump/reload. See the upgrading chapter for more informations.
A.84.1 Upgrading
You need a dump/reload to upgrade from precedent releases. See the upgrading chapter for more informations.
BUGFIX in multi()
early return [when noop] from multi()
A.85.1 Upgrading
If you are upgrading from release 1.0.0RC4 you DO NOT need a dump/reload.
Upgrading from any other precedent release requires a dump/reload. See the upgrading chapter for more informations.
A.86.1 Upgrading
You need a dump/reload to upgrade from precedent releases. See the upgrading chapter for more informations.
A.87.1 Upgrading
You need a dump/reload to upgrade from precedent releases. See the upgrading chapter for more informations.
A.88.1 Upgrading
You need a dump/reload to upgrade from precedent releases. See the upgrading chapter for more informations.
A.89.1 Upgrading
You need a dump/reload to upgrade from precedent releases. See the upgrading chapter for more informations.
A.89.2 Changes