I often user a separate query to count rows to set a total variable when querying a table for paginated results.
Returns total users in table
SELECT Count(*) FROM users WHERE organizationId = :organizationId
Returns paginated results
SELECT * FROM users WHERE organizationId = :organizationId LIMIT :start, :end
public SearchResults findAll(User user, Paginator paginator) {
HashMap<String, Object> namedParameters = new HashMap<String, Object>();
namedParameters.put("organizationId", user.getOrganizationId());
namedParameters.put("userId", user.getId());
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
//Get count
int total = namedParameterJdbcTemplate.queryForInt(SQL_FIND_ALL_COUNT, namedParameters);
int start = 0;
int end = total;
if(paginator != null) {
start = paginator.getFirst();
end = paginator.getCount();
}
namedParameters.put("start", start);
namedParameters.put("end", end);
SqlRowSet results = namedParameterJdbcTemplate.queryForRowSet(SQL_FIND_ALL, namedParameters);
return new SearchResults(mapUser(results), total);
}
The only reason for collecting the total is so I can return that as part of the search results, because its necessary for pagination so I know how many pages of results to display to the user without actually having to pass the results and find every record in the database.
Is there a way to do this in one query? So in other words, get the total count, while still using the LIMIT condition to only query for a specific amount (say 10 records at a time). If so, from a performance standpoint, does it make more sense to just keep these in separate queries?
Something like this?
SELECT *, (SELECT Count(*) FROM users WHERE organizationId = :organizationId) FROM users WHERE organizationId = :organizationId"
If the above query works, how do I actually get that subquery column, does it have a name I can reference?
results.getInt("count"); //?
Add an
ALIASafter the subqueryAlternative solution in your query is to use
CROSS JOIN