ph94
ph94

Reputation: 27

Check if row with value already exists in SQLite table

How do I check to see if row with a particular value already exists in a SQLite table?

My table has a String "name" column. I would like to check out if a particular name already exists in the another table row. I am still learning SQLite, but I think it is possible to do this with the cursor.

Upvotes: 0

Views: 1429

Answers (1)

CL.
CL.

Reputation: 180010

If you have a UNIQUE constraint on the name column, you can use INSERT OR IGNORE (or insertWithOnConflict() in Android) to insert a row only if it does not already exist.

In the general case, to check whether a row exists, you have to run a SELECT query. However, there is a helper function for counting rows:

boolean nameExists(String name) {
    SQLiteDatabase db = ...;
    long count = DatabaseUtils.queryNumEntries(db,
                    "MyTable", "name = ?", new String[] { name });
    return count > 0;
}

Upvotes: 2

Related Questions