my $sql = "SELECT * FROM mytable WHERE foo = bar"; my $sth = $dbh->prepare($sql); $sth->execute() || die $DBI::errstr; my $row = $sth->fetchrow_hashref; my %cols = %$row; # Print the field names print join(', ', sort keys %cols); # Print corresponding values print join(', ', map { defined $cols{$_} ? $dbh->quote($cols{$_}) : 'NULL' } sort keys %cols);