Always specify an order when using 'limit'
SQL’s limit
function retrieves the first records from a dataset (often a table).
This leaves it up to the user to specify additional conditions to ensure that the dataset is correct for using limit.
Many ActiveRecord query helpers (e.g., first
and last
) add a default order of ID ascending.
This is important because rows in a database table are not guaranteed to be in chronological order.
Let’s use ActiveRecord’s first
to see our oldest ten account records:
Account.first(10)
SELECT "accounts".* FROM "accounts" ORDER BY "accounts"."id" ASC LIMIT $1 [["LIMIT", 10]]
[#<Account id: 1>,
#<Account id: 7>,
#<Account id: 78>,
#<Account id: 158>,
#<Account id: 256>,
#<Account id: 512>,
#<Account id: 768>,
#<Account id: 1024>,
#<Account id: 1280>,
#<Account id: 1536>]
Account.first(10)
is functionally equivalent to Account.order(id: :asc).limit(10)
.
To see why specifying an order is important, let’s try limit
without order
:
Account.limit(10)
SELECT "accounts".* FROM "accounts" LIMIT $1 [["LIMIT", 10]]
[#<Account id: 1>,
#<Account id: 7>,
#<Account id: 78>,
#<Account id: 158>,
#<Account id: 256>,
#<Account id: 512>,
#<Account id: 1024>,
#<Account id: 1280>,
#<Account id: 1536>,
#<Account id: 1792>]
Account 768 is missing! If order is important, it must be specified.