# untested but realistic my $dbh = DBI->connect("...",{RaiseError => 1} ) or die "can't\n"; my $cust_sth = $dbh->prepare( qq{SELECT cust_ID, cust_name from customer}); $cust_sth->execute(); while (my $cust = $cust_sth->fetchrow_hashref()) { my $orders_sth = $dbh->prepare( qq{select * from orders where cust_ID = ? }); # do something smart with customer name $order_sth->execute($cust->{cust_ID}); while (my $order = $orders_sth->fetchrow_hashref()) { # do something even smarter with the orders data } }