1

Possible Duplicate:
Fastest way to count exact number of rows in a very large table?

What query do I use to get the number of rows that share a common specification.
Example: The number of rows where idpost = 3

Community
  • 1
  • 1
Sam K.
  • 147
  • 6
  • possible duplicate of [Fastest way to count exact number of rows in a very large table?](http://stackoverflow.com/questions/6069237/fastest-way-to-count-exact-number-of-rows-in-a-very-large-table) or [php: count the number of rows in mysql?](http://stackoverflow.com/questions/7049153/count-the-number-of-rows-in-mysql) – Anirudh Ramanathan Sep 08 '12 at 18:30

5 Answers5

6

You can use COUNT() documented here.

SELECT COUNT(1) FROM posts WHERE idpost = 3

EDIT: Updated according to dbf's suggestion.. Make sure you distinguish between COUNT(*) and COUNT(1), discussed here.

Community
  • 1
  • 1
Michal Klouda
  • 14,263
  • 7
  • 53
  • 77
  • 2
    for performance reasons if a lot of fields exist in the table, I would consider using COUNT(idpost) instead of * (all) – dbf Sep 08 '12 at 18:31
  • 3
    Both the accepted answer to that linked question (which is specific to [tag:sql-server], not [tag:mysql]) and the manual entry for [`COUNT()`](http://dev.mysql.com/doc//en/group-by-functions.html#function_count) make clear that `COUNT(*)` is perfectly efficient. The MySQL manual states: "*`COUNT(*)` is optimized to return very quickly if the `SELECT` retrieves from one table, no other columns are retrieved, and there is no `WHERE` clause.*" – eggyal Sep 08 '12 at 19:24
  • 1
    @dbf: You are incorrect. See this: [What is better in MYSQL count(*) or count(1)?](http://stackoverflow.com/a/5180023/548696). Both `COUNT(*)` and `COUNT(1)` **perform exactly the same**. – Tadeck Sep 08 '12 at 21:27
2

The query looks like this:

SELECT count(*) FROM some_table WHERE (conditions);

In your example:

SELECT count(*) FROM some_table WHERE idpost=3;

More on counting rows in MySQL: MySQL 5.6 Reference Manual: 3.3.4.8. Counting Rows

EDIT:

If you were wondering, which way of counting all rows is better (count(*) or count(1)), see this: What is better in MYSQL count(*) or count(1)?.

Community
  • 1
  • 1
Tadeck
  • 132,510
  • 28
  • 152
  • 198
1

Consider learning SQL:

select count(*) from mytable where idpost=3
JvdBerg
  • 21,777
  • 8
  • 38
  • 55
1

Try

SELECT
    COUNT(*) as NumberRows
FROM
    your_table_name_here
WHERE
    idpost = 3
;
Jost
  • 5,948
  • 8
  • 42
  • 72
0

the select count(*) function grabs the number of rows that meet a certain criteria - define that in the where statement.

http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html - read here

tehdoommarine
  • 1,868
  • 3
  • 18
  • 31