I am trying to Update a row if it exists, otherwise insert (on duplicate key update) in MS Access, with the answer from this question SQL access query- Update row if exists, insert if does not
My insert query has the form:
INSERT INTO mytbl(id, title, notes)
(SELECT 10, 'test', 'a'
From mytbl
WHERE 10 Not IN (select id from mytbl)
)
But I get an SQL syntax error. What am I missing here?
You don’t need the parentheses around the outside SELECT:
To handle the duplicate key error, I added the
TOP 1clause.The way your query was originally written, if 10 is not an ID in mytbl, then the SELECT portion of your query would return a record for every existing row in mytbl. Because you are not referencing any fields in the table, they would all be identical rows. For example, if there were four rows in mytbl, you would have:
It would then try to do an insert for each of those returned rows. The first would succeed and the rest would fail with a duplicate key error. The
TOP 1clause says just use the TOP 1 record. Order does not matter in this case. Since all your fields are literals, every row will be the same.Note that you could accomplish the same thing by substituting
DISTINCTforTOP 1. I would expect the performance to be worse, though, unless the db engine is smart enough to realize up front that every row will be identical.EDIT: DummyTableWithExactlyOneRecord is a local table with exactly one record. As @onedaywhen pointed out in his comment below, if there are no records at all in the table you are SELECTing from, then no record will be inserted.
Note that if you can guarantee that your dummy table will always have exactly 1 record, then the
TOP 1clause is not necessary. However, I’ve left it in because I think it makes the intent more obvious to a reader who may not know the contents of the dummy table (I’m assuming you will be naming your dummy table something shorter thanDummyTableWithExactlyOneRecord).