ChatGPT解决这个技术问题 Extra ChatGPT

INSERT IF NOT EXISTS ELSE UPDATE?

I've found a few "would be" solutions for the classic "How do I insert a new record or update one if it already exists" but I cannot get any of them to work in SQLite.

I have a table defined as follows:

CREATE TABLE Book 
ID     INTEGER PRIMARY KEY AUTOINCREMENT,
Name   VARCHAR(60) UNIQUE,
TypeID INTEGER,
Level  INTEGER,
Seen   INTEGER

What I want to do is add a record with a unique Name. If the Name already exists, I want to modify the fields.

Can somebody tell me how to do this please?

"insert or replace" is utterly different from "insert or update"
How about UPSERT? 😁
Does this answer your question? SQLite - UPSERT *not* INSERT or REPLACE

j
janm

Have a look at http://sqlite.org/lang_conflict.html.

You want something like:

insert or replace into Book (ID, Name, TypeID, Level, Seen) values
((select ID from Book where Name = "SearchName"), "SearchName", ...);

Note that any field not in the insert list will be set to NULL if the row already exists in the table. This is why there's a subselect for the ID column: In the replacement case the statement would set it to NULL and then a fresh ID would be allocated.

This approach can also be used if you want to leave particular field values alone if the row in the replacement case but set the field to NULL in the insert case.

For example, assuming you want to leave Seen alone:

insert or replace into Book (ID, Name, TypeID, Level, Seen) values (
   (select ID from Book where Name = "SearchName"),
   "SearchName",
    5,
    6,
    (select Seen from Book where Name = "SearchName"));

Wrong "insert or replace" is different than "insert or update". For a valid answer, see stackoverflow.com/questions/418898/…
@rds No, it's not wrong because this question says "modify the fields" and the primary key is not part of the column list, but all of the other fields are. If you are going to have corner cases where you are not replacing all of the field values, or if you are messing around with the primary key you should be doing something different. If you have a complete set of new fields this approach is just fine. Do you have a specific problem I can't see?
It's valid if you know all the new value for all the fields. If the user update only, say, the Level, this approach cannot be followed.
Correct. The other answer is relevant, but this approach is valid for updating all fields (excluding the key).
Yes This is Completly wrong. What will happen if just i want to update single column value on Confliction from new one. In above case all other data will be replaced by new one that is not correct.
i
imans77

You should use the INSERT OR IGNORE command followed by an UPDATE command: In the following example name is a primary key:

INSERT OR IGNORE INTO my_table (name, age) VALUES ('Karen', 34)
UPDATE my_table SET age = 34 WHERE name='Karen'

The first command will insert the record. If the record exists, it will ignore the error caused by the conflict with an existing primary key.

The second command will update the record (which now definitely exists)


at which moment it will ignore? when the name and age are both the same?
This should be the solution... if you are using any trigger on insert, the accepted answer fires every time. This does not and performs an update only
It ignores based solely on the name. Remember that only the "name" column is a primary key.
When the record is new, then the update is not necessary but will be executed anyway, leading to bad performance?
How to execute a prepared statement for this?
A
Anna B

You need to set a constraint on the table to trigger a "conflict" which you then resolve by doing a replace:

CREATE TABLE data   (id INTEGER PRIMARY KEY, event_id INTEGER, track_id INTEGER, value REAL);
CREATE UNIQUE INDEX data_idx ON data(event_id, track_id);

Then you can issue:

INSERT OR REPLACE INTO data VALUES (NULL, 1, 2, 3);
INSERT OR REPLACE INTO data VALUES (NULL, 2, 2, 3);
INSERT OR REPLACE INTO data VALUES (NULL, 1, 2, 5);

The "SELECT * FROM data" will give you:

2|2|2|3.0
3|1|2|5.0

Note that the data.id is "3" and not "1" because REPLACE does a DELETE and INSERT, not an UPDATE. This also means that you must ensure that you define all necessary columns or you will get unexpected NULL values.


B
Burçin

Firstly update it. If affected row count = 0 then insert it. Its the easiest and suitable for all RDBMS.


Two operations should be no problem with a transaction at the right isolation level, regardless of the database.
Insert or Replace is really more preferable.
I really wish IT documentation would contain more examples. I've tried this below and it doesn't work (my syntax is obviously wrong). Any ideas on what it should be? INSERT INTO Book (Name,TypeID,Level,Seen) VALUES( 'Superman', '2', '14', '0' ) ON CONFLICT REPLACE Book (Name,TypeID,Level,Seen) VALUES( 'Superman', '2', '14', '0' )
Also what if row values are exactly the same, then affected row count will be zero, and a new duplicate row will be created.
+1, because INSERT OR REPLACE will delete the original row on conflict and if you are not setting all the columns, you will lose original values
S
Steely Wing

