Home > Database > Mysql Tutorial > body text

How to Count Results in MySQL Queries?

Linda Hamilton
Release: 2024-11-04 11:08:02
Original
587 people have browsed it

How to Count Results in MySQL Queries?

Counting Results from MySQL Queries

The number of rows returned by a MySQL query can be retrieved using several methods:

Iterating Over Results

Simply loop through the result set and count the rows. While this approach can be straightforward, it's not very efficient.

Using MySQL Functions

MySQL provides the mysql_num_rows function to count the rows in a result. This function is exposed in client libraries, such as mysqli_num_rows in PHP:

<code class="php">$result = mysqli_query($link, "SELECT * FROM table1");
$num_rows = mysqli_num_rows($result);</code>
Copy after login

Using COUNT(*) for Selective Counting

To count rows matching specific criteria, use the COUNT(*) aggregate function. For example:

<code class="sql">SELECT COUNT(*) FROM foo WHERE bar= 'value';</code>
Copy after login

Getting Total Rows When Using LIMIT

If your query includes a LIMIT clause, you can use SQL_CALC_FOUND_ROWS and FOUND_ROWS() to retrieve the total number of rows that would have been returned without the LIMIT:

<code class="sql">SELECT SQL_CALC_FOUND_ROWS * FROM foo
   WHERE bar="value" 
   LIMIT 10;

SELECT FOUND_ROWS();</code>
Copy after login

Note: Using SQL_CALC_FOUND_ROWS is deprecated in MySQL 8.0.17 and higher. It's recommended to issue a separate query to calculate the count instead.

The above is the detailed content of How to Count Results in MySQL Queries?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!