Full fix for CRM-13293

 Also includes query optimization in where() function.