count() in SQL

Syntax of using count() :

Count () can be used in SELECT statement as well as in GROUP BY clause.

Syntax with SELECT STATEMENT :-

SELECT COUNT(EXPRESSION) FROM TABLE_NAME;
SELECT COLUMN_NAME,COUNT(EXPRESSION) FROM TABLE_NAME GROUP BY COLUMN_NAME HAVING COUNT(EXPRESSION) RELATIONAL_OPERATOR VALUE;
emid	ename	cmpny
NULL NULL 0
NULL NULL 0
NULL NULL 0
SELECT count(*)
FROM [tb_emp_table]
3
emid	ename	cmpny
NULL NULL 0
NULL NULL 0
NULL NULL 0
SELECT count(1)
FROM [tb_emp_table]
3
emid	ename	cmpny
NULL NULL 0
NULL NULL 0
NULL NULL 0
SELECT count(empid)
FROM [tb_emp_table]
0

note:-

Count takes complex expressions as well like case, if, etc. Example:-

Data:-
emid ename cmpny
1 Vihal tcs
2 XYZ0 wipro
3 XYZ 3i
4 Aarsh tcs
5 XYZ1 tcs

SELECT count(
case
when cmpny='tcs' then
emid
end)
FROM [tb_emp_table];

result:-
3

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vishal Pathak

Vishal Pathak

72 Followers

love ❤ coding, solving some industry problems technologies: JavaScript, C#, Angular, PLSQL, Docker Want to learn: Python, Go language, AI, ML and Cloud