Rails SQL query counts results when not asked

12 views
Skip to first unread message

Bazley

unread,
Aug 24, 2016, 8:11:42 AM8/24/16
to Ruby on Rails: Talk
This rails/sql code...

    @new_relationships = User.select('*')
                             
.from("(#{@rels_unordered.to_sql}) AS rels_unordered")
                             
.joins("
                        INNER JOIN  relationships
                        ON          rels_unordered.id = relationships.character_id
                        ORDER BY    relationships.created_at DESC
                        "
)

produces a query that begins like this:

    SELECT COUNT(*) FROM (SELECT .....

Why is it counting the records?? I haven't asked for a count. I simply want to select all columns after the join:

    SELECT * FROM (SELECT .....

Frederick Cheung

unread,
Aug 24, 2016, 8:26:54 AM8/24/16
to Ruby on Rails: Talk
The code you posted above doesn't actually run any query - queries are executed lazily. What are you doing with @new_relationships? 

Fred 
Message has been deleted
Message has been deleted

Bazley

unread,
Aug 24, 2016, 8:49:48 AM8/24/16
to Ruby on Rails: Talk
The first thing I do with it is this:

if @new_relationships.any?

So it looks like .any? affects the query? I would have thought rails would perform the query, get all the records into @new_relationships, and then count them. This is a surprising feature.

Colin Law

unread,
Aug 24, 2016, 4:34:20 PM8/24/16
to Ruby on Rails: Talk

Surprising possibly, but it saved a lot of processor time. Such is the magic of rails.

Colin

> --
> You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-ta...@googlegroups.com.
> To post to this group, send email to rubyonra...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/41ec5676-836d-4079-b48c-b28b49a5326d%40googlegroups.com.
>
> For more options, visit https://groups.google.com/d/optout.

Bazley

unread,
Aug 25, 2016, 11:25:01 AM8/25/16
to Ruby on Rails: Talk
Indeed. At least the misery of fixing this problem has given me a deeper understanding of Rails!

Frederick Cheung

unread,
Aug 25, 2016, 12:47:25 PM8/25/16
to Ruby on Rails: Talk
What rails is trying to avoid is loading 1000 objects from the db, just to check whether there is > 0 objects. If the query had already run, then it would just could the loaded objects. 

Fred
Reply all
Reply to author
Forward
0 new messages