Monday, January 25, 2010

Count the number of rows in a MySQL query, the COUNT function

Many times it'snecessary to count the result lines of a query. There are two ways to do this, php (mysql_num_rows) and MySQL with the COUNT. In this post I show the MySQL COUNT function.



This is a normal SELECT queries:

SELECT * FROM table WHERE field='value'

The result of this query is compose by all rows that respect the WHERE clause (field='value'). But if I want to retrieve only the number of rows but not its value I can use the mydql count function. At the follow a example:

SELECT COUNT(*) FROM table WHERE  field='value'

Now the result is the number of rows that respect the WHERE clause. This function can also be applied on a table field in this way:


SELECT COUNT(field) FROM table WHERE  field='value'

In this way the query is faster the the other with the all value (*).

No comments:

Post a Comment