Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL INSERT IF (custom if statements)
    primarykey
    data
    text
    <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>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload