> For the complete documentation index, see [llms.txt](https://ploegert.gitbook.io/til/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ploegert.gitbook.io/til/programmy/rails/grab-a-random-record-from-the-database.md).

# Grab A Random Record From The Database

I recently learned of a clever way to grab a random record for a particular model from the database. This is handy if you are poking around in the database to see what some records look like.

Order the records for that table randomly and then grab the first.

```ruby
Event.order('random()').first
```

This grabs a random `Event` record from the `events` table.

Note, however, that for Rails 6+, this approach won't work. Because of some extra safety measures around executing raw SQL, you'll instead have to write the above as:

```ruby
Event.order( Arel.sql('random()') ).first
```

This uses [`Arel.sql`](https://api.rubyonrails.org/classes/Arel.html#method-c-sql) to mark `'random()'` as a known-safe string of SQL.

Because we are explicitly passing a string that represents a known-safe function call, this is fine. Take care to not pass any user-generated SQL in a scenario like this unless you know what you're doing.

[source](https://stackoverflow.com/a/49525874/535590)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ploegert.gitbook.io/til/programmy/rails/grab-a-random-record-from-the-database.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
