# How to run direct sql

**URL:** <https://www.ruby-forum.com/t/how-to-run-direct-sql/52627>\
**Category:** Rails\
**Created:** [January 17, 2006, 5:02am UTC](https://www.ruby-forum.com/t/how-to-run-direct-sql/52627 "2006-01-17T05:02:03Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [January 17, 2006, 5:02am UTC](https://www.ruby-forum.com/t/how-to-run-direct-sql/52627/1 "2006-01-17T05:02:03Z")

</div>

How can i run and get the value from the following sql:

select avg(my\_field) from my\_table where which\_year=‘0506’ and  
which\_week \<= 21 and my\_foreign\_key\_id=10

cheers

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [January 17, 2006, 6:29am UTC](https://www.ruby-forum.com/t/how-to-run-direct-sql/52627/2 "2006-01-17T06:29:47Z")

</div>

thanks!

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [January 17, 2006, 5:23am UTC](https://www.ruby-forum.com/t/how-to-run-direct-sql/52627/3 "2006-01-17T05:23:01Z")

</div>

On 1/16/06, chris hulbert [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> How can i run and get the value from the following sql:
> 
> select avg(my\_field) from my\_table where which\_year=‘0506’ and  
> which\_week \<= 21 and my\_foreign\_key\_id=10

You can use:  
YourModel.connection.select\_value(your\_query\_string)  
…which returns the result as a string that you will need to type\_cast  
into whatever you need.

If you find yourself doing a lot of this, you should look at the cool  
Calculations plugin:  
[http://techno-weenie.net/svn/projects/plugins/calculations/](http://techno-weenie.net/svn/projects/plugins/calculations/)
