my $sql="$a where "; my (@where, @args); if ($something) { push @where, "field1 = ?"; push @args, $some_value; } if ($something_else) { push @where, "field2 = ?"; push @args, $another_value; } $sql .= join " and ", @where; # Assume RaiseError is true; # If this is executed more than once # in this script, # use 'prepare_cached' instead. my $sth = $dbh->prepare($sql); $sth->execute(@args);