Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite "INSERT OR REPLACE INTO" not working

Tags:

sqlite

I have to write a query in sqlite to update the record if it exists or insert it if the record do not already exists. I have looked the syntax of INSERT OR REPLACE INTO from here. But in my case, when I execute the query below many times the record is duplicated. i.e If I execute the query 5 times the record is inserted 5 times.

INSERT OR REPLACE INTO NICKS 
    (id_nick,name_nick,date_creation)
 VALUES 
    ('nabeelarif', 'Muhammad Nabeel','2012-03-04')

Have you any idea what I am doing wrong. I am working on android platform and using 'Firefox Sqlite Manager' to test my query.

like image 553
Muhammad Nabeel Arif Avatar asked Mar 05 '12 20:03

Muhammad Nabeel Arif


People also ask

How does insert and replace work?

You can use the INSERT OR REPLACE statement to write new rows or replace existing rows in the table. The syntax and behavior of the INSERT OR REPLACE statement is similar to the INSERT statement. Unlike the INSERT statement, the INSERT OR REPLACE statement does not generate an error if a row already exists.

How do you replace a word in SQLite?

The SQLite REPLACE() function is a string function that allows you to replace all occurrences of a specified string with another string. In this syntax: string is the string that you want to perform the replacement. pattern is the substring to be found in the original string.

Does SQLite support Upsert?

UPSERT in SQLite follows the syntax established by PostgreSQL. UPSERT syntax was added to SQLite with version 3.24. 0 (2018-06-04). An UPSERT is an ordinary INSERT statement that is followed by the special ON CONFLICT clause shown above.


3 Answers

Do you have a primary key or unique index defined for your table? I believe the attributes that make up the primary key or a unique index are used to determine if a row already exists or not.

like image 156
Jan-Henk Avatar answered Nov 05 '22 15:11

Jan-Henk


You need to have a unique index on one or a combination of those columns.

CREATE UNIQUE INDEX idx_something ON NICKS (id_nick, name_nick, date_creation);

like image 37
Brad Avatar answered Nov 05 '22 13:11

Brad


In Android, you should use SQLiteDatabase.replace(), which does insert or update. With the Android SQLite implementation, you normally don't use raw queries represented as strings. See http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#replace%28java.lang.String,%20java.lang.String,%20android.content.ContentValues%29

like image 6
TotoroTotoro Avatar answered Nov 05 '22 13:11

TotoroTotoro