Clean up where conditions in sql query

Less raw SQL, more arrays. Also remove an array_merge() we don't
need anymore.

Change-Id: I2862460a4ebfa3340e7af5c7661a110c8f1f5694
Merge "Clean up where conditions in sql query"