Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLITE - INSERT or UPDATE without changing ROWID value

I need to update a table row IF EXISTS, otherwise INSERT a new row. I tried:

INSERT OR REPLACE INTO table VALUES ...

but if the row row exist this statement changes the row's ROWID, and that's what I'm trying to avoid (I need the rowid :D)

I also tried to find a way to get some sort of return value from the update, in the case where an update has taken place, but I still don't understand how... If I could get the return value from the update statement, I could choose wether to proceed with an insert or not.

Do you have any suggestion or solution to this problem? Or do I need to make a copy of the ROWID and use that instead of the "pure" table ROWID?

Thanks in advance, best regards

ps: I was looking HERE and I was wondering if sqlite has the OUTPUT special word too, but google didn't help me..

---- EDIT after reading comments:

table schema example

CREATE TABLE test (
    table_id TEXT NOT NULL,
    some_field TEXT NOT NULL,
    PRIMARY KEY(table_id)
)

INSERT or REPLACE INTO test (table_id, some_field) VALUES ("foo","bar")
like image 859
BeNdErR Avatar asked Jul 30 '12 09:07

BeNdErR


People also ask

Does Rowid change in SQLite?

A rowid is assigned to a row upon insert and is imutable (never changing) unless the row is deleted and re-inserted (meaning it is another row, not the same row!) However, rows can be deleted+inserted by various commands "transparently", IF the DBA/table owner has set the "enable row movement" clause on the table.

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.

What does insert or ignore do SQLite?

insert or ignore ... will insert the row(s) and ignore rows which violation any constraint (other than foreign key constraints).


1 Answers

I tested Chris suggestion but the rowid still gets changed. I think the best alternative is to do a SELECT to see if a row with that key already exist. If so, UPDATE, otherwise, INSERT... good old fashion but guaranteed to work.

like image 57
SHamel Avatar answered Oct 09 '22 11:10

SHamel