SQL COUNT(): Count Rows and Values

SQL COUNT query

The SQL COUNT() aggregate function returns a number. Use COUNT(*) when you want to count rows in a result set.

SELECT COUNT(*) AS total_records
FROM student;

For the Plus2net sample student table, this returns:

total_records
35
Important difference: COUNT(*) counts rows. COUNT(column_name) counts only rows where that column is not NULL.

SQL COUNT() Syntax Top ↑

To count all rows returned by a query:

SELECT COUNT(*)
FROM table_name;

An alias gives the result a useful column name:

SELECT COUNT(*) AS total_records
FROM student;

COUNT() returns one row containing the aggregate result unless it is combined with GROUP BY.

COUNT() with WHERE Top ↑

Add a WHERE clause when only matching rows should be counted.

SELECT COUNT(*) AS total_records
FROM student
WHERE class = 'Four';

For the sample table, the output is:

total_records
9

COUNT() with Multiple Conditions Top ↑

SELECT COUNT(*) AS total_records
FROM student
WHERE class = 'Four'
  AND mark > 60;

This counts students in class Four whose mark is greater than 60. See AND and OR conditions.

COUNT() with BETWEEN Top ↑

SELECT COUNT(*) AS total_records
FROM student
WHERE class = 'Four'
  AND mark BETWEEN 50 AND 60;

See the BETWEEN tutorial for range conditions.

COUNT(*) vs COUNT(column) Top ↑

SELECT COUNT(*) AS row_count,
       COUNT(class) AS class_value_count
FROM student3;
  • COUNT(*) counts every row.
  • COUNT(class) counts only rows where class is not NULL.

The older version of this tutorial suggested that counting a unique ID is inherently more efficient than COUNT(*). That should not be treated as a general rule. Use the form that matches the result you need.

COUNT(DISTINCT) for Unique Values Top ↑

SELECT COUNT(DISTINCT class) AS unique_classes
FROM student;

For the sample table, the output is 7. See DISTINCT when you want the unique values themselves.

COUNT() with GROUP BY Top ↑

SELECT class,
       COUNT(*) AS total_students
FROM student
GROUP BY class
ORDER BY class;

Each class becomes one result row with its own count.

Filter Grouped Counts with HAVING Top ↑

SELECT class,
       COUNT(*) AS total_students
FROM student
GROUP BY class
HAVING COUNT(*) > 5;
WHERE filters individual rows before grouping. HAVING filters grouped results after aggregation.

COUNT() and NULL Values Top ↑

SELECT IFNULL(class,'Not Known') AS class,
       COUNT(*) AS total_rows
FROM student3
GROUP BY class;

For the NULL group, COUNT(*) still counts the rows.

SELECT IFNULL(class,'Not Known') AS class,
       COUNT(class) AS known_class_values
FROM student3
GROUP BY class;

For rows where class is NULL, COUNT(class) returns 0. See SQL NULL values.

SQL dump of student3 table

COUNT() with LEFT JOIN Top ↑

SELECT product.product,
       COUNT(product_sale.product_id) AS sale_count
FROM product
LEFT JOIN product_sale
  ON product_sale.product_id = product.product_id
GROUP BY product.product_id, product.product
ORDER BY product.product_id;
productsale_count
Monitor3
CPU1
Keyboard0
Mouse0

Counting the right-table key allows unmatched products to show a count of zero. See LEFT JOIN.

Download the SQL dump of the product tables.

Conditional Counts in One Row Top ↑

MySQL can calculate several conditional counts in one query:

SELECT
COUNT(IF(class = 'Three', 1, NULL)) AS THREE,
COUNT(IF(class = 'Four', 1, NULL)) AS FOUR,
COUNT(IF(class = 'Five', 1, NULL)) AS FIVE
FROM student;

This uses the MySQL IF() function. A portable alternative uses CASE with SUM().

Count Records between Two Dates Top ↑

SELECT COUNT(*) AS no_tickets
FROM main_table
WHERE DATE_PL BETWEEN '2026-09-01'
                  AND '2026-09-30';

If dates come from PHP or a form, validate them and bind them as prepared-statement parameters rather than inserting variables directly into SQL text.

Get a COUNT() Result in PHP PDO Top ↑

<?php
require 'config.php';

$class='Four';

$stmt=$dbo->prepare(
    "SELECT COUNT(*)
     FROM student
     WHERE class=:class"
);

$stmt->bindValue(
    ':class',
    $class,
    PDO::PARAM_STR
);

$stmt->execute();

$total=(int)$stmt->fetchColumn();

echo 'Number of records: '.$total;

For a SELECT count, this is more portable than relying on PDO rowCount(). See PDO rowCount().

