my $next_col1 = "select distinct(col1) from table1"; $next_col1 = $dbh -> prepare($next_col1); $next_col1 -> execute(); my @col1s = map { @{ $_ } } @{ $next_col1 -> fetchall_arrayref() }; foreach my $col1 (@col1s) { ...