Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL access query- Update row if exists, insert if does not

Tags:

sql

ms-access

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.)

like image 395
Urbycoz Avatar asked Mar 14 '11 10:03

Urbycoz


People also ask

Can you write update query with WHERE condition?

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.

Which command insert rows that do not exist and update the rows that exist?

With the INSERT IGNORE statement, MySQL will insert a new row only if the values don't exist in the table.

How do you check if a row exists or not?

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.


1 Answers

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.

like image 110
ypercubeᵀᴹ Avatar answered Nov 16 '22 04:11

ypercubeᵀᴹ