##TIL ๐ฌ๐ง
How to write Active record queries for multiple OR conditions on the same column ?
Jeanro Krupa
Jeanro Krupa
1 min read
Today I was wondering how to optimize this query that was not elegant:
MyModel.where.("column = ? OR colum = ? OR colum = ?", :value_1, :value_2, :value_3)
The SQL is:
SELECT "my_models".* FROM "my_models" WHERE (column = 'value_1' OR column = 'value_2' OR column = 'value_3')
You can change your query by using
IN
instead of OR
:MyModel.where(column: [:value_1, :value_2, :value_3])
The SQL is:
SELECT "my_models".* FROM "my_models" WHERE "my_models"."column" IN ('value_1', 'value_2', 'value_3')
Regarding performance it seems to be roughly the same depending on the DB you are using: cf stackoverflow thread