Sunday, November 7, 2010

Select Odd Rows in MySQL

Any time you can use a bitwise operator in place of a function call, it's a good thing. Selecting odd rows from a table in MySQL that have an auto_increment primary key is no exception.

SELECT * FROM mytable WHERE id & 1;


If you're unfamiliar with a bitwise AND, basically what it says is return true of the left operand has the same bits set as the right operand. The number 1 only has one bit set, and conveniently enough that one bit is the same bit that will only be present in odd numbers.

2 comments:

Anonymous said...

What about even?

Stanislav said...

And what about a situation when you have deleted some rows and have id=2, id=4 etc.?