1

Consider the following table structure:

id   speed 
 1   100
 2   200
 3   300
 4   400
 5   500

Consider the following query: "SELECT * FROM records WHERE speed >= 300" - this will return the rows #3, 4, 5. Is there a way to modify this query so that with the same 300 speed parameter it would also return the first row that does not fit the condition i.e. #2. So that the end results would be rows #2, 3, 4, 5?

UPD: Note that all the values and the records count here are arbitrary and for example only. The database is SQLite.

jpw
  • 44,361
  • 6
  • 66
  • 86
Zaur Nasibov
  • 22,280
  • 12
  • 56
  • 83

3 Answers3

3

Try this:

SELECT *
FROM Test
WHERE Speed >= 300

UNION

SELECT * 
FROM (
    SELECT *
    FROM Test
    WHERE Speed < 300
    ORDER BY Speed DESC
    LIMIT 1
) AS XXX

ORDER BY Speed

See DEMO

Note: changed for SQLite syntax.

Ruslan Veselov
  • 337
  • 1
  • 10
  • I agree with the idea to just union the one row that is nearest, but this is `SQL Server` syntax and the question is tagged `SQLite` – DrCopyPaste Aug 21 '14 at 14:47
  • @DrCopyPaste Yeah, sorry for that. Should replace `TOP` with `LIMIT`, but I can not check, cause http://sqlfiddle.com/ is not available. – Ruslan Veselov Aug 21 '14 at 15:00
2

Try this simple query, which selects the row with the maximum id and speed < 300 as well as rows with speed >= 300.

SELECT * 
FROM records 
WHERE speed >= 300
OR id = (SELECT MAX(id) FROM records WHERE speed < 300)
ORDER BY id;
Joseph B
  • 5,519
  • 1
  • 15
  • 19
1
select * 
from records
order by abs(300 - speed) asc
limit 5
juergen d
  • 201,996
  • 37
  • 293
  • 362