5

I need to do a query to return the next (or prev) record if a certain record is not present. For instance consider the following table:

ID (primary key)    value
1                    John
3                    Bob
9                    Mike
10                   Tom.

I'd like to query a record that has id 7 or greater if 7 is not present.

My questions are,

  1. Are these type of queries possible with SQL?
  2. What are such queries called in the DB world?

Thanks!

Assad Ebrahim
  • 6,234
  • 8
  • 42
  • 68
user983043
  • 111
  • 1
  • 2
  • 13

4 Answers4

18

Yes, it's possible, but implementation will depend on your RDBMS.

Here's what it looks like in MySQL, PostgreSQL and SQLite:

select ID, value
from YourTable
where id >= 7
order by id
limit 1

In MS SQL-Server, Sybase and MS-Access:

select top 1 ID, value
from YourTable
where id >= 7
order by id

In Oracle:

select * from (
    select ID, value
    from YourTable
    where id >= 7 
    order by id
)
where rownum = 1

In Firebird and Informix:

select first 1 ID, value
from YourTable
where id >= 7
order by id

In DB/2 (this syntax is in SQL-2008 standard):

select id, value
from YourTable
where id >= 7
order by id
fetch first 1 rows only

In those RDBMS that have "window" functions (in SQL-2003 standard):

select ID, Value
from (
  select 
    ROW_NUMBER() OVER (ORDER BY id) as rownumber,
    Id, Value
  from YourTable
  where id >= 7
) as tmp                  --- remove the "as" for Oracle
where rownumber = 1

And if you are not sure which RDBMS you have:

select ID, value
from YourTable
where id = 
      ( select min(id)
        from YourTable
        where id >= 7
      )
ypercubeᵀᴹ
  • 113,259
  • 19
  • 174
  • 235
Adriano Carneiro
  • 57,693
  • 12
  • 90
  • 123
1

Try this for MS-SQL:

SELECT TOP 1 
id, value 
FROM your_table
WHERE id >= 7
ORDER BY id

or for MySql

SELECT id, value 
FROM your_table
WHERE id >= 7
ORDER BY id
LIMIT 0,1
Marco
  • 56,740
  • 14
  • 129
  • 152
1

I would simply do it like this:

select top 1 * from myTable where id >=7
order by id

implementation of the top 1 part is T-SQL (MSSQL/Sybase), other implementations vary but it is always possible (mysql/postgre LIMIT 1, oracle rownum = 1)

Paul Creasey
  • 28,321
  • 10
  • 54
  • 90
0
select top 1 * from Persons where Id >= @Id order by Id
Christoffer Lette
  • 14,346
  • 7
  • 50
  • 58