COUNT() Performance Notes Top ↑

  • Use COUNT(*) when the question is "how many rows?"
  • Use COUNT(column) when the question is "how many non-NULL values?"
  • Use COUNT(DISTINCT column) when the question is "how many unique non-NULL values?"
  • Indexes can help selective WHERE and JOIN conditions, depending on the query and data.
  • For expensive queries on large tables, inspect the execution plan rather than assuming one COUNT form is always faster.

SQL COUNT() Video Top ↑

Number of records in a table with different conditions by using SQL COUNT()

Common SQL COUNT() Mistakes Top ↑

Using COUNT(column) when NULL rows must be counted Top ↑

COUNT(column) ignores NULL values. Use COUNT(*) when every row should contribute to the total.

Using COUNT(*) on the right side of a LEFT JOIN Top ↑

If you want zero for unmatched child rows, count a non-NULL key from the child table.

Using WHERE to filter an aggregate result Top ↑

Use WHERE before grouping to filter rows. Use HAVING when filtering grouped results such as COUNT(*) > 5.

Fetching all rows in PHP only to count them Top ↑

If only the count is needed, let SQL return the aggregate instead of transferring every matching row to PHP.

SQL SUM SQL AVG SQL MAX

GROUP BY HAVING LEFT JOIN

Student table SQL dump

Frequently Asked Questions Top ↑

Q1: What does COUNT(*) do in SQL?

COUNT(*) returns the number of rows in the result set, including rows containing NULL values in individual columns.

Q2: What is the difference between COUNT(*) and COUNT(column)?

COUNT(*) counts rows. COUNT(column) counts only rows where the specified column is not NULL.

Q3: Does COUNT(DISTINCT column) count NULL?

No. It counts distinct non-NULL values in the specified expression.

Q4: Can COUNT() be used with WHERE?

Yes. WHERE first filters the rows and COUNT() returns the number of rows or non-NULL values remaining after that filter.

Q5: How do I get a separate count for each category?

Use COUNT() with GROUP BY. Each group produces its own aggregate count.

Q6: What is the difference between WHERE and HAVING with COUNT()?

WHERE filters source rows before grouping. HAVING filters grouped aggregate results.

Q7: How should I get a COUNT() value with PHP PDO?

Execute the COUNT query and use PDOStatement::fetchColumn() to retrieve the aggregate value directly.





Subscribe to our YouTube Channel here



plus2net.com
Nagappan

06-11-2009

IT'S VERY NICE
nayan

02-04-2010

hi thanks for giving information thanks again...
sumit

27-04-2010

please tell me the query if i want to count the no. employees from a table emp_detail (and display it) and also need to see the different entries of a different table course_detail ? I need to see them on single web page together..
Rajan Arora

25-06-2010

Really simple and nice way to explain... Gr8 gng... Keep it Up ...
ragavan

11-07-2010

u r done a very good job. i need the answer for how to get the totals of the three columns in the table.
vikas

10-10-2010

how to get the totals of between two given date.
Bruno

17-12-2010

Pls I need a syntax for count with this scenario: patients who visited their gp in the last three months
Siddharth

23-12-2011

how to add a new row of total at the last of all the integer record.. plz help me
sathya

23-12-2011

Pls i need a syntax to increase the count by 1. (e.g): In a shop bill generation, the bill no should increase automatically by 1 at each bill
dhanasekaran

04-02-2012

hi..plz help me out. i like to get count of records in the table ( included deleted recors ). in other words.. the number of records from the table creation.
Alvin567

09-08-2012

Hi there, is it possible to do this? Select count(enabled = 1) from user
saurabh titus

30-09-2014

i have a question. i have a table with 2 fields(name,second field is no of cards)how i calculate all the no of cards with or without using sql,
it is necessary to use sql or not
vey

18-08-2015

Can i Count Quantity student by Anny subject with sql server
SMO

10-02-2017

You have to use SQL , All database supports SQL to manage data.
smo1234

10-02-2017

By using if condition you can create grid view, this part is added to the main contain of this page.
adrian

14-10-2017

i want the the ouput will be display in a label
smo1234

15-10-2017

Link is added to generate code for label
Swetha

15-12-2018

How to find highest value in the table where no total column we need to find highest without having total column
smo1234

16-12-2018

Use SQL MAX

04-09-2019


how to add a new row of total at the last of all the integer record.. plz help me

14-08-2020

How to count inserted and deleted rows separately on same page.

23-08-2020

You can use MySQL function mysql_affected_rows() to get the number of records deleted or update or inserted after executing the query.

18-01-2022

How to select count of record year wise

15-08-2022

I have a referral system, email is the referral code it's working but I want to count how many times a value (email) appears in a row as to display to the user how many person he/she have refer.

22-09-2022

SELECT count(*) from table_name WHERE email='userid@exampl.com'

22-09-2022

SELECT year(date_column),count(*) FROM table_name GROUP BY year(date_column)
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer