for my $currentpage (1..5) { # simulate requests for different pages my $startcount = ($currentpage - 1) * $titlesperpage + 1; dd $dbh->selectall_arrayref( 'SELECT threadID, COUNT(*) FROM messages GROUP BY threadID'); my $sth_s = $dbh->prepare('SELECT msgID, threadID FROM messages ' .'ORDER BY msgID LIMIT ?,?'); $sth_s->execute($startcount, $titlesperpage); while ( my $row = $sth_s->fetchrow_hashref ) { dd $row->{msgID}; } }