I am trying to process records in my database like so:
rows = MyModel.joins("JOIN other_model ON other_model.my_model_id = my_model.id")
.joins("JOIN <some other join>")
.where("<conditions>")
rows.find_each(batch_size: 50, &:destroy)
I am not specifying any row order, so I expect that there won't be any ORDER BY clause in the final SQL. However, when I run this code, ActiveRecord adds an ORDER BY clause; the query actually looks like this:
... WHERE <conditions> ORDER BY "my_model"."id" ASC LIMIT 50;
This is a problem as I have many records in the table, and ORDER BY clause slows everything down.
I could probably rewrite my code so as to not use ActiveRecord to select the ids, but I'm wondering why ActiveRecord behaves like this. Why does it add an ORDER By when I'm not asking it to? Is there any way to prevent this?