PHP contextual filter code in drupal 7 'no query was run'
I would suspect that no query is run because your code snippet isn't returning anything. The thing that jumps out to me is that you are trying to use $result as the first row returned by the query, however it is actually the entire result set.  For example, retrieving data from a DB usually look similar to the code below:

$result = db_query($sql);

// Iterate over the collection ($result).
foreach ($result as $record) {
  $agency_id = $record-&gt;agencyid;
}


In the example you posted above, you could use the following code snippet to pull a single field from the first row in the result set:

// This would return the agency ID.
return db_query($sql)-&gt;fetchField();


Take a look at the documentation of fetchField() for more information on how it is used.