How to Count the Numbers of Rows That a MySQL Query Returned

How can I count the numbers of rows that a MySQL query returned?

Getting total rows in a query result...

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";

Getting a count of rows matching some criteria...

Just use COUNT(*) - see Counting Rows in the MySQL manual. For example:

SELECT COUNT(*) FROM foo WHERE bar= 'value';

Get total rows when LIMIT is used...

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.

Get number of rows returned in MySQL query

Select count(*)
From
(
SELECT COUNT(l.product_number_language) as counts, l.id, l.product_number,
l.language, l.product_number_language
FROM bs_products_languages l
LEFT JOIN bs_products p ON (l.product_number_language = p.product_number)
WHERE l.product_number = 'C4164'
AND l.active='Y'
AND p.active='Y'
GROUP BY l.language
) as t

Mysql Query returning record count is more than returning rows

If you want to count the number of groups GROUP BY returns you can use COUNT(distinct user_id)



Related Topics



Leave a reply



Submit