Target different database for a single query? Can I set the target database on a db_select()?

Example:

$result = db_select('table', 't')-&gt;fields('t')-&gt;db_target('db_name')-&gt;execute();


One can use db_set_active() to change to which database a query should be sent, but that requires one to manually "reset" the active db, which is a potential cause of bugs.
From the comments above such as from @Clive, I do this alll the time:

$count_query = Database::getConnection('default', 'dew_remote_sources')
               -&gt;select('survey', 's');
$count_query-&gt;addExpression('COUNT(DISTINCT(survey_number))', 'cnt');


For this to work you need to have various databases defined in your $databases value of settings.php (or you can add additional $databases[key] values to top of your module sometimes, or create such a connection on-the-fly using:

Database::addConnectionInfo('for_migration', 'default', array(
  'driver' =&gt; 'mysql',
  'database' =&gt; 'migration_database',
  'username' =&gt; 'username',
  'password' =&gt; 'password',
  'host' =&gt; 'localhost',
  'prefix' =&gt; '',
));


You see this pattern alot in the Migrate documentation pages, migrate examples and 3rd party modules that have implemented migrations. Because you are literally moving content from DatabaseX to DatabaseY alot and switching around with db_set_active can easily lead to confusion in such cases with the Object Oriented nature of the Migrate module.