How to order a database query In Drupal v7.22 I'm trying to order the query below for a custom module but I cannot seem to find documentation that fits this query.

$sql = "SELECT field1, field2 FROM {tablename} WHERE field3 = :var1 AND field4 = :var2";
$result = db_query($sql, array(':var1' =&gt; $var1, ':var2' =&gt; $var2));
$num = $result-&gt;rowCount();
if ($num != null) {
  foreach($result as $line) {
    // Do something
  }
}


I've found details on 'orderBy' but only with examples as below which are not in the same format as my query. Any help would be appreciated.

$query-&gt;groupBy("thread.sid");
$query-&gt;having("MAX(comment.created)");
$query-&gt;orderBy("comment.created", "DESC");
$result = $query-&gt;execute();
Something like:

$query = db_select('tablename');
$query-&gt;fields('tablename', array('field1', 'field2'));
$query-&gt;condition('field3', $var1);
$query-&gt;condition('field4', $var2);
$query-&gt;orderBy('field1', 'DESC');

$result = $query-&gt;execute();

foreach($result as $row){
  // Debug
  drupal_set_message('&lt;pre&gt;'.print_r($row,1).'&lt;/pre&gt;');
}


More info: 


https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_select/7
https://api.drupal.org/api/drupal/includes%21database%21select.inc/function/SelectQuery%3A%3AorderBy/7