How can I count the number of rows that a MySQL query returned?
If you want the result plus the number of rows returned do something like this. Using PHP.
$query = "SELECT * FROM Employee";
$result = mysql_query($query);
echo "There are ".mysql_num_rows($result)." Employee(s).";
Assuming you're using the mysql_ or mysqli_ functions, your question should already have been answered by others.
However if you're using PDO, there is no easy function to return the number of rows retrieved by a select statement, unfortunately. You have to use count() on the resultset (after assigning it to a local variable, usually).
Or if you're only interested in the number and not the data, PDOStatement::fetchColumn() on your SELECT COUNT(1)... result.
If your SQL query has a LIMIT
clause and you want to know how many results total are in that data set you can use SQL_CALC_FOUND_ROWS
followed by SELECT FOUND_ROWS();
This returns the number of rows A LOT more efficiently that using COUNT(*)
Example (straight from MySQL docs):
mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
-> WHERE id > 100 LIMIT 10;
mysql> SELECT FOUND_ROWS();
This is not a direct answer to the question, but in practice I often want to have an estimate of the number of rows that will be in the result set. For most type of queries, MySQL's "EXPLAIN" delivers that.
I for example use that to refuse to run a client query if the explain looks bad enough.
Then also daily run "ANALYZE LOCAL TABLE" (outside of replication, to prevent cluster locks) on your tables, on each involved MySQL server.
You could just iterate the result and count them. You don't say what language or client library you are using, but the API does provide a mysql_num_rows function which can tell you the number of rows in a result.
This is exposed in PHP, for example, as the mysqli_num_rows function. As you've edited the question to mention you're using PHP, here's a simple example using mysqli functions:
$link = mysqli_connect("localhost", "user", "password", "database");
$result = mysqli_query($link, "SELECT * FROM table1");
$num_rows = mysqli_num_rows($result);
echo "$num_rows Rows\n";
Just use COUNT(*) - see Counting Rows in the MySQL manual. For example:
SELECT COUNT(*) FROM foo WHERE bar= 'value';
If you'd used a LIMIT clause but want to know how many rows you'd get without it, use SQL_CALC_FOUND_ROWS in your query, followed by SELECT FOUND_ROWS();
SELECT SQL_CALC_FOUND_ROWS * FROM foo
WHERE bar="value"
LIMIT 10;
SELECT FOUND_ROWS();
For very large tables, this isn't going to be particularly efficient, and you're better off running a simpler query to obtain a count and caching it before running your queries to get pages of data.