INSERT OR REPLACE will replace the other fields to default value.

sqlite> CREATE TABLE Book (
  ID     INTEGER PRIMARY KEY AUTOINCREMENT,
  Name   TEXT,
  TypeID INTEGER,
  Level  INTEGER,
  Seen   INTEGER
);

sqlite> INSERT INTO Book VALUES (1001, 'C++', 10, 10, 0);
sqlite> SELECT * FROM Book;
1001|C++|10|10|0

sqlite> INSERT OR REPLACE INTO Book(ID, Name) VALUES(1001, 'SQLite');

sqlite> SELECT * FROM Book;
1001|SQLite|||

If you want to preserve the other field

Method 1

sqlite> SELECT * FROM Book;
1001|C++|10|10|0

sqlite> INSERT OR IGNORE INTO Book(ID) VALUES(1001);
sqlite> UPDATE Book SET Name='SQLite' WHERE ID=1001;

sqlite> SELECT * FROM Book;
1001|SQLite|10|10|0

Method 2

Using UPSERT (syntax was added to SQLite with version 3.24.0 (2018-06-04))

INSERT INTO Book (ID, Name)
  VALUES (1001, 'SQLite')
  ON CONFLICT (ID) DO
  UPDATE SET Name=excluded.Name;

The excluded. prefix equal to the value in VALUES ('SQLite').


j
jww

Upsert is what you want. UPSERT syntax was added to SQLite with version 3.24.0 (2018-06-04).

CREATE TABLE phonebook2(
  name TEXT PRIMARY KEY,
  phonenumber TEXT,
  validDate DATE
);

INSERT INTO phonebook2(name,phonenumber,validDate)
  VALUES('Alice','704-555-1212','2018-05-08')
  ON CONFLICT(name) DO UPDATE SET
    phonenumber=excluded.phonenumber,
    validDate=excluded.validDate
  WHERE excluded.validDate>phonebook2.validDate;

Be warned that at this point the actual word "UPSERT" is not part of the upsert syntax.

The correct syntax is

INSERT INTO ... ON CONFLICT(...) DO UPDATE SET...

and if you are doing INSERT INTO SELECT ... your select needs at least WHERE true to solve parser ambiguity about the token ON with the join syntax.

Be warned that INSERT OR REPLACE... will delete the record before inserting a new one if it has to replace, which could be bad if you have foreign key cascades or other delete triggers.


It exists in the documentation and I have the lastest version of sqlite which is 3.25.1 but it doesn't work for me
did you try those two queries above verbatim?
Note that Ubuntu 18.04 comes with SQLite3 v3.22, not 3.25, so it doesn't support the UPSERT syntax.
This works well and is the supported method recommended in the documentation.
m
matt

If you have no primary key, You can insert if not exist, then do an update. The table must contain at least one entry before using this.

INSERT INTO Test 
   (id, name)
   SELECT 
      101 as id, 
      'Bob' as name
   FROM Test
       WHERE NOT EXISTS(SELECT * FROM Test WHERE id = 101 and name = 'Bob') LIMIT 1;

Update Test SET id='101' WHERE name='Bob';

This is the only solution that worked for me without creating duplicate entries. Probably because the table I am using has no primary keys, and has 2 columns with no default values. Even though it is a bit of a lengthy solution, it does the job properly and works as expected.
C
Community

I believe you want UPSERT.

"INSERT OR REPLACE" without the additional trickery in that answer will reset any fields you don't specify to NULL or other default value. (This behavior of INSERT OR REPLACE is unlike UPDATE; it's exactly like INSERT, because it actually is INSERT; however if what you wanted is UPDATE-if-exists you probably want the UPDATE semantics and will be unpleasantly surprised by the actual result.)

The trickery from the suggested UPSERT implementation is basically to use INSERT OR REPLACE, but specify all fields, using embedded SELECT clauses to retrieve the current value for fields you don't want to change.


C
Community

I think it's worth pointing out that there can be some unexpected behaviour here if you don't thoroughly understand how PRIMARY KEY and UNIQUE interact.

As an example, if you want to insert a record only if the NAME field isn't currently taken, and if it is, you want a constraint exception to fire to tell you, then INSERT OR REPLACE will not throw and exception and instead will resolve the UNIQUE constraint itself by replacing the conflicting record (the existing record with the same NAME). Gaspard's demonstrates this really well in his answer above.

If you want a constraint exception to fire, you have to use an INSERT statement, and rely on a separate UPDATE command to update the record once you know the name isn't taken.