SQL COUNT

The COUNT() function returns the number of rows in the result set.

 

Syntax:

SELECT COUNT(column_name) FROM table_name WHERE condition;

 

Example Database:

This is  employee  table.

id name salary hire date
1 Kailash 20000 2022-12-10
2 Amit 5000 2022-07-15
3 Siddarth 15000 2022-03-23
4 Amit 30000 2022-08-20

 

Example 1: COUNT()

Find total entries in employee table using count.

SQL:

SELECT COUNT(*) FROM employee;

Result:

COUNT(*)
4

 

Example 2: Aliases with COUNT()

Find total entries in employee table using count as alias.

SQL:

SELECT COUNT(*) as TOTAL FROM employee;

Result:

TOTAL
4

 

Example 3: COUNT() with WHERE

SQL:

SELECT COUNT(name) AS TOTAL
FROM employee
WHERE name = 'Amit';

Result:

TOTAL
2

 

Example 4: COUNT() with DISTINCT

If we need to count the number of unique rows, we can use the COUNT() function with the DISTINCT clause

SQL:

SELECT COUNT(DISTINCT name)
FROM employee;

Result:

COUNT(DISTINCT name)
3