Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
SUM() Function in MySQL
Next article icon

SQL SUM() Function

Last Updated : 13 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The SUM() function in SQL is one of the most commonly used aggregate functions. It allows us to calculate the total sum of a numeric column, making it essential for reporting and data analysis tasks. Whether we're working with sales data, financial figures, or any other numeric information, the SUM() function can help us quickly compute the sum of values based on specific conditions.

In this article, we will explain the SUM() function in detail, provide multiple examples, and highlight its use in various SQL queries to enhance our understanding.

What is the SQL SUM() Function?

The SUM() function in SQL is used to calculate the total of a numeric column or expression. This aggregate function sums the values in the specified column and returns a single result. It is commonly used in combination with other SQL clauses like WHERE, GROUP BY, and HAVING to refine the data set and calculate sums based on specific conditions.

Syntax

SELECT SUM(column_name)
FROM table_name
WHERE condition;

Key Terms

  • column_name: The numeric column whose values you want to sum.
  • table_name: The name of the table from which to retrieve the data.
  • condition: (Optional) A condition to filter the rows before performing the aggregation.

Examples of SQL SUM() Function

In this section, we will demonstrate the usage of the SUM() function with examples using a sample table called Sales, which stores sales data such as the Product, Quantity, and Price. This simple dataset will help us understand how the SUM() function works in SQL to calculate totals, sums of distinct values, and more.

Sales-Table
Sales Table

Example 1: Using SUM() with One Column

In this example, we will use the SUM() function to calculate the total value of a specific column, such as total sales or total salary.

Query:

SELECT SUM(Salary) AS TotalSalary
FROM Employees;

Output

TotalSalary
450,000

Explanation:

This query calculates the sum of the Salary column in the Employees table. This output shows the total salary paid to employees in the database.

Example 2: Using SUM() with an Expression

We can also use the SUM() function with an expression to calculate sums based on some logic or mathematical operations.

Query:

SELECT SUM(Price * Quantity) AS TotalRevenue
FROM Sales;

Output

TotalRevenue
1,200,000

Explanation:

This query multiplies Price and Quantity for each record in the Sales table and then calculates the sum of those values. This is useful for calculating the total revenue generated from sales.

Example 3: Using SUM() with GROUP BY

When we want to calculate the sum of values within groups, we can use the GROUP BY clause along with SUM(). This is particularly useful for grouping data by categories such as departments, products, or cities.

Query:

SELECT Department, SUM(Salary) AS DepartmentSalary
FROM Employees
GROUP BY Department;

Output

DepartmentDepartmentSalary
HR200,000
Sales300,000
IT250,000

Explanation:

This query groups employees by their Department and then calculates the total salary for each department.

Example 4: Using SUM() with DISTINCT

If we want to sum only the distinct values in a column, we can use the DISTINCT keyword with the SUM() function.

Query:

SELECT SUM(DISTINCT Price) AS TotalDistinctPrice
FROM Products;

Output:

TotalDistinctPrice
500,000

Explanation:

This query sums only the unique values in the Price column of the Products table. Duplicate values are excluded from the sum.

Example 5: Using SUM() with HAVING

The HAVING clause can be used in combination with GROUP BY to filter groups based on the result of the SUM() function. This allows you to apply conditions to the grouped data after the aggregation.

Query:

SELECT Department, SUM(Salary) AS DepartmentSalary
FROM Employees
GROUP BY Department
HAVING SUM(Salary) > 200,000;

Output

DepartmentDepartmentSalary
Sales300,000
IT250,000

Explanation:

This query calculates the total salary per department and then filters the result to include only those departments where the total salary is greater than 200,000.

Best Practices for Using the SQL SUM() Function

  • Use with Indexes: When summing a large dataset, it’s important to have indexes on the columns you’re filtering by, such as dates or categories. This will improve the performance of your query.
  • Use GROUP BY to Categorize Data: The SUM() function works perfectly with GROUP BY. It helps you summarize data efficiently by different categories like departments or regions.
  • Avoid Summing Non-Numeric Values: Ensure that the column you are summing contains only numeric values. Summing non-numeric values can result in errors.
  • Consider Using Aliases: Always use aliases for SUM() results for better readability and clarity in your output.

Conclusion

The SQL SUM() function is a powerful tool for aggregating numeric data. Whether we need to calculate the total salary, revenue, or count items, the SUM() function simplifies these tasks and helps us derive valuable insights from our database. By using it with different clauses like DISTINCT, GROUP BY, and HAVING, we can tailor our queries to specific conditions, making our analysis more efficient. The SUM() function is especially useful for generating summary reports and analyzing financial, sales, or inventory data.


Next Article
SUM() Function in MySQL

A

anubhah6hf
Improve
Article Tags :
  • SQL
  • Databases
  • DBMS-SQL

Similar Reads

  • PL/SQL SUM() Function
    The SUM() function in PL/SQL is used to calculate the sum of the numeric column. It is an aggregate function that performs calculations on a set of values and returns a single value. In this article, we will explore the syntax, usage, and examples of the PL/SQL SUM() function to help us understand i
    5 min read
  • SQLite SUM() Function
    SQLite is an embedded database that doesn't use a database like Oracle in the background to operate. It is written in C language and is used by developers who embed a lightweight database over the existing application, browser, or embedded systems. The main features of SQLite are that it is a tiny,
    6 min read
  • SUM() Function in MySQL
    The SUM() function in MySQL is a powerful aggregate function used to calculate the total sum of values in a numeric column. By summing up the values in the specified column, this function helps in generating overall totals and performing calculations that provide meaningful insights from our data. I
    4 min read
  • SQL UPPER() Function
    In SQL, the UPPER() function is one of the most commonly used string functions. It is used to convert all characters in a given string to uppercase. Whether we are dealing with textual data that requires uniform formatting or need to compare strings without case sensitivity, the UPPER() function com
    4 min read
  • PLSQL | SIN Function
    The PLSQL SIN function is used to return the sine of a numeric value. The SIN function accepts one parameter which is the number whose sine needs to be calculated. The SIN function returns a value of the numeric data type. This function takes as an argument any numeric data type as well as any non-n
    2 min read
  • PLSQL | SUBSTR Function
    The PLSQL SUBSTR function is used for extracting a substring from a string. The SUBSTR function accepts three parameters which are input_string, start_position, length. SUBSTR calculates lengths using characters as defined by the input character set. SUBSTRB uses bytes instead of characters. Note: I
    2 min read
  • PLSQL | SQRT Function
    In PL/SQL, the SQRT function is used to find the square root of a number. This function is really handy for various tasks that involve mathematical calculations, such as analyzing statistics, solving geometry problems, or handling financial data. The SQRT function is easy to use and can simplify com
    4 min read
  • PLSQL | TRIM Function
    The PLSQL TRIM function is used for removing all specified characters either from the beginning or the end of a string. The TRIM function accepts three parameters among which the first parameter can either have one of the values 'LEADING', 'TRAILING', 'Both' and Trim_character and input_string. If L
    2 min read
  • SQL | String functions
    SQL String Functions are powerful tools that allow us to manipulate, format, and extract specific parts of text data in our database. These functions are essential for tasks like cleaning up data, comparing strings, and combining text fields. Whether we're working with names, addresses, or any form
    8 min read
  • PLSQL | UPPER Function
    The PLSQL UPPER function is used for converting all letters in the specified string to uppercase. If there are characters in the string that are not letters, they are unaffected by this function. The char to be converted can be any of the datatypes such as CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences