147

I would like to see the SQL statement that a given ActiveRecord Query will generate. I recognize I can get this information from the log after the query has been issued, but I'm wondering if there is a method that can be called on and ActiveRecord Query.

For example:

SampleModel.find(:all, :select => "DISTINCT(*)", :conditions => ["`date` > #{self.date}"], :limit => 1, :order => '`date`', :group => "`date`")

I would like to open the irb console and tack a method on the end that would show the SQL that this query will generate, but not necessarily execute the query.

12 Answers 12

202

Similar to penger's, but works anytime in the console even after classes have been loaded and the logger has been cached:

For Rails 2:

ActiveRecord::Base.connection.instance_variable_set :@logger, Logger.new(STDOUT)

For Rails 3.0.x:

ActiveRecord::Base.logger = Logger.new(STDOUT)

For Rails >= 3.1.0 this is already done by default in consoles. In case it's too noisy and you want to turn it off you can do:

ActiveRecord::Base.logger = nil
5
  • This isn't working for me in rails console. Does it work only for irb loaded directly from the shell? (or was it removed for rails 3?)
    – Eric Hu
    Commented Mar 23, 2011 at 19:34
  • 2
    They moved it to a more sensible place for Rails 3... see my updated version.
    – gtd
    Commented Apr 7, 2011 at 3:08
  • Is there any way to do this automatically every time I start the console? Something like a before load hook?
    – stream7
    Commented Jul 6, 2011 at 7:20
  • 1
    @stream7..I dont know if u need this now, but you can move this code to environment.rb..if "irb" == $0;ActiveRecord::Base.logger = Logger.new(STDOUT);end..got this from comments in http://weblog.jamisbuck.org/2007/1/8/watching-activerecord-do-it-s-thing
    – rubyprince
    Commented Oct 24, 2011 at 8:45
  • 2
    This doesn't answer the question: how to show the sql for a particular query while debugging without running the query.
    – bradw2k
    Commented Sep 30, 2016 at 16:47
111

Stick a puts query_object.class somewhere to see what type of object your working with, then lookup the docs.

For example, in Rails 3.0, scopes use ActiveRecord::Relation which has a #to_sql method. For example:

class Contact < ActiveRecord::Base
  scope :frequently_contacted, where('messages_count > 10000')
end

Then, somewhere you can do:

puts Contact.frequently_contacted.to_sql
4
  • 3
    Why is this answer not upvoted? For Rails 3 it's a way better answer - you can get the results of any AR::Relation statement just by putting ".to_sql" at the end. This question also provides that answer: stackoverflow.com/questions/3814738/… Commented Sep 17, 2014 at 5:03
  • 5
    Beware: you won't get all the SQL if you have an includes in your relation Commented Jan 23, 2015 at 18:25
  • 3
    @BarryKelly Why is that? Commented May 17, 2016 at 7:27
  • @VishnuNarang I believe it's because includes requires multiple queries. Commented Sep 7, 2021 at 19:52
45

just use to_sql method and it'll output the sql query that will be run. it works on an active record relation.

irb(main):033:0> User.limit(10).where(:username => 'banana').to_sql
=> "SELECT  "users".* FROM "users"  WHERE "users"."username" = 'banana'
LIMIT 10"

when doing find, it won't work, so you'll need to add that id manually to the query or run it using where.

irb(main):037:0* User.where(id: 1).to_sql
=> "SELECT "users".* FROM "users"  WHERE "users"."id" = 1"
28

This may be an old question but I use:

SampleModel.find(:all,
                 :select => "DISTINCT(*)",
                 :conditions => ["`date` > #{self.date}"], 
                 :limit=> 1, 
                 :order => '`date`',
                 :group => "`date`"
                 ).explain

The explain method will give quite a detailed SQL statement on what its going to do

1
  • 7
    It'll also run the query, which might not be what people want, just for the record.
    – Ibrahim
    Commented Aug 24, 2016 at 16:48
13

This is what I usually do to get SQL generated in console

-> script/console
Loading development environment (Rails 2.1.2)
>> ActiveRecord::Base.logger = Logger.new STDOUT
>> Event.first

