How to count rows effectively (or how to get administrator's attention)
18 July, 2006
Last week I found this beauty:
select * from SCHEMA.USERS where ID in
(105,145,165,166,167,168,169,187,188,189,190,225,245,
246,285,305,326,345,346,347,348,366,385,386, ... ... 8407)
and 1=1
and USER_GROUP_ID='108'
and DESCRIPTION like '%'
or DESCRIPTION is NULL
order by DESCRIPTION;
So I started searching for the "guilty code" and I found this:
// description: returns number of entries
function get_user_list(&$ap_result, $a_id, $a_description, $a_group){
$db =& db::get("schemaname");
$l_query = "select * from ".USERS_TABLE." ";
$l_query.= "where ".USERS_ID." in ($a_id) and 1=1";
if($a_group)
$l_query.= " and ".USER_GROUP_ID."='$a_group'";
if ($a_description)
$l_query .= " and ".USERS_DESCRIPTION." like '$a_description'";
if ($a_description=="%")
$l_query .= " or ".USERS_DESCRIPTION." is NULL";
$l_query.= " order by ".USERS_DESCRIPTION;
$l_res_id = $db->exec($l_query);
if(!$l_res_id){
api::debug("1901", "db error", $db->lasterr());
return false;
}
while($l_row = $db->fetch($l_res_id)){
$ap_result[] = $l_row;
}
$db->free($l_res_id);
return count($ap_result);
}
Dear developer, well done! You've got my attention. Now I will show you some tricks like how to write meaningful SQL queries, SELECT COUNT magic, tricky Bind variables, how to minimize transfered bytes over network, how to minimize CPU or IO operations or how to use curly braces in control structures and other interesting things. Also I'll try to tell you the terrible truth. There is no _GO_FASTER=TRUE (1=1).
Why, why I didn't take the blue pill?! :-)
There are no published comments.
New comment