You can sort in the database rather than run many queries with
select Id, Name from Person where id = '+variable+';
You can loop through variables and make a comma-separated list, so you only run one query
int[] variableList = wherever_you_get_it_from; StringBuffer csv = new StringBuffer(); for (int i = 0; i < variableList.length; i++) { csv.append(variableList[i]); if (i < variableList.length - 1) csv.append(","); }
then give
select Id, Name from Person where id in ( +csv.toString()+) order by Name;
Since you get user IDs from the company table, you can join and get
select u.usrid, u.name from company c left join user u on c.usrid = u.usrid where c.companyid in (comapnyid1, companyid2, companyid3) order by u.name;
source share