domingo, diciembre 07, 2008

Firebird 2.1 UPDATE OR INSERT

Another great feature that I like in Firebird 2.1 is the UPDATE OR INSERT statement. It's a really time saver and it makes the SQL cleaner.

For example suppose I have a products table like the one I use in my last post and an inventory table to store the product stock. Before Firebird 2.1 if I want to set the stock for a product I needed to check if a record for that product_id already exists; if the product_id already exists then I write an update. If not then I write an insert statement. So I ended up with something like this:


IF EXISTS(SELECT * FROM inventory WHERE product_id = :product_id ) THEN
UPDATE
inventory
SET
stock = :stock
WHERE
product_id = :product_id;
ELSE
INSERT INTO inventory
(product_id, stock)
VALUES
(:product_id, :stock);

In this example I only update one field but when I have to update a big table I ended up with a big chunk of code and thinking: "there should be another (better) way to do this".

Fortunately now with Firebird 2.1 there is a better way to do it, I only need to use the UPDATE OR INSERT statement and the engine will take care of checking if the record already exists, based on the primary key value. If the table does not have a primary key defined then I should use the MATCHING keyword with the columns I want to match. So in this example the sql can look like this:

--product_id is the primary key

UPDATE OR INSERT INTO inventory
(product_id, stock)
VALUES
(:product_id, :stock);

or like this

--product_id is not defined as the primary key

UPDATE OR INSERT INTO inventory
(product_id, stock)
VALUES
(:product_id, :stock)
MATCHING
(product_id);


This code looks much cleaner and does not need any comments to explain what is going on.

I really like this new feature.