0

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.

1
  • 1
    I editted primarily the grammar to make it more clear what was being asked. I also removed 'Java', 'Android', 'row', and 'exists' tags -- the first two because this is about SQLite and not the Java/Android implementations; the last two because they're nonsense. If this question really is about something Java or Android specific, please update your question with Java/Android code that is specific to such an implementation rather than just SQLite in general Commented Mar 8, 2015 at 22:59

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

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.