The
COUNT function is one the simplest function in SQL Server and very useful in counting the number of records which are expected
to be returned by a SELECT statement.
SQL COUNT SYNTAX
Select COUNT(column_name) FROM tablename
Consider the
Products table which has the following records:
Prd001 |
Pen |
40.25 |
Prd002 |
Pen |
100.75 |
Prd003 |
Eraser |
10.35 |
Prd004 |
Pencil |
20.45 |
Prd005 |
Book |
50.65 |
Prd006 |
Gum |
25.22 |
To count the total number of records in this table, the Count function can be used as shown below:
Select COUNT(*) as TotalNoOfRecords from Products;
Similarly to count the number of records for a particular value in a column such as
Pen
then it can be done as shown below:
Select COUNT(*) as PenCount from Products
Where ProductName= 'Pen';
Note: Since all SQL queries are case insensitive, it does not make any difference if you give
PEN or
Pen
in the
Where condition.