Home > Database > Mysql Tutorial > How to Efficiently Count Rows in MySQL Query Results?

How to Efficiently Count Rows in MySQL Query Results?

DDD
Release: 2024-11-05 02:34:02
Original
444 people have browsed it

How to Efficiently Count Rows in MySQL Query Results?

Counting Rows in MySQL Query Results

Introduction:

When working with MySQL databases, counting the number of rows resulting from a query is a common task for various applications. This article provides several methods for efficiently counting rows in MySQL.

1. Using the mysql_num_rows() Function:

The mysql_num_rows() function returns the number of rows in a result set. To use it, retrieve the result from the database using a query and then pass the result to the function:

# Example usage in PHP:
$result = mysqli_query($conn, "SELECT * FROM table1");
$num_rows = mysqli_num_rows($result);
Copy after login

2. Using the COUNT(*) Keyword:

The COUNT(*) keyword allows you to count the number of rows that match a specific criterion. This is particularly useful for filtering results:

# Count rows where 'bar' equals 'value':
SELECT COUNT(*) FROM table1 WHERE bar = 'value';
Copy after login

3. Getting Total Rows with LIMIT (Until MySQL 8.0.16):

To obtain the total number of rows without considering the LIMIT clause, use the SQL_CALC_FOUND_ROWS keyword followed by SELECT FOUND_ROWS():

# Calculate total rows ignoring LIMIT:
SELECT SQL_CALC_FOUND_ROWS * FROM table1 WHERE bar = 'value' LIMIT 10;

SELECT FOUND_ROWS();
Copy after login

Important Note for MySQL 8.0.17 and Later:

SQL_CALC_FOUND_ROWS is deprecated in MySQL 8.0.17 and will be removed in future versions. Instead, it is recommended to use a separate query to calculate the total row count.

The above is the detailed content of How to Efficiently Count Rows in MySQL Query Results?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template