SQLite UPSERT / UPDATE OR INSERT

Q&A Style Well, after researching and fighting with the problem for hours, I found out that there are two ways to accomplish this, depending on the structure of your table and if you have foreign keys restrictions activated to maintain integrity. I’d like to share this in a clean format to save some time to … Read more

Using a if condition in an insert SQL Server

The pattern is (without error handling): SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; BEGIN TRANSACTION; UPDATE #TProductSales SET StockQty = @StockQty, ETA1 = @ETA1 WHERE ProductID = @ProductID; IF @@ROWCOUNT = 0 BEGIN INSERT #TProductSales(ProductID, StockQTY, ETA1) VALUES(@ProductID, @StockQTY, @ETA1); END COMMIT TRANSACTION; You don’t need to perform an additional read of the #temp table here. You’re … Read more

MongoDB: upsert sub-document

No there isn’t really a better solution to this, so perhaps with an explanation. Suppose you have a document in place that has the structure as you show: { “name”: “foo”, “bars”: [{ “name”: “qux”, “somefield”: 1 }] } If you do an update like this db.foo.update( { “name”: “foo”, “bars.name”: “qux” }, { “$set”: … Read more

How to Perform an UPSERT so that I can use both new and old values in update part

As mentioned in my comment, you don’t have to do the subselect to reference to the row that’s causing ON DUPLICATE KEY to fire. So, in your example you can use the following: INSERT INTO `item` (`item_name`, items_in_stock) VALUES( ‘A’, 27) ON DUPLICATE KEY UPDATE `new_items_count` = `new_items_count` + 27 Remember that most things are … Read more