Introduction to PostgreSQL polygon Data Type
polygon
is a data type in PostgreSQL used to store closed planar polygons. It consists of a series of coordinates of points that are connected to form a closed polygonal region. The definition of a polygon
can be simple (with only one outer ring) or complex (with multiple inner rings).
Syntax
The syntax for creating a polygon
data type in PostgreSQL is as follows:
polygon
To define a column with a polygon
type in a table, you can use the following syntax:
column_name polygon
Use Cases
The polygon
data type is primarily used in fields such as Geographic Information Systems (GIS) and computational geometry to store and manipulate data related to planar polygons. It can be used to store regions on a map, such as countries, provinces, cities, counties, etc., as well as other closed areas such as factories, parks, etc.
In practical applications, the polygon
data type is often used in conjunction with other GIS-related functions and extensions, such as the PostGIS extension, for storing and manipulating spatial data in the database.
Example
In this example, we will create a table named areas
with a polygon
column named shape
. The shape
column will store polygons of various shapes.
CREATE TABLE areas (
id SERIAL PRIMARY KEY,
shape POLYGON
);
Next, we will insert some data into the areas
table:
INSERT INTO areas (shape) VALUES
('((0,0),(0,10),(10,10),(10,0),(0,0))'),
('((5,5),(5,15),(15,15),(15,5),(5,5))');
Then, we can query the areas
table and use the ST_Area
function to calculate the area of each polygon:
SELECT id, ST_Area(shape) AS area FROM areas;
After executing the above query, we will get the following result:
id | area
----+----------
1 | 100.0000
2 | 100.0000
Conclusion
The polygon
type is an important data type in PostgreSQL that can store closed polygons on a plane, and it has a wide range of applications. Whether it is storing building outlines or map regions, the polygon
type can meet the requirements well. With spatial functions such as ST_Contains
, ST_Intersects
, and ST_Area
, we can easily perform spatial queries and calculations, providing powerful support for the development of Geographic Information Systems.