Reduce number of SQL queries