# How to get results from database SQL query

**URL:** <https://www.ruby-forum.com/t/how-to-get-results-from-database-sql-query/153542>\
**Category:** Rails\
**Created:** [November 18, 2008, 4:23pm UTC](https://www.ruby-forum.com/t/how-to-get-results-from-database-sql-query/153542 "2008-11-18T16:23:10Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![yan-oleg](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/y/a3d4f5/32.png) [@yan-oleg](https://www.ruby-forum.com/u/yan-oleg)\
**Post date:** [November 18, 2008, 4:23pm UTC](https://www.ruby-forum.com/t/how-to-get-results-from-database-sql-query/153542/1 "2008-11-18T16:23:10Z")

</div>

I need to get results from SQL query to database.

I have an SQL statement, e.g.: SELECT MAX(my\_field) max\_my\_field FROM  
my\_table WHERE id=5

I want to get the result, what is the max value. I have to get only one  
record with a number, or null if no records found. Please provide Ruby  
code to do this? (to store results in variable)

---

<div class="post-metadata">

**Author:** ![yan-oleg](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/y/a3d4f5/32.png) [@yan-oleg](https://www.ruby-forum.com/u/yan-oleg)\
**Post date:** [November 18, 2008, 5:03pm UTC](https://www.ruby-forum.com/t/how-to-get-results-from-database-sql-query/153542/2 "2008-11-18T17:03:20Z")

</div>

On Nov 18, 3:23 pm, Yan O. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> I need to get results from SQL query to database.
> 
> I have an SQL statement, e.g.: SELECT MAX(my\_field) max\_my\_field FROM  
> my\_table WHERE id=5
> 
> I want to get the result, what is the max value. I have to get only one  
> record with a number, or null if no records found. Please provide Ruby  
> code to do this? (to store results in variable)

Checkout the maximum method ([Peak Obsession](http://api.rubyonrails.com/classes/)  
ActiveRecord/Calculations/ClassMethods.html#M001659)

Fred
