sum() — SQL Technical Interview Questions & Answers

sum()

sum()

  • SUM(marks) adds numbers. NULLs ignored. SELECT SUM(marks) FROM students WHERE city='Pune'; SUM with GROUP BY city.
  • SUM of no rows is NULL. COALESCE(SUM(marks),0) for 0.
  • Trap: SUM on a string column. Trap: SUM(DISTINCT …) unless you really mean unique values only.
  • On the example next to this theory: sum() — aggregate functions collapse many rows into one summary row.

Technical Interview Tip: SELECT city, SUM(marks) FROM students GROUP BY city;

Code Examples for sum()

sum() — 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;

sum() — aggregate functions collapse many rows into one summary row.

How to Explain sum() to an Interviewer

What does SUM skip?

NULL values