Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force an INSERT into a table with a unique key if it's already in the table?

I have a table:

CREATE TABLE Students (studentId TEXT PRIMARY KEY, name TEXT);

I want to insert records into the table, if I insert a student twice I want the second insert to override(update) the first record.

INSERT INTO Students (StudentId, name) VALUES ('123', 'Jones');
INSERT INTO Students (StudentId, name) VALUES ('123', 'Jonas');

What's the best way of doing this?

like image 774
stevemcl Avatar asked Nov 07 '11 23:11

stevemcl


People also ask

How do I add a new record to an existing table?

Basic INSERT syntaxINSERT INTO table_name (column1, column2, column3,etc) VALUES (value1, value2, value3, etc); The first line of code uses the INSERT statement followed by the name of the table you want to add the data to. After the table name, you should specify the column names.

What is insert on duplicate key update?

INSERT ... ON DUPLICATE KEY UPDATE is a MariaDB/MySQL extension to the INSERT statement that, if it finds a duplicate unique or primary key, will instead perform an UPDATE. The row/s affected value is reported as 1 if a row is inserted, and 2 if a row is updated, unless the API's CLIENT_FOUND_ROWS flag is set.

How does on duplicate key update work?

ON DUPLICATE KEY UPDATE inserts or updates a row, the LAST_INSERT_ID() function returns the AUTO_INCREMENT value. The ON DUPLICATE KEY UPDATE clause can contain multiple column assignments, separated by commas. The use of VALUES() to refer to the new row and columns is deprecated beginning with MySQL 8.0.

How insert value in table which contains foreign key?

If you are inserting data into a dependent table with foreign keys: Each non-null value you insert into a foreign key column must be equal to some value in the corresponding parent key of the parent table. If any column in the foreign key is null, the entire foreign key is considered null.


1 Answers

Try REPLACE:

REPLACE INTO Students (StudentId, name) VALUES ('123', 'Jonas');

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.

like image 152
p.campbell Avatar answered Sep 21 '22 23:09

p.campbell