my $count =0; my $maximum = 20; while (my $array_ref = $sth->fetchrow_arrayref()) { last if $count++ >= $maximum; # do something with your records } $sth->finish(); # will clean the memory in the database