Given any query (grouping, joins, and subqueries are all possible in any combination), I'd like to break it up with pagination as efficiently as possible. Right now I just run the query, then count the number of rows returned to PHP, figure out how many pages of data that is, display the ones that go on the current page, and output the proper links to the other pages.
Seems to me that the potentially very large result set from the query is mostly wasted however. Is there a way to run the query twice where the first time you select COUNT(*) to get a single number with the rows to be paginated and the second time you run the original query with proper limits based on the page currently being viewed? Would this be significantly less taxing on the database server?
For a trivial query this is no problem... replace everything after SELECT and before WHERE with count(*). However this doesn't work if there is grouping in the query, as you'll get the count in each group, not the total number of rows. If you're grouping on columns a, b, and c is it correct to select count(distinct a, b, c)? Does anything special need to be done to handle subqueries?