Have no deep theoretical knowledge about this, so tested both versions on a table with 3 mio rows (ORA 18.104.22.168.).
Found no difference in time, execution plan, costs and of course not in results .
SDO_NN can return rows in ascending order of distance, while SDO_WITHIN_DISTANCE does not.
They are completely different.
sdo_nn returns the N nearest objects, whatever their distance. You can further limit the results using the distance parameter. For example if searching for the nearest gas stations, you probably only want those that are within some reasonable distance.
sdo_within_distance returns *all* objects that are within a set distance.
Albert, if you don't limit the rows returned by sdo_nn then it can give the same results as sdo within distance. For examples find the nearest gas stations within 5 miles is the same as find all gas stations within 5 miles unless you care about proximity and limit the results to the closest (x) gas stations. We tested it and performance seems to be the same with both so we are using within distance since it is more transparent and we do not care about proximity. Yhu, your point about distance ordering make sense though could I not do the same with sdo_distance?
If you don't use SDO_NN, you may do something like:
from table a
where sdo_wthin_distance(a.geom :geom, 'distance=...') = 'TRUE'
order by sdo_geom.sdo_distance(a.geom, :geom, :tolerance)
The performance of the above query depends on how many rows are returned from sdo_within_distance(),
as sorting a large number of rows can be expensive.