23

I am looking to the fastest and the correct way to check if a record exists in the database:

public boolean Exists(String _id) {
    Cursor c=db.query(TABLENAME(), new String[] {"1"}, "_ID="+_id, null, null, null, null);
    if (!c.equals(null))
        return c.moveToFirst();
    return false;
}

Do you see any problem with it?

1

6 Answers 6

41

Consider that mDb is your SqlLiteDatabase class

public boolean Exists(String _id) {
   Cursor cursor = mDb.rawQuery("select 1 from yourTable where _id=%s", 
        new String[] { _id });
   boolean exists = (cursor.getCount() > 0);
   cursor.close();
   return exists;
}
  • I keep your parameter _id as a String but I think it should be a Long.
  • select 1 is more fast than select columnName because the process doesn't need to retrieve all values from the table in the select clause.
  • you can put the string select 1 from... in a static final constant to be even faster.
6
  • 4
    you should also close the cursor before returning a value. it doesn't cause a crash but it does give warnings.
    – Al.
    Mar 4, 2010 at 17:46
  • Such a valuable answer! I never consider about a good way to check exits record till my current app, which works a lot with database. Really thank u!
    – Anh Tuan
    Jul 25, 2011 at 1:47
  • @tbruyelle: I have to check a record is existed or not in listview, then present its. I implemented in getItemViewType in adapter, but it make app freeze until i touch anywhere, then it's just worked again :( Is there a way to run it in another thread at getItemViewType?
    – Steve Luck
    Oct 28, 2015 at 4:13
  • @SteveLuck I can't say, you should post a question with all the details.
    – tbruyelle
    Oct 29, 2015 at 10:30
  • @tbruyelle: I posted a new thread here. Please have a look stackoverflow.com/questions/33427726/…
    – Steve Luck
    Oct 30, 2015 at 6:17
6
+100

Since you are looking for an answer from 'credible and/or official sources', here in DatabaseUtils we have a method called queryNumEntries.

So your method could be made like this:

public boolean Exists(String _id) {
    return DatabaseUtils.queryNumEntries(db, TABLENAME(), "_ID=?", new String[] {"1"}) > 0;
}

Or, for faster one:

public boolean Exists(String _id) {
    return DatabaseUtils.longForQuery(db, "select count(*) from " + TABLENAME() + " where _ID=? limit 1", new String[] {"1"}) > 0;
}
2
  • This was the kind of answer I was looking for when I made the bounty. I wasn't aware of these DatabaseUtils before. If you wouldn't mind, could you briefly explain why longForQuery is faster? The documentation is a little sparse on that one.
    – Suragch
    Mar 4, 2015 at 14:37
  • I guess it is faster because of the LIMIT 1 clause, preventing it from counting the number of rows if you have multiple rows that fulfills the selection criteria. However, since your criteria is _ID, which can be assumed unique for a particular table, then both of them should be of the same speed. Mar 5, 2015 at 1:39
5

This question and the selected answer were helpful to me for understanding how to simply and quickly check if a record exits. However, I've seen many places that recommend against using rawQuery because of the possibility of SQL injection. (For example, rawQuery Vs. database.query)

So here is what I decided on:

public boolean Exists(String searchItem) {

    String[] columns = { COLUMN_NAME };
    String selection = COLUMN_NAME + " =?";
    String[] selectionArgs = { searchItem };
    String limit = "1";

    Cursor cursor = db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, null, limit);
    boolean exists = (cursor.getCount() > 0);
    cursor.close();
    return exists;
}

I don't know if this is as fast as the selected answer or not, but after researching this it seems to conform to recommended Android conventions more.

Update

I now recommend @yuku's answer, but I won't delete mine yet because I still want to guide people away from using raw queries.

1

Try this:

In your DatabaseHelper, put this method...

public String Exist(String user) {        
     String username="";
     SQLiteDatabase db = this.getReadableDatabase();               

     try { 
         Cursor c = db.query(TABLE_USER, null, KEY_USER + "=?", new String[]{String.valueOf(user)},null, null, null);                                               

         if (c == null) {                        
             return username;                                   
         }
         else {    
             c.moveToFirst();               
             username = c.getString(c.getColumnIndex(KEY_USER)); 
         }                           
     }

     catch(Exception e){
         e.printStackTrace();
     }

     return username; 
}

then in your onClickListener, try to call the method that you create in your DatabaseHelper. Try this code:

String myUser = txtUser.getText().toString();
String storedUser = db.Exist(myUser);


//If Username exist
if (myUser.equals(storedUser)){
    Toast.makeText(getApplicationContext(), "Username already exist!", Toast.LENGTH_SHORT).show();
0

Checkout my answer here: Android Sqlite: Check if row exists in table

0

This works good:

  Cursor cursor = null;
  String sql ="SELECT * FROM "+TableName+" WHERE ID="+idValue; 
  cursor= db.rawQuery(sql,null);
  Log.d("ISEXISTS","Cursor Count : " + cursor.getCount());

  boolean exists = (cursor.getCount() > 0);
  cursor.close();

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.