10

What is the difference between using a

rawQuery(String sql, String[] selectionArgs)

and

query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)

in android?

From my understanding query() method should in turn convert its parameters to form a sql query. So, would rawQuery() method give us better performance over query()?

Prasanna
  • 2,593
  • 7
  • 39
  • 53
  • Well, a rawQuery doesn't have to perform such a "transform", so it should be a little faster. And it allows you writing complex query strings, let's say a query with a join between two (or more) different tables. – Phantômaxx Feb 22 '14 at 17:09
  • 3
    Either way its going to be dominated by the time to actually perform the SQL lookup. RawQuery is for people who understand SQL and aren't afraid of it, query is for people who don't. – Gabe Sechan Feb 22 '14 at 17:13
  • You should check these two questions and their answers: http://stackoverflow.com/q/8435932/529138 and http://stackoverflow.com/q/8830753/529138. This question is kind of a duplicate. – Bandreid Feb 22 '14 at 17:15

1 Answers1

1

To execute queries, there are two methods: Execute db.rawQuery method Execute db.query method To execute a raw query to retrieve all departments:

Cursor getAllDepts()
  {
   SQLiteDatabase db=this.getReadableDatabase();
   Cursor cur=db.rawQuery("SELECT "+colDeptID+" as _id, 
        "+colDeptName+" from "+deptTable,new String [] {});

   return cur;
  }

The rawQuery method has two parameters: String query: The select statement String[] selection args: The arguments if a WHERE clause is included in the select statement Notes The result of a query is returned in Cursor object. In a select statement if the primary key column (the id column) of the table has a name other than _id, then you have to use an alias in the form SELECT [Column Name] as _id cause the Cursor object always expects that the primary key column has the name _id or it will throw an exception . Another way to perform a query is to use a db.query method. A query to select all employees in a certain department from a view would be like this:

public Cursor getEmpByDept(String Dept) {
   SQLiteDatabase db=this.getReadableDatabase();
   String [] columns=new String[]{"_id",colName,colAge,colDeptName};
   Cursor c=db.query(viewEmps, columns, colDeptName+"=?", 
        new String[]{Dept}, null, null, null);
   return c;
  }

The db.query has the following parameters: String Table Name: The name of the table to run the query against String [ ] columns: The projection of the query, i.e., the columns to retrieve String WHERE clause: where clause, if none pass null String [ ] selection args: The parameters of the WHERE clause String Group by: A string specifying group by clause String Having: A string specifying HAVING clause String Order By by: A string Order By by clause