# How to create a SQL query without ActiveRecord?

**URL:** <https://discuss.rubyonrails.org/t/how-to-create-a-sql-query-without-activerecord/4745>\
**Category:** rubyonrails-talk\
**Created:** [November 19, 2006, 12:44pm UTC](https://discuss.rubyonrails.org/t/how-to-create-a-sql-query-without-activerecord/4745 "2006-11-19T12:44:22Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![blacknight](https://avatars.discourse-cdn.com/v4/letter/b/c68b51/32.png) [@blacknight](https://discuss.rubyonrails.org/u/blacknight)\
**Post date:** [November 19, 2006, 12:44pm UTC](https://discuss.rubyonrails.org/t/how-to-create-a-sql-query-without-activerecord/4745/1 "2006-11-19T12:44:22Z")

</div>

I want to write an independent (not model-related) SQL query for some statistic information in an online shop system. So I know I could grab all users with ActiveRecord and then just count the array size, but that would massively waste resources. And I also want MySQL to do some max, min and average calculations. So is there a way to issue a query and get the result set without models being involved?

---

<div class="post-metadata">

**Author:** ![bphogan](https://sea2.discourse-cdn.com/rubyonrails/user_avatar/discuss.rubyonrails.org/bphogan/32/4186_2.png) [@bphogan](https://discuss.rubyonrails.org/u/bphogan)\
**Post date:** [November 20, 2006, 1:56pm UTC](https://discuss.rubyonrails.org/t/how-to-create-a-sql-query-without-activerecord/4745/2 "2006-11-20T13:56:59Z")

</div>

First of all, there are calculations available with ActiveRecord.

```ruby
Person.count
  Person.count(:conditions => "age > 26")
  Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job) # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN.

  Person.count(:conditions => "age > 26 AND job.salary > 60000", :joins => "LEFT JOIN jobs on jobs.person_id = [person.id](http://person.id)") # finds the number of rows matching the conditions and joins.

  Person.count('id', :conditions => "age > 26") # Performs a COUNT(id)
  Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*

```

Or you can do Person.find\_by\_sql(“select first\_name from people where age \> 26”)

Retrieving the results is a little more interesting but not that bad. Search the API, there are lots of good things in there.

See [http://api.rubyonrails.com/classes/ActiveRecord/Calculations/ClassMethods.html](http://api.rubyonrails.com/classes/ActiveRecord/Calculations/ClassMethods.html) on calulations
