2

There are three fields(_id,name,count) in in a table name poet. I want to check if poet name exist in the table then update count field with increment of 1 or else insert a new record with the given name and count as 1. Here is my query. It is inserting null value for count if there name not found in the table. Although it is working good if I want to update already existing records.

insert or replace into poet (_id,Name, count) values (
   (select _id from poet where Name = "SearchName"),
   "SearchName",
    (select count from poet where Name = "SearchName")+ 1)

2 Answers 2

4

How about changing the query to use ifnull or coalesce.

insert or replace into poet (_id,Name, count) values (
   (select _id from poet where Name = "SearchName"),
   "SearchName",
    ifnull((select count from poet where Name = "SearchName"), 0) + 1)
Sign up to request clarification or add additional context in comments.

Comments

1

Don't try to be clever. Just use two commands:

db.beginTransaction();
try {
    db.execSQL("UPDATE poet SET count = count + 1 WHERE Name = ?",
               new Object[]{ searchName });
    if (DatabaseUtils.longForQuery(db, "SELECT changes()", null) == 0) {
        db.execSQL("INSERT INTO poet(Name, count) VALUES(?,?)",
                    new Object[]{ searchName, 1 });
    }
    db.setTransactionSuccessful();
} finally {
    db.endTransaction();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.