Conditional INSERT Statements in MySQL
Question: Is it feasible to perform an INSERT operation conditionally, akin to an IF statement?
Elaboration:
Suppose we need to place an order for 20 items with product ID 2. To ensure sufficient stock, we first check the quantity on hand:
SELECT IF( ( SELECT SUM(qty) FROM orders WHERE product_id = 2 ) 20If the result is true, we execute the INSERT query. However, this approach is susceptible to concurrency issues. Multiple simultaneous orders can result in overselling.
Answer:
Yes, conditional INSERT statements are possible using the following syntax:
INSERT INTO TABLE SELECT value_for_column1, value_for_column2, ... FROM wherever WHERE your_special_conditionIf the SELECT statement returns no rows (i.e., the special condition is false), no insertion occurs.
Example:
For the given schema:
products: id, qty_on_hand orders: id, product_id, qtyinsert into orders (product_id, qty) select 2, 20 where (SELECT qty_on_hand FROM products WHERE id = 2) > 20;This query will only insert a row if there is sufficient stock on hand. Otherwise, it will not execute the insertion.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3