Rails SQL query counts results when not asked

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 .....

``

The code you posted above doesn’t actually run any query - queries are executed lazily. What are you doing with @new_relationships?

Fred

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.

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.

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

Colin

Indeed. At least the misery of fixing this problem has given me a deeper understanding of Rails!

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