For finding features located within a specified distance, PostGIS is equipped with a specialized ST_DWithin function. It can be imagined as a combination of ST_Buffer and ST_Within, only it omits the buffer geometry construction step and is much faster.
The syntax is as follows:
ST_DWithin(tested_geometry,reference_geometry,distance)
Let's look at an example - listing all villages located within 10 kilometers of Rybnik city:
SELECT name,wkb_geometry FROM points WHERE place='village' AND ST_DWithin(
wkb_geometry,
(SELECT wkb_geometry FROM points WHERE name='Rybnik' AND place='city'),
10000
)
Rybnik city (in the middle), villages within 10 kilometers (black), and other villages (gray)