If you have many rows that satisfy the equality predicates on Name
, Size
, and PType
columns then you may want to include range predicates on the Area
column in your query. If the Area
column is indexed this could allow efficient index-based access.
The following query (written using Oracle syntax) uses one branch of a UNION ALL
to find the record with minimal Area >=
your target, while the other branch finds the record with maximal Area <
your target. One of these two records will be the record that you are looking for. Then you can ORDER BY ABS(Area - ?input)
to pick the winner out of those two candidates. Unfortunately the query is complex due to nested SELECTS that are needed to enforce the desired ROWNUM / ORDER BY precedence.
SELECT *
FROM
(SELECT * FROM
(SELECT * FROM
(SELECT * FROM [myTable]
WHERE Name = 'Test' AND Size = 2 AND PType = 'p' AND Area >= ?target
ORDER BY Area)
WHERE ROWNUM < 2
UNION ALL
SELECT * FROM
(SELECT * FROM [myTable]
WHERE Name = 'Test' AND Size = 2 AND PType = 'p' AND Area < ?target
ORDER BY Area DESC)
WHERE ROWNUM < 2)
ORDER BY ABS(Area - ?target))
WHERE rownum < 2
A good index for this query would be (Name, Size, PType, Area)
, in which case the expected query execution plan would be based on two index range scans that each returned a single row.