my $sth = $dbh->prepare( "SELECT foo_id, col1, col2 FROM a ORDER BY foo_id"); $sth->execute(); my @group; while (my $row = $sth->fetchrow_hashref) { if (!@group or $row->{foo_id} == $group[0]->{foo_id}) { push @group, $row; } else { # print Dumper(\@group); process(\@group); @group = ($row); } }