SUM() calculates the sum of values from stored records. SUM() doesn’t consider NULL in the calculation, and it returns NULL instead of zero if the executed statement returns no rows.
The input and return types we support can be seen in the table below.
👨🏻💻 If the input type is 32-bit, then the result will be 64-bit.
We have two sample tables here:
It will create a table as shown below:
Here, we have a rental table which stores the details for car rental:
The following example uses the SUM() function to calculate the total rent price of all rental_id:
It will return a sum value of the total_price:
The following example uses the SUM() function to calculate the total rent price of the customer_id = 11118.
Since no records in the rental table have the customer_id = 11118, the SUM() function returns a NULL.
You can use the GROUP BY clause to group the records in the table and apply the SUM() function to each group afterward.
The following example uses the SUM() function and the GROUP BY clause to calculate the total price paid by each customer:
It will calculate the total_price from a group of customer_id as shown below:
You can use the SUM() function with the HAVING clause to filter out the sum of groups based on a specific condition:
It will return the customers who spent greater than or equal to 3000:
The example uses the following:
- SUM() function to calculate total rental days.
- JOIN clause to combine the rental table with the customer table.
- GROUP BY group a result-set based on the customers' names.
The final result will display the customers' names with their total rental period.