title: Have AND Clause if variable is not null in MySQL Select
body: <p>Hello I am trying to make an If statement inside SQL Select query, I would like to apply only if variable $department is different than NULL. if the variable is different then Null place <code>P2.department = P1.department</code> as AND Clause. </p>
  
  <p>The query line is as follows: </p>
  
  <pre><code>,(SELECT SUM(P2.fee) FROM cases P2 WHERE 
   IF('$department' IS NULL, 0, P2.department = P1.department) AND curency = 1) as fee_USD
  </code></pre>
  
  <p>In the current situation the query is working but it displays wrong results. My question is this is the best way to include <code>P2.department = P1.department AND</code> inside the query. Any help is welcome. </p>
  
  <p>Here is the full query: </p>
  
  <pre><code>                       SELECT 
                         P1.id
                        ,P1.department
                        ,P1.curency
                        ,P1.fee   
                        ,count(P1.id) as count_cases
                        ,(SELECT SUM(P2.fee) FROM cases P2 WHERE 
                        IF('$department' IS NULL, 0, P2.department = P1.department) 
                        AND curency = 1) as fee_USD                                           
  
                      FROM cases P1 WHERE 1";                                                 
                              if (!empty($department)) { $sql .= " AND P1.department = '$department'"; }
                              if (!empty($status)) { $sql .= " AND P1.status = '$status'"; }
  </code></pre>