Labs ICT
โญ Pro Login

COUNT

COUNT is exactly what it sounds like โ€” it counts rows. It is probably the most used aggregate function in SQL. If you ever work with analytics or reporting, you will use COUNT every single day.

COUNT All Rows

SELECT COUNT(*) AS total_students FROM students;

COUNT(*) counts every row, including rows with NULL values.

COUNT a Specific Column

-- Count only rows where age is NOT NULL
SELECT COUNT(age) AS students_with_age FROM students;

COUNT(column) only counts non-NULL values in that column. If you have 10 rows but only 8 have a value in that column, it returns 8.

COUNT with WHERE

-- How many students scored above 85?
SELECT COUNT(*) AS high_scorers FROM students WHERE score > 85;

COUNT with DISTINCT

Remember DISTINCT? Combine it with COUNT:

-- How many different cities do our students come from?
SELECT COUNT(DISTINCT city) AS unique_cities FROM students;

๐Ÿงช Quick Quiz

Which aggregate function counts the number of rows?