count() — SQL Technical Interview Questions & Answers
count()
count()
- COUNT(*) how many rows (including NULL-filled rows). COUNT(marks) how many non-NULL marks. COUNT(DISTINCT city) how many unique cities.
- SELECT city, COUNT(*) FROM students GROUP BY city; class size per city. HAVING COUNT(*) > 10; crowded cities.
- Trap: COUNT(1) vs COUNT(*) myths — both count rows. Trap: COUNT(marks) when you meant students including absentees.
- On the example next to this theory: count() — aggregate functions collapse many rows into one summary row.
Technical Interview Tip: COUNT(*) all rows. COUNT(marks) only who has marks.
Code Examples for count()
count() — sample query
CREATE TABLE scores (id INTEGER PRIMARY KEY, marks INTEGER);
INSERT INTO scores VALUES (1, 80), (2, 90), (3, 70);
SELECT COUNT(*) AS n, AVG(marks) AS avg_marks, MAX(marks) AS top
FROM scores;count() — aggregate functions collapse many rows into one summary row.
How to Explain count() to an Interviewer
Count students with missing marks included?
COUNT(*) Not COUNT(marks)