2

Let's say I have a simple table of values (almost like a key/value store). There is a primary key on the table which is indexed and auto incremented. For example here are some rows:

 [id]  [columnA]   [columnB]
  2     "data"    "more data"    
  3     "data"    "more data"    
  4     "data"    "more data"    
  7     "data"    "more data"
  8     "data"    "more data"
  11    "data"    "more data"

There might be a 1000+ values in the table.

Let's say I want to select the row containing the first odd numbered id in that table. In this case it should return the row 3 "data" "more data".

Also how would I select the first even numbered id?

Thanks very much

user2503552
  • 601
  • 2
  • 8
  • 14

2 Answers2

3
select id
from table
where MOD(id, 2) = 1
order by id
limit 0, 1

Use mathematical function 13 % 2 = 1 (sorry, i don't know how is it in english, devide by modulo). MySQL function is MOD

Maxim Zhukov
  • 10,060
  • 5
  • 44
  • 88
3

This will give you all the rows having even id.

SELECT ID FROM table WHERE MOD(ID,2) = 0

And then on this result you can use

SELECT TOP 1 *
FROM myTable
ORDER BY ID

And for odd you can use

SELECT ID FROM table WHERE MOD(ID,2) = 1

If you are using SQL Server use TOP if you are using MySQL or Postgres use Limit!

Coffee_lover
  • 545
  • 6
  • 15