my $sth = $dbh->prepare("SELECT item1 as _first_item, item2 as _second_item, item3 as _third_item FROM table WHERE topic = ? ORDER BY id ASC"); my @loop = map { $sth->execute( $_ ); { _TOPIC => $_, _ITEMS => $sth->fetchall_arrayref({}) }; } @topic[0 .. $x-1];