How can I construct a MySQL INSERT query that only executes if the number of rows satisfying some condition already in the table is less than 20, and fails otherwise?
That is, if the table has 18 rows satisfying the condition, then the INSERT should proceed. If the table has 23 rows satisfying the condition, then the INSERT should fail.
For atomicity, I need to express this in a single query, so two requests can not INSERT at the same time, each in the 'belief' that only 19 rows satisfy the condition.
Thank you.
What about:
INSERT INTO TargetTable(Column1, Column2, ...)
SELECT 'Value For Column 1', 'Value For Column 2', ...
FROM Dual
WHERE (SELECT COUNT(*) FROM TargetTable WHERE ...Some Condition...) < 20;
If the WHERE clause is not satisfied, no row is inserted; if the where clause is satisfied, then one row is inserted.
You can adapt the same mechanism to select from another table (instead of a single row of values from DUAL).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With