> 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/query-a-single-value-from-the-database.md).

# Query A Single Value From The Database

In a Rails context, most database interactions tend to happen through the ORM (e.g. `Book.find("123")`). There is a general purpose escape hatch that lets you execute a SQL statement directly against the DB -- `execute`. The resulting value of `execute`, however, tends to be a little clunky to work with.

If you just need a single value from the DB, use the [`select_value`](https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-select_value) method.

```ruby
> statement = "select gen_random_uuid()"
> ActiveRecord::Base.connection.select_value(statement)
   (5.0ms)  select gen_random_uuid()
 => "abc2e780-f442-418b-afa3-56f0ccd0a903"
```

This is the cleanest way to get the result of a "single value" query.

If you happen to pass in a query that results in more than one row or column, it will return the value of the first column from the first row.


---

# 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/query-a-single-value-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.
