Bratish Goswami

Personal website and blog

How to See MySQL Queries in Rails Console

When debugging a Rails application, I often want to see the SQL behind a query. The Rails console doesn't show those database queries by default.

Here's how to enable SQL logging in Rails console:

Method 1: Enable for current session

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

Now when you run queries, you'll see the SQL:

User.find(1)
# User Load (0.3ms)  SELECT * FROM `users` WHERE `users`.`id` = 1 LIMIT 1

Method 2: For Rails 3+ with colored output

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

Method 3: Make it permanent

Add this to your ~/.irbrc file:

if defined?(Rails) && Rails.env
  ActiveRecord::Base.logger = Logger.new(STDOUT)
  ActiveRecord::Base.colorize_logging = true
end

Method 4: One-liner in console

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

Method 5: Enable for specific queries only

# Temporarily enable logging
old_logger = ActiveRecord::Base.logger
ActiveRecord::Base.logger = Logger.new(STDOUT)
User.find(1)  # This will show SQL
ActiveRecord::Base.logger = old_logger  # Restore

Method 6: Using Rails.logger instead

ActiveRecord::Base.logger = Rails.logger

Method 7: Custom logger with different levels

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

SQL logging helps with these tasks:

  • Debug slow queries
  • Understand what ActiveRecord is actually doing
  • Optimize your database calls
  • Learn SQL by seeing what Rails generates

Colored output helps distinguish the SQL queries from the rest of the console output.