I need to write an SQL query for MS Access 2000 so that a row is updated if it exists, but inserted if it does not.
i.e.
If row exists...
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
If it does not exist...
INSERT INTO Table1 VALUES (...)
Can this be done in one query?
(The ON DUPLICATE KEY UPDATE method that works in MySQL doesn't seem to work here.)
The SQL UPDATE Query is used to modify the existing records in a table. You can use the WHERE clause with the UPDATE query to update the selected rows, otherwise all the rows would be affected.
With the INSERT IGNORE statement, MySQL will insert a new row only if the values don't exist in the table.
To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.
Not in one query but you could do two queries for multiple rows.
In MySQL, the equivalent is (as you already know :)
INSERT INTO Table1 (...)
VALUES(...)
ON DUPLICATE KEY
UPDATE column=column+1
;
or
INSERT INTO Table1 (...)
( SELECT ...
FROM ...
)
ON DUPLICATE KEY
UPDATE column=column+1
;
The second form can be written with two queries as:
UPDATE Table1
SET (...)
WHERE Column1 = 'SomeValue'
;
INSERT INTO Table1 (...)
( SELECT ...
FROM ...
WHERE 'SomeValue' NOT IN ( SELECT Column1
FROM Table1 )
)
;
You could also reverse the order and first insert the new rows and then update all rows if that fits with your data better.
*Note that the IN
and NOT IN
subqueries could be possibly converted to equivalent JOIN
and LEFT JOIN with check for NOT NULL
forms.
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