something like pseudocode: foreach my $data(tableA){ my $sth = "select count * from tableA where tableA = tableB"; do_it ($sth); }