### Home Classes Methods

### In Files

- lib/active_record/querying.rb

### Methods

- #count_by_sql
- #find_by_sql

### Files

- README.rdoc

### Class/Module Index

Quicksearch

- ActiveRecord
- ActiveRecord::ActiveRecordError
- ActiveRecord::AdapterNotFound
- ActiveRecord::AdapterNotSpecified
- ActiveRecord::Aggregations
- ActiveRecord::Aggregations::ClassMethods
- ActiveRecord::AssociationTypeMismatch
- ActiveRecord::Associations
- ActiveRecord::Associations::ClassMethods
- ActiveRecord::AttributeAssignment
- ActiveRecord::AttributeAssignment::ClassMethods
- ActiveRecord::AttributeAssignmentError
- ActiveRecord::AttributeMethods
- ActiveRecord::AttributeMethods::BeforeTypeCast
- ActiveRecord::AttributeMethods::ClassMethods
- ActiveRecord::AttributeMethods::DeprecatedUnderscoreRead
- ActiveRecord::AttributeMethods::DeprecatedUnderscoreRead::ClassMethods
- ActiveRecord::AttributeMethods::Dirty
- ActiveRecord::AttributeMethods::PrimaryKey
- ActiveRecord::AttributeMethods::PrimaryKey::ClassMethods
- ActiveRecord::AttributeMethods::Query
- ActiveRecord::AttributeMethods::Read
- ActiveRecord::AttributeMethods::Read::ClassMethods
- ActiveRecord::AttributeMethods::Serialization
- ActiveRecord::AttributeMethods::Serialization::Attribute
- ActiveRecord::AttributeMethods::Serialization::ClassMethods
- ActiveRecord::AttributeMethods::TimeZoneConversion
- ActiveRecord::AttributeMethods::TimeZoneConversion::ClassMethods
- ActiveRecord::AttributeMethods::Write
- ActiveRecord::AttributeMethods::Write::ClassMethods
- ActiveRecord::AutosaveAssociation
- ActiveRecord::AutosaveAssociation::ClassMethods
- ActiveRecord::Base
- ActiveRecord::Batches
- ActiveRecord::Calculations
- ActiveRecord::Callbacks
- ActiveRecord::Coders
- ActiveRecord::ConfigurationError
- ActiveRecord::ConnectionAdapters
- ActiveRecord::ConnectionAdapters::AbstractAdapter
- ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter
- ActiveRecord::ConnectionAdapters::ConnectionHandler
- ActiveRecord::ConnectionAdapters::ConnectionManagement
- ActiveRecord::ConnectionAdapters::ConnectionPool
- ActiveRecord::ConnectionAdapters::DatabaseLimits
- ActiveRecord::ConnectionAdapters::DatabaseStatements
- ActiveRecord::ConnectionAdapters::Mysql2Adapter
- ActiveRecord::ConnectionAdapters::MysqlAdapter
- ActiveRecord::ConnectionAdapters::MysqlAdapter::StatementPool
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::StatementPool
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::TableDefinition
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::Utils
- ActiveRecord::ConnectionAdapters::PostgreSQLColumn
- ActiveRecord::ConnectionAdapters::QueryCache
- ActiveRecord::ConnectionAdapters::Quoting
- ActiveRecord::ConnectionAdapters::SQLiteAdapter
- ActiveRecord::ConnectionAdapters::SQLiteAdapter::ExplainPrettyPrinter
- ActiveRecord::ConnectionAdapters::SQLiteAdapter::StatementPool
- ActiveRecord::ConnectionAdapters::SQLiteAdapter::Version
- ActiveRecord::ConnectionAdapters::SchemaCache
- ActiveRecord::ConnectionAdapters::SchemaStatements
- ActiveRecord::ConnectionAdapters::StatementPool
- ActiveRecord::ConnectionAdapters::Table
- ActiveRecord::ConnectionAdapters::TableDefinition
- ActiveRecord::ConnectionNotEstablished
- ActiveRecord::ConnectionTimeoutError
- ActiveRecord::CounterCache
- ActiveRecord::DangerousAttributeError
- ActiveRecord::Delegation
- ActiveRecord::DynamicFinderMatch
- ActiveRecord::DynamicMatchers
- ActiveRecord::DynamicScopeMatch
- ActiveRecord::Explain
- ActiveRecord::FinderMethods
- ActiveRecord::Fixtures
- ActiveRecord::Fixtures::File
- ActiveRecord::Generators
- ActiveRecord::Generators::Migration
- ActiveRecord::Generators::MigrationGenerator
- ActiveRecord::Generators::ModelGenerator
- ActiveRecord::Generators::ObserverGenerator
- ActiveRecord::Generators::SessionMigrationGenerator
- ActiveRecord::IdentityMap
- ActiveRecord::IdentityMap::Middleware
- ActiveRecord::Inheritance
- ActiveRecord::Inheritance::ClassMethods
- ActiveRecord::Integration
- ActiveRecord::InvalidForeignKey
- ActiveRecord::IrreversibleMigration
- ActiveRecord::Locking
- ActiveRecord::Locking::Optimistic
- ActiveRecord::Locking::Optimistic::ClassMethods
- ActiveRecord::Locking::Pessimistic
- ActiveRecord::LogSubscriber
- ActiveRecord::Migration
- ActiveRecord::Migration::CommandRecorder
- ActiveRecord::MigrationProxy
- ActiveRecord::ModelSchema
- ActiveRecord::ModelSchema::ClassMethods
- ActiveRecord::MultiparameterAssignmentErrors
- ActiveRecord::NestedAttributes
- ActiveRecord::NestedAttributes::ClassMethods
- ActiveRecord::NestedAttributes::TooManyRecords
- ActiveRecord::Observer
- ActiveRecord::Persistence
- ActiveRecord::Persistence::ClassMethods
- ActiveRecord::PreparedStatementInvalid
- ActiveRecord::QueryCache
- ActiveRecord::QueryCache::ClassMethods
- ActiveRecord::QueryMethods
- ActiveRecord::Querying
- ActiveRecord::Railtie
- ActiveRecord::Railties
- ActiveRecord::Railties::ControllerRuntime
- ActiveRecord::Railties::ControllerRuntime::ClassMethods
- ActiveRecord::ReadOnlyRecord
- ActiveRecord::ReadonlyAttributes
- ActiveRecord::ReadonlyAttributes::ClassMethods
- ActiveRecord::RecordInvalid
- ActiveRecord::RecordNotFound
- ActiveRecord::RecordNotSaved
- ActiveRecord::RecordNotUnique
- ActiveRecord::Reflection
- ActiveRecord::Reflection::ClassMethods
- ActiveRecord::Reflection::MacroReflection
- ActiveRecord::Result
- ActiveRecord::Rollback
- ActiveRecord::Sanitization
- ActiveRecord::Sanitization::ClassMethods
- ActiveRecord::Schema
- ActiveRecord::Scoping
- ActiveRecord::Scoping::ClassMethods
- ActiveRecord::Scoping::Default
- ActiveRecord::Scoping::Default::ClassMethods
- ActiveRecord::Scoping::Named
- ActiveRecord::Scoping::Named::ClassMethods
- ActiveRecord::Serialization
- ActiveRecord::SerializationTypeMismatch
- ActiveRecord::SessionStore
- ActiveRecord::SessionStore::Session
- ActiveRecord::SessionStore::SqlBypass
- ActiveRecord::SpawnMethods
- ActiveRecord::StaleObjectError
- ActiveRecord::StatementInvalid
- ActiveRecord::Store
- ActiveRecord::Store::ClassMethods
- ActiveRecord::TestFixtures
- ActiveRecord::TestFixtures::ClassMethods
- ActiveRecord::ThrowResult
- ActiveRecord::Timestamp
- ActiveRecord::Transactions
- ActiveRecord::Transactions::ClassMethods
- ActiveRecord::Translation
- ActiveRecord::UnknownAttributeError
- ActiveRecord::UnknownPrimaryKey
- ActiveRecord::Validations
- ActiveRecord::Validations::AssociatedValidator
- ActiveRecord::Validations::ClassMethods
- ActiveRecord::Validations::UniquenessValidator
- ActiveRecord::WrappedDatabaseException
- Mysql
- Mysql::Result
- Mysql::Stmt
- Mysql::Time
- ArJdbcMySQL
- ArJdbcMySQL::Error

