settings and switching to external pgsql db
first check whether you are executing your query before  doing db_set_active(); because this function call will set your db to default drupal db.

so you should go like this:

db_set_active('custom_db');


// execute your query related stuff here

then at last switch to your default db by db_set_active();