This topic describes the ST_DWithin function. This function checks whether two objects are within a specified distance to each other. If the two objects are within a specified distance to each other, this function returns True. Otherwise, this function returns False.

Syntax

boolean  ST_DWithin(geometry  g1 , geometry  g2 , double precision  distanceOfSrid);
boolean  ST_DWithin(geography  gg1 , geography  gg2 , double precision  distanceMeters);
boolean  ST_DWithin(geography  gg1 , geography  gg2 , double precision  distanceMeters , boolean  useSpheroid);

Parameters

Parameter Description
g1 The first geometry object that you want to specify.
g2 The second geometry object that you want to specify.
distanceOfSrid The distance that you want to specify. The distance is measured in the unit that is specified in the spatial reference system of the geometry objects.
gg1 The first geography object that you want to specify.
gg2 The second geography object that you want to specify.
distanceMeters The distance that you want to specify. Unit: meters.
useSpheroid Specifies whether to use an ellipsoid reference system. If you use an ellipsoid reference system, this function returns a more accurate result but at a slightly lower speed.

Description

  • If you specify two geometry objects, the geometry objects must have the same spatial reference identifier (SRID).
  • By default, if you specify two geography objects, the distance is measured in meters.
  • This function automatically compares the bounding boxes of the geometry objects that you specify by using all available indexes on the geometry objects.
  • If you want to check whether two 3D objects are within a specified distance to each other, use the ST_3DDWithin function.

Examples

The following example shows the difference between the ST_DWithin function and the ST_DFullyWithin function:
SELECT ST_DFullyWithin(g1,g2,2), ST_DWithin(g1,g2,2) from (SELECT 'LINESTRING(0 1,1 1)'::geometry as g1,
                                                                           'LINESTRING(0 0,0 -1)'::geometry as g2) as test;
 st_dfullywithin | st_dwithin
-----------------+------------
 f               | t
(1 row)