---
title: "Rails 6.1 supports ORDER BY clause for batch processing methods"
description:
  "Rails 6.1 supports order DESC for find_each, find_in_batches, and in_batches"
canonical_url: "https://www.bigbinary.com/blog/rails-6-1-supports-order-desc-for-find_each-find_in_batches-and-in_batches"
markdown_url: "https://www.bigbinary.com/blog/rails-6-1-supports-order-desc-for-find_each-find_in_batches-and-in_batches.md"
---

# Rails 6.1 supports ORDER BY clause for batch processing methods

Rails 6.1 supports order DESC for find_each, find_in_batches, and in_batches

- Author: Sagar Patil
- Published: October 22, 2020
- Categories: Rails 6.1, Rails

Before Rails 6.1, batch processing methods like _find_each_, _find_in_batches_
and _in_batches_ didn't support the _ORDER BY_ clause. By default the order was
set to _id ASC_.

```ruby
> User.find_each{|user| puts user.inspect}

User Load (0.4ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ?  [["LIMIT", 1000]]
```

Rails 6.1 now supports _ORDER BY id_ for ActiveRecord batch processing methods
like _find_each_, _find_in_batches_, and _in_batches_. This would allow us to
retrieve the records in ascending or descending order of _ID_.

```ruby
> User.find_each(order: :desc){|user| puts user.inspect}

User Load (0.4ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT ?  [["LIMIT", 1000]]
```

```ruby
> User.find_in_batches(order: :desc) do |users|
>   users.each do |user|
>     puts user.inspect
>   end
> end

User Load (0.3ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT ?  [["LIMIT", 1000]]
```

```ruby
> User.in_batches(order: :desc) do |users|
>   users.each do |user|
>     puts user.inspect
>   end
> end

(0.2ms)  SELECT "users"."id" FROM "users" ORDER BY "users"."id" DESC LIMIT ?  [["LIMIT", 1000]]
User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ?  [["id", 101]]
```

Points to remember:

- The _ORDER BY_ clause only works with the primary key column.
- Valid values for the _ORDER BY_ clause are _[:asc,:desc]_ and it's case
  sensitive. If we use caps or title case (like _DESC_ or _Asc_) then we'll get
  an _ArgumentError_ as shown below.

```ruby
> User.find_in_batches(order: :DESC) do |users|
>   users.each do |user|
>     puts user.inspect
>   end
> end

Traceback (most recent call last):
        2: from (irb):5
        1: from (irb):6:in `rescue in irb_binding'
ArgumentError (unknown keyword: :order)
```

Check out the [pull request](https://github.com/rails/rails/pull/30590) for more
details.

## Links

- [Human page](https://www.bigbinary.com/blog/rails-6-1-supports-order-desc-for-find_each-find_in_batches-and-in_batches)
