How to use hook_query_alter (Altering Queries in D7)

This gonna be my first post on Drupal 7. Finally I could find some minutes to write up about this. You may already know that previous versions of Drupal a developer would use db_rewrite_sql to essentially perform string manipulation on a sql query in order to modify it but with D7 the DB API has been abstracted so you don't typically write SQL and instead rely more on PDO query. Altering queries is now easier as you are primarily altering structured data (arrays).

In a query object u may use Tag and Metadata but neither tagging nor meta data do anything on their own. Both exist solely to provide information to hook_query_alter(), which can take virtually any action on a Select query.

<?php
/**
* Implementation of hook_query_alter().
*/
function example_query_alter(QueryAlterableInterface $query) {
  // ...
}
?>

More : http://drupal.org/node/310077