The SQL SUM function is used to calculate the total sum of a numeric column by adding all of the numeric values. This function is useful when you need to get the total values in a dataset.
SQL Sum Syntax
SQL
x
1
SELECT SUM(column_name)
2
FROM table_name
3
WHERE condition;
SQL Sum Example
SQL Sum with All Rows Example
This query sums up the total length of all contact numbers from the Patients table.
SQL
1
1
SELECT SUM(LENGTH(contact_number))
2
FROM Patients;

SQL Sum with a WHERE Clause
This query calculates the total length of contact numbers for all female patients. The WHERE clause limits the rows to those where gender = ‘F’
SQL
1
1
SELECT SUM(LENGTH(contact_number))
2
FROM Patients
3
WHERE gender = 'F';

SQL Sum with Group By Clause
This query calculates the total length of contact numbers for each gender group. The GROUP BY clause divides the rows by gender.
SQL
1
1
SELECT gender, SUM(LENGTH(contact_number))
2
FROM Patients
3
GROUP BY gender;

SQL Sum Visual Diagram
