The ST_Within() function
The ST_Within() function returns t
(TRUE)
if the first object is completely within the second; otherwise, it
returns f
(FALSE).
Syntax
ST_Within(g1 ST_Geometry, g2 ST_Geometry)
Usage
The results of the spatial relationship of the ST_Within() function can be understood or verified by comparing the results with a pattern matrix that represents the acceptable values for the DE-9IM. The ST_Within() function pattern matrix states that the interiors of both geometries must intersect and that the interior and boundary of the primary geometry (geometry a) must not intersect the exterior of the secondary (geometry b).
b | ||||
---|---|---|---|---|
Interior | Boundary | Exterior | ||
Interior | T | * | F | |
a | Boundary | * | * | F |
Exterior | * | * | * |
Return type
BOOLEAN
Example
In the example, two tables are created: buildingfootprints contains a city's building footprints, while the other, lots, contains its lots. The city engineer wants to make sure that all the building footprints are completely inside their lots.
CREATE TABLE buildingfootprints (building_id integer,
lot_id integer,
footprint ST_MultiPolygon);
CREATE TABLE lots (lot_id integer,
lot ST_MultiPolygon);
SELECT building_id
FROM buildingfootprints, lots
WHERE ST_Within(footprint,lot);
building_id
506
543
178
SELECT bf.building_id, bf.lot_id bldg_lot_id, lots.lot_id lots_lot_id
FROM buildingfootprints bf, lots
WHERE ST_Within(footprint,lot)
AND lots.lot_id <> bf.lot_id;
building_id bldg_lot_id lots_lot_id
178 5192 203