my $sql = 'select col_x, col_x from a_table'; # You'll be setting this hash up from some kind of # input to your program. I'm using variables for # illustrative purposes. my %cols = ( col_x => $foo, col_y => $bar, col_z => $baz, ); my @where; my @vals; foreach (keys $cols) { if (defined $cols{$_}) { push @where, "$_ = ?"; push @vals, $cols{$_}; } } if (@where) { $sql .= ' where ' . join(' and ', @where); } my $sth = $dbh->prepare($sql); $sth->execute(@vals);