my $dbh = DBI->connect("DBI:mysql:database=proyecto;host=localhost", "root", "xyz123", {'RaiseError' => 1}); # Pre-prepare using placeholders my $sth_a = $dbh->prepare("SELECT dept, course FROM final WHERE pat=?"); my $sth = $dbh->prepare("SELECT DISTINCT PAT FROM patentes"); $sth->execute(); while (my ($pat) = $sth->fetchrow_array()) { # You don't need an array here $sth_a->execute($pat); while (my ($dept,$course) = $sth_a->fetchrow_array()) { print "$pat, $dept, $course\n"; # Here you can create and populate your new tables as needed } } $sth->finish() $sth_a-finish();