my @where, @params); if (defined $foo) { push @where, "foo = ?"; push @params, $foo; } if (defined $bar) { push @where, "bar = ?"; push @params, $bar; } my $sth = $dbh->prepare($sql . " WHERE ". join(" AND ", @where)); $sth->execute(@params);