Database query with notExists
Here is another approach to write Dynamic queries. We generally write queries in phpmyadmin or mysql command prompt and then convert them to D7 style or dynamic queries using Query coder module.

For example, as per your question, you want to find out all those records in child table which don't exist in parent table.

So D6 style query,

db_query("SELECT c.* FROM {child} c LEFT JOIN {parent} p ON c.p_id = p.p_id WHERE p.p_id IS NULL");


after converting to D7 style query using query coder module would look like,

$query = db_select('child', 'c');
$query-&gt;fields('c', array('*'));
$query-&gt;leftJoin('parent', 'p', 'c.p_id = p.p_id');
$query-&gt;isNull('p.p_id');
$result = $query-&gt;execute();