How do I select the first odd/even numbered primary key in a SQL database

user2503552 picture user2503552 · Jul 24, 2013 · Viewed 7.4k times · Source

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

Answer

Maxim Zhukov picture Maxim Zhukov · Jul 24, 2013
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