# Optimizing OR Queries in Rails and MySQL

**URL:** <https://www.ruby-forum.com/t/optimizing-or-queries-in-rails-and-mysql/166956>\
**Category:** Rails\
**Created:** [May 1, 2009, 12:14pm UTC](https://www.ruby-forum.com/t/optimizing-or-queries-in-rails-and-mysql/166956 "2009-05-01T12:14:59Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Moodang](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/c4cdca/32.png) [@Moodang](https://www.ruby-forum.com/u/Moodang)\
**Post date:** [May 1, 2009, 12:14pm UTC](https://www.ruby-forum.com/t/optimizing-or-queries-in-rails-and-mysql/166956/1 "2009-05-01T12:14:59Z")

</div>

According to MySQL doc, I must use union and temporary tables.

It seems I have to do something along the line of this:

[http://www.ricroberts.com/articles/2007/09/25/mysql-temporary-tables-and-rails](http://www.ricroberts.com/articles/2007/09/25/mysql-temporary-tables-and-rails)

There are cases where I use OR queries quite often. I am talking about  
queries like this “where column\_1 = 123 OR column\_2 = 123”. It seems  
MySQL indices cannot properly optimize this.

Are there plugins or snippets out there that automagically hide the  
complexity of using temporary tables for such queries?

---

<div class="post-metadata">

**Author:** ![Moodang](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/c4cdca/32.png) [@Moodang](https://www.ruby-forum.com/u/Moodang)\
**Post date:** [May 1, 2009, 12:16pm UTC](https://www.ruby-forum.com/t/optimizing-or-queries-in-rails-and-mysql/166956/2 "2009-05-01T12:16:10Z")

</div>

On May 1, 10:38 am, Moodang [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> According to MySQL doc, I must use union and temporary tables.
> 
> It seems I have to do something along the line of this:
> 
> [ricroberts.com](http://www.ricroberts.com/articles/2007/09/25/mysql-temporary-tables-)…
> 
> There are cases where I use OR queries quite often. I am talking about  
> queries like this “where column\_1 = 123 OR column\_2 = 123”. It seems  
> MySQL indices cannot properly optimize this.

I don’t think that’s quite true - on mysql5 it should be able to do an  
index merge:  
[http://dev.mysql.com/doc/refman/5.0/en/index-merge-optimization.html](http://dev.mysql.com/doc/refman/5.0/en/index-merge-optimization.html)

Fred
