title: MySQL INSERT IF (custom if statements)
body: <p>First, here's the concise summary of the question:</p>
  
  <p>Is it possible to run an <code>INSERT</code> statement conditionally?
  Something akin to this:</p>
  
  <pre><code>IF(expression) INSERT...
  </code></pre>
  
  <p>Now, I know I can do this with a stored procedure.
  My question is: can I do this in my query?</p>
  
  <hr>
  
  <p>Now, why would I want to do that?</p>
  
  <p>Let's assume we have the following 2 tables:</p>
  
  <pre><code>products: id, qty_on_hand
  orders: id, product_id, qty
  </code></pre>
  
  <p>Now, let's say an order for 20 Voodoo Dolls  (product id 2) comes in.<br />
  We first check if there's enough Quantity On Hand:</p>
  
  <pre><code>SELECT IF(
      ( SELECT SUM(qty) FROM orders WHERE product_id = 2  ) + 20
      &lt;=
      ( SELECT qty_on_hand FROM products WHERE id = 2)
  , 'true', 'false');
  </code></pre>
  
  <p>Then, if it evaluates to true, we run an <code>INSERT</code> query.<br />
  So far so good.</p>
  
  <hr>
  
  <p>However, there's a problem with concurrency.<br />
  If 2 orders come in at the <em>exact same time</em>, they might both read the quantity-on-hand before any one of them has entered the order.
  They'll then both place the order, thus exceeding the <code>qty_on_hand</code>.</p>
  
  <hr>
  
  <p>So, back to the root of the question:<br />
  Is it possible to run an <code>INSERT</code> statement conditionally, so that we can combine both these queries into one?</p>
  
  <p>I searched around a lot, and the only type of conditional <code>INSERT</code> statement that I could find was <code>ON DUPLICATE KEY</code>, which obviously does not apply here.</p>