5

I need a MySql statement that will select all the rows, as well as how many total rows there are.

I was using

mysql_query("SELECT * FROM posts LIMIT 0, 5");

...trying to add the count:

mysql_query("SELECT *, COUNT(*) AS total FROM posts LIMIT 0, 5");

...but that only returns a single row.

Also, if there is a better way to get the total than to add an extra column to each row, then I would like that instead. Thank you!

3
  • 2
    If you're using PHP, why not use mysql_num_rows Commented Mar 29, 2012 at 5:47
  • 1
    @hjpotter92 but it depend on which "total" OP is thinking. Total currently selected (than mysql_num_rows is fine) or number of rows in whole table. Commented Mar 29, 2012 at 5:50
  • Good point, @Michal. I addressed both cases in my answer. Commented Mar 29, 2012 at 7:12

3 Answers 3

9

-- Please see @Ittai 's comment below. The proposed solution relies on a feature that has been deprecated -- https://dev.mysql.com/worklog/task/?id=12615

I need a MySql statement that will select all the rows, as well as how many total rows there are.

When taken literally, this is not possible. The result of a SQL query is a (virtual) table; the column in each row in that result table provides a value that is associated with that row only, and the rows are in effect independent of each other.

There are many ways to grab the rowcount of the entire result, but it's either done in two statements or with a query that is conceptually different from what you have. (Solutions below)

There is one aspect in your original question that could be interpreted in multiple ways:

as well as how many total rows there are

This could mean either:

  1. Count each row returned in the result.
  2. Count each row that would have been returned if it weren't for the LIMIT clause (which truncates the result to 5 rows in this case)

(I'll come up with answers for both below)

but that only returns a single row. I'm guessing it's because COUNT(*) is going to be the same for each row, and for some reason, MySql is only returning rows with unique values for it? I have no clue.

COUNT is an aggregate function. By using an aggregate function, you're asking the database to bunch up groups of rows and project some aspects of it into a single row. What is confusing is that mysql also you to mix non-aggregate and aggregate expressions in the same SELECT list. Most other databases don't allow this and give you an error for this, but alas MySQL does not.

But COUNT(*) does still however aggregate all rows into a single row, that represents the entire group of rows.

Also, if there is a better way to get the total than to add an extra column to each row, then I would like that instead. Thank you!

yes, there are several ways.

If you want to get the number of rows returned to PHP, so, after MySQL applied its limit clause, I suggest simply calling the php function mysql_num_rows (http://www.php.net/manual/en/function.mysql-num-rows.php) after doing the mysql_query call.

If you want to get the number of rows that would have been returned in absence of the LIMIT clause, I suggest doing it in 2 steps: first, execute a slighly modified version of your original query, and then, immmediately after that, call MySQL's FOUND_ROWS function. (see http://dev.mysql.com/doc/refman/5.5/en/information-functions.html#function_found-rows)

It would look like this:

$result = mysql_query('SELECT SQL_CALC_FOUND_ROWS * FROM posts LIMIT 0, 5');
//do stuff with the result, but don't do any other queries

//get the total number of rows (disregarding the LIMIT clause) 
$result = mysql_query('SELECT FOUND_ROWS()');

The SQL_CALC_FOUND_ROWS modifier tells MySQL to keep track of the total number of rows before applying the LIMIT clause, and FOUND_ROWS() returns that number. Keep 2 things in mind:

  1. both these mysql_query calls should be executed over the same connection
  2. Don't execute another query inbetween these calls to mysql_query

Oh, final note: when using LIMIT, you typically want the results to be ordered in a particular way. Usually people use LIMIT for pagination. If you don't order the rows, the order is indeterminate and subsequent queries may return rows already returned by previous statements, even if the LIMIT offset is different. You can explicitly order the result by using an ORDER BY clause. (http://dev.mysql.com/doc/refman/5.5/en/select.html)

Sign up to request clarification or add additional context in comments.

5 Comments

Yes, I agree with you entirely on your last statement, it is indeed possible to order the result set explicitly by using an ORDER BY clause. In fact, I would even go as far as to say, "only by using an ORDER BY clause". ;) Just being a little sarcastic, sorry. I find your answer well elaborated and educating, +1.
@Andriy heh, thanks :) Just a nitpick, but in MySQL, for better or for worse, a GROUP BY clause is also guaranteed to return an ordered resultset. You can even specify ASC and DESC modifiers to the expressions in the GROUP BY list.
That's very interesting, thanks! Never heard about that before. Seems unusual at first, but on the other hand, not too surprising if one remembers that MySQL GROUP BY allows one to reference columns by their aliases (instead of real names), and also by their position numbers. Both things are allowed only in ORDER BY in most, if not all, other RDBMSes. So, if MySQL GROUP BY allows that, it seems only consistent that it also accepts ASC & DESC and assumes the relevant functionality.
well, I'm not so sure these things should be coupled. I think it's nice and useful to refer to expressions by their alias. the only place where that would logically not always work is in the WHERE, and even there it could work most of the time. I personally think that guaranteeing that GROUP BY returns an ordered set is a design flaw. It makes the RDBMS do more work than necessary. You can override the behavior by addinga ORDER BY NULL clause, but many tools don't know that.
If you’re coming here now please note that it seems the ROWS FOUND solution is deprecated by mysql dev.mysql.com/worklog/task/?id=12615
7

