# Querying children optimized sql?

**URL:** <https://www.ruby-forum.com/t/querying-children-optimized-sql/82447>\
**Category:** Rails\
**Created:** [January 19, 2007, 4:30pm UTC](https://www.ruby-forum.com/t/querying-children-optimized-sql/82447 "2007-01-19T16:30:28Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![bataras](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/3ab097/32.png) [@bataras](https://www.ruby-forum.com/u/bataras)\
**Post date:** [January 19, 2007, 4:30pm UTC](https://www.ruby-forum.com/t/querying-children-optimized-sql/82447/1 "2007-01-19T16:30:28Z")

</div>

Re-asking…

I have a parent with has\_many children. The children have a column  
‘blah’. IF I do the following:

```
parent.children.find_by_blah(42)

```

The sql exectued is:

```
select * from blah where parent_id = 1 and blah = 42
select * from blah where parent_id = 1

```

The first line of sql is what I want. The second appears to be  
ActiveRecord loading up all of parent.children. This I don’t want b/c  
children is huge.

How to I use ActiveRecord to find the children “by\_blah” without  
causing ALL children to be selected from the DB?

thanks

---

<div class="post-metadata">

**Author:** ![bataras](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/3ab097/32.png) [@bataras](https://www.ruby-forum.com/u/bataras)\
**Post date:** [January 19, 2007, 4:31pm UTC](https://www.ruby-forum.com/t/querying-children-optimized-sql/82447/2 "2007-01-19T16:31:19Z")

</div>

bataras wrote:

> ```
> parent.children.find_by_blah(42)
> 
> ```
> 
> The sql exectued is:
> 
> ```
> select * from blah where parent_id = 1 and blah = 42
> select * from blah where parent_id = 1
> 
> ```
> 
> The first line of sql is what I want. The second appears to be  
> ActiveRecord loading up all of parent.children. This I don’t want b/c  
> children is huge.

Somewhere later you must be referring to the naked parent.children  
collection, just like in your earlier problem

[http://groups.google.com/group/rubyonrails-talk/browse\_thread/thread/d741810f309336a3/594abd2765f61201](http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/d741810f309336a3/594abd2765f61201)

–  
We develop, watch us RoR, in numbers too big to ignore.

---

<div class="post-metadata">

**Author:** ![bataras](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/3ab097/32.png) [@bataras](https://www.ruby-forum.com/u/bataras)\
**Post date:** [January 19, 2007, 4:31pm UTC](https://www.ruby-forum.com/t/querying-children-optimized-sql/82447/3 "2007-01-19T16:31:24Z")

</div>

No i just want to use idiomatic rails to cause

select \* from blah where parent\_id = 1 and blah = 42

without causing rails to also do a presumptive

select \* from blah where parent\_id = 1

Instead of using parent.children.find\_by\_blah(42), should I just just  
do Child.find(:all, :condition =\> ['parent = ? and blah = ?",  
parent.id, 42] ?

Kind of funky to me.
