Development

How to do INSERT with an UPDATE on duplicate using SQLite

How to do an UPDATE from an INSERT with SQLite when there is a duplicate key value.

With SQLite you cannot do the simple MySQL INSERT on duplicate key UPDATE:

INSERT INTO `table` (id, name, price, quantity) VALUES(1, 'test', '2.50', 164)
    ON DUPLICATE KEY UPDATE `quantity` = 164, `price` = '2.50'

Instead, you have to do what is called an upsert.

The concept is very similar to the MySQL example above. The differences being you have to specify which column is the indexed/key column (unique) and then state the DO UPDATE:

INSERT INTO users(username,score) VALUES('Johnny', 388) 
ON CONFLICT(username) DO UPDATE SET score = '388';

Had you need to update multiple columns simply separate each update instance with a comma:

DO UPDATE SET score = '388', rating = 'A';

From the example if a row already has the value “Johnny” in the name column then the score column value will be updated to be 388.

Share
Tags: How toSQLite

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago