SQLite SUM and IN commands for Android
public int calculateTotalSalaryForEmployees( long[] departmentIds )
{
int total = 0;
// create a list of ids to use in the IN statement
// Arrays.toString creates String which looks like [1,2,3]
String deptlist = Arrays.toString( departmentIds );
// remove the enclosing brackets from id list
String inClause = deptlist.substring( 1, deptlist.length() - 1 );
String sql = "select sum(salary) from employees where department_id " +
"in (" + inClause + ")";
Cursor c = mDb.rawQuery( sql, null );
// move to the first row of the cursor
c.moveToFirst();
total = c.getInt(0);
c.close();
return total;
}
Trying something new out here. As I’m programming I find many little hints and tips that I want to remember or share. Not the longer more in-depth posts I’ve been trying out with the subjects on Android HTTP and Ruby on Rails, but little quick things to put into ones toolbox.
So here’s the first one, a little method to retrieve the sum of all the salaries of employees within a department. It utilizes the SQL SUM and IN commands. It was surprisingly difficult to find the exact way to perform these command, but surprisingly obvious and easy once I figured it out. Just the types of little tools I don’t want to loose.

December 13th, 2008 at 2:00 am
I like the idea of the series and in that spirit I want to ask if it is necessary to close the cursor after using it? I would assume that when you create Cursors yourself and don’t let Android manage it you would leak Cursors if you don’t close them after use.
December 15th, 2008 at 3:04 pm
Good point Mariano, the cursor should be closed before exiting the method.
Thanks for the catch,
- michael