You have to do this when you first start the console, if you do this after you have typed some code, it doesn't seem to work

Can't really take credit for this, found it long time ago from someone's blog and can't remember whose it is.

3
  • 1
    I'm pretty sure it was Jamis Buck's blog: weblog.jamisbuck.org/2007/1/8/…
    – rswolff
    Commented Aug 28, 2009 at 17:03
  • 1
    I'm not sure if it's due to Rails 2.3 or something in my environment, but this doesn't work for me. See my response below.
    – gtd
    Commented Oct 16, 2009 at 5:23
  • This is a great solution IMO. Commented Jul 15, 2014 at 4:54
11

When last I tried to do this there was no official way to do it. I resorted to using the function that find and its friends use to generate their queries directly. It is private API so there is a huge risk that Rails 3 will totally break it, but for debugging, it is an ok solution.

The method is construct_finder_sql(options) (lib/active_record/base.rb:1681) you will have to use send because it is private.

Edit: construct_finder_sql was removed in Rails 5.1.0.beta1.

3
  • 1
    This is close to what I'm thinking. I guess a person could write a plugin that would do something like: SampleModel.find(:all, :select => "DISTINCT(*)", :conditions => ["date > #{self.date}"], :limit => 1, :order => 'date', :group => "date").show_generated_sql and have this call the construct_finder_sql method.
    – rswolff
    Commented Aug 28, 2009 at 17:02
  • 1
    With DataMapper you could because it doesn't run the query right away. ActiveRecord on the other hand executes the query immediately. show_generated_sql will be acting on an already retrieved dataset from find. Commented Aug 28, 2009 at 20:55
  • 4
    In Rails 3 construct_finder_sql is indeed removed
    – Veger
    Commented Dec 26, 2011 at 14:21
10

Create a .irbrc file in your home directory and paste this in:

if ENV.include?('RAILS_ENV') && !Object.const_defined?('RAILS_DEFAULT_LOGGER')
  require 'logger'
  RAILS_DEFAULT_LOGGER = Logger.new(STDOUT)
end

That will output SQL statements into your irb session as you go.

EDIT: Sorry that will execute the query still, but it's closest I know of.

EDIT: Now with arel, you can build up scopes/methods as long as the object returns ActiveRecord::Relation and call .to_sql on it and it will out put the sql that is going to be executed.

1
  • This is what I've been doing, but I'm more interested in simply seeing the projected SQL the ActiveRecord query will generate. I'm surprised there's no simple way to do this...
    – rswolff
    Commented Aug 28, 2009 at 16:59
6

My typical way to see what sql it uses is to introduce a "bug" in the sql, then you'll get an error messages spit out to the normal logger (and web screen) that has the sql in question. No need to find where stdout is going...

1
  • 2
    Spectacular but quickest solution :) Commented Aug 9, 2018 at 11:54
3

You can simply use to_sql() function with the active record

Form.where(status:"Active").to_sql
2

Try the show_sql plugin. The plugin enables you to print the SQL without running it

SampleModel.sql(:select => "DISTINCT(*)", :conditions => ["`date` > #{self.date}"], :limit => 1, :order => '`date`', :group => "`date`")
1
  • 1
    Looks like that the link got broken (404 error). Probably, Ryan Bigg deleted the plugin.
    – DNNX
    Commented Jan 25, 2012 at 20:45
1

You could change the connection's log method to raise an exception, preventing the query from being run.

It's a total hack, but it seems to work for me (Rails 2.2.2, MySQL):

module ActiveRecord
  module ConnectionAdapters
    class AbstractAdapter
      def log_with_raise(sql, name, &block)
        puts sql
        raise 'aborting select' if caller.any? { |l| l =~ /`select'/ }
        log_without_raise(sql, name, &block)
      end
      alias_method_chain :log, :raise
    end
  end
end
0

In Rails 3 you can add this line to the config/environments/development.rb

config.active_record.logger = Logger.new(STDOUT)

It will however execute the query. But half got answered :

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.