No matching classes.

# ActiveRecord::Querying

### Public Instance Methods

count_by_sql(sql) click to toggle source

Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part. The use of this method should be restricted to complicated SQL queries that can't be executed using the ActiveRecord::Calculations class methods. Look into those before using this.

#### Parameters

- `sql` - An SQL statement which should return a count query from the database, see the example below.

#### Examples

    Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"

    # File lib/active_record/querying.rb, line 53
    def count_by_sql(sql)
      sql = sanitize_conditions(sql)
      connection.select_value(sql, "#{name} Count").to_i
    end

find_by_sql(sql, binds = []) click to toggle source

Executes a custom SQL query against your database and returns all the results. The results will be returned as an array with columns requested encapsulated as attributes of the model you call this method from. If you call `Product.find_by_sql` then the results will be returned in a Product object with the attributes you specified in the SQL query.

If you call a complicated SQL query which spans multiple tables the columns specified by the SELECT will be attributes of the model, whether or not they are columns of the corresponding table.

The `sql` parameter is a full SQL query as a string. It will be called as is, there will be no database agnostic conversions performed. This should be a last resort because using, for example, MySQL specific terms will lock you to using that particular database engine or require you to change your call if you switch engines.

#### Examples

    # A simple SQL query spanning multiple tables
    Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
    > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]

    # You can use the same string replacement techniques as you can with ActiveRecord#find
    Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]
    > [#<Post:0x36bff9c @attributes={"title"=>"The Cheap Man Buys Twice"}>, ...]

    # File lib/active_record/querying.rb, line 36
    def find_by_sql(sql, binds = [])
      logging_query_plan do
        connection.select_all(sanitize_sql(sql), "#{name} Load", binds).collect! { |record| instantiate(record) }
      end
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.