I'm not sure on which total you are thinking: total currently selected or number of all rows in whole table. This returns numbers of all rows in whole table, of course in each row same value:

mysql_query("SELECT *, (select COUNT(*) from posts) AS total FROM posts LIMIT 0, 5");

5 Comments

Alright, thanks, that's perfect. I assume I could just modify that other query to select the count of what I want it to. Is this terribly inefficient though? Is it making twice as many queries?
@Walkerneo If that's your actual question, then mysql_num_rows is the best solution.
@Walkerneo it is not correlated (there is no correlation between outer and inner query) so it should not lose efficiency. And yes you can limit inner query to anything you want.
I just realized mysql_num_rows isn't what I wanted. I'm only selecting 5 rows, but I need the total number of rows, not just the five I selected. I guess I'll use this, but do you suggest anything else?
@Walkerneo, take a look at my anser. You can solve this with FOUND_ROWS().
1

I think you are over-complicating this issue. I don't see a problem with using two queries.

First query to get total posts (I'm assuming you want the total in the whole table):

SELECT COUNT(*) AS total FROM posts;

And a second, to query for your posts:

SELECT * FROM posts LIMIT 0, 5

The reason is that it's not always a bad thing to retrieve data using more than one query, especially when it makes sense.

If you were to add it as an additional column using say a subquery, you'd have the total in each row, but you'd still basically be running two queries (or would the subquery run for every row, I can't remember?)

It also provides more flexibility to get the count first since some queries will return the wrong total count depending on how complex your query is. And you may need to modify the count query so you get the correct total and can paginate correctly.

For example in the case of a one to many query, say you want to get posts and comments, you'd get the wrong count since the post would get duplicated for each comment for that post.

Abbreviated example:

post_id | comment_id
1       | 1
1       | 2
2       | 3
3       | 4
3       | 5

So to do it correctly you'd first need to run the following query to get total posts:

SELECT COUNT(*) AS total FROM posts;

And then you'd need to run:

SELECT id FROM posts limit 0, 5;

And finally you'd run:

select p.id, c.id from posts p left join comments c on c.post_id = p.id where id in(id list from above query)

Obviously your query wouldn't run into the above problem. But I'm just trying to illustrate why it may be good to get the total count in a separate query.

1 Comment

Using multiple queries does require thinking about concurrency, though. What if something adds or removes rows after your first query finishes, but before the second one starts? The count returned by the second query would be inconsistent with the results of the first. (You can avoid that by doing both queries in a single transaction with a high enough isolation level.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.