tags:

views:

24

answers:

3

I have a table in SQLite 3:

CREATE TABLE foo
(
bar TEXT
);

It always has 0 or 1 rows. I want to write a query which updates the row if there is 1 row and adds the row if there are 0. What is the cleanest way to do it?

+1  A: 

You could do something like

IF (SELECT COUNT(*) FROM foo) = 0  
    BEGIN  
        INSERT INTO foo VALUES ('text')  
    END  
ELSE  
    BEGIN  
        UPDATE foo SET baa = 'text' 
    END

Hope this helps.

Ash Burlaczenko
@Ash - you've got the logic inverted there - you're updating when the count is zero ...
martin clayton
+1  A: 

Take the approach described here, giving the table a primary key, and using the INSERT OR IGNORE syntax, always using the same key value.

Matt Gibson
+1  A: 

if you could add one more unique field, then you can:

INSERT OR REPLACE INTO foo (id, bar) VALUES (1, ?);

the table creation is in this case:

CREATE TABLE foo (id INTEGER NOT NULL, bar TEXT, UNIQUE (id));

or as Alexey found it out, without the primary key:

INSERT OR REPLACE INTO foo (rowid, bar) VALUES (1, ?);
KARASZI István
Will this work with `rowid` instead of adding another field?
Alexey Romanov
I don't know, you can try.
KARASZI István
looks like it does.
Alexey Romanov
No, actually it doesn't. It deletes already present data instead of updating it.
Alexey Romanov
it replaces the actual data with the new one. isn't it what you've asked for?
KARASZI István
If there are two columns, and I want to update one, the other will be set to default value.
Alexey Romanov
you haven't mentioned this in the O.P.
KARASZI István