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:
PLSQL | SQRT Function
Next article icon

PL/SQL SUM() Function

Last Updated : 23 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 its importance in database operations.

PL/SQL SUM() Function

  • The SUM() function is commonly used in database management systems like Oracle to add up the values of a particular numeric field. It is an essential part of the aggregate functions that help in summarizing large datasets.
  • The SUM() function is often used in scenarios where we need to sum values from multiple rows like calculating the total sales of the product or the total salary of the employees.

Syntax:

SELECT SUM(column_name) 
FROM table_name
[WHERE condition];

Key Terms:

  • column_name: The column on which the sum operation is to be performed. It should contain numeric data.
  • table_name: The name of the table where the column resides.
  • WHERE condition: A filter to restrict which rows are included in the sum.

Create the Employees Table

The given SQL query creates an employees table with three columns: employee_id, name, and salary. The subsequent INSERT statements add five employee records to the table, with their respective IDs, names, and salaries.

Query:

CREATE TABLE employees (
employee_id INT PRIMARY KEY,
name VARCHAR(50),
salary INT
);

INSERT INTO employees (employee_id, name, salary)
VALUES (1, 'John', 50000);
INSERT INTO employees (employee_id, name, salary)
VALUES (2, 'Sarah', 60000);
INSERT INTO employees (employee_id, name, salary)
VALUES (3, 'David', 55000);
INSERT INTO employees (employee_id, name, salary)
VALUES (4, 'Emily', NULL);
INSERT INTO employees (employee_id, name, salary)
VALUES (5, 'Steve', 45000);

Output:

employee_idnamesalary
1John50000
2Sarah60000
3David55000
4EmilyNULL
5Steve45000

Explanation:

In the above table, we have created an employees table with columns: employee_id, name, and salary. Notice that Emily's salary is NULL, which will be ignored by the SUM() function.

Example 1: Calculating Total Salary (Ignoring NULL Values)

This example demonstrates how to calculate the total salary of all employees using the SUM() function, which automatically ignores NULL values. In the context of employee salary data, this ensures that any missing salary information does not affect the result.

Query:

SELECT SUM(salary) AS total_salary
FROM employees;

Output:

total_salary
210000

Explanation:

The SUM() function adds the salaries of all employees except Emily, whose salary is NULL. The total sum is 50000 + 60000 + 55000 + 45000 = 210000.

Example 2: Using SUM() with GROUP BY Clause

When we need to calculate the sum of the values for different groups in a dataset the SUM() function is often paired with the GROUP BY clause. The GROUP BY allows to categorize your data into the distinct groups based on the one or more columns and then apply aggregate functions like SUM() to the each group individually.

Query:

ALTER TABLE employees ADD department VARCHAR(20);

UPDATE employees SET department = 'Sales' WHERE employee_id IN (1, 2);
UPDATE employees SET department = 'HR' WHERE employee_id IN (3, 4, 5);

SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department;

Output:

departmenttotal_salary
HR100000
Sales110000

Explanation:

The salaries are grouped by department. In the HR department, the sum of salaries is 55000 (David) + 45000 (Steve) = 100000, while in the Sales department, the sum is 50000 (John) + 60000 (Sarah) = 110000. Emily’s NULL salary is ignored.

Example 3: Using SUM() with HAVING Clause

The HAVING clause is used to filter groups based on the result of an aggregate function like SUM(). Let’s filter out departments whose total salary is less than 100000.

Query:

SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department
HAVING SUM(salary) > 100000;

Output:

departmenttotal_salary
Sales110000

Explanation:

Only the Sales department is shown because its total salary (110000) is greater than 100000. The HR department is excluded because its total salary is 100000, which does not meet the filter condition.

Example 4: SUM() with INNER JOIN Clause

The SUM() function can be used in combination with the INNER JOIN to aggregate data across multiple tables. Consider the following example where we have two tables: customers and sales.

Query:

SELECT c.customer_name, SUM(s.amount) AS total_sales
FROM customers c
INNER JOIN sales s ON c.customer_id = s.customer_id
GROUP BY c.customer_name;

Output:

customer_nametotal_sales
Customer A250
Customer B200

Explanation:

The SUM() function adds up the sales amounts for each customer. Customer A has sales of 100 + 150 = 250, and Customer B has a total of 200.

Conclusion

The SUM() function in PL/SQL is an essential tool for the database developers and administrators when it comes to summarizing numeric data. It can be used in the combination with the other SQL clauses like GROUP BY and WHERE to perform the powerful data aggregation. Understanding how to use SUM() efficiently allows to generate valuable insights from the large datasets.


Next Article
PLSQL | SQRT Function

G

gururaj69bn
Improve
Article Tags :
  • PL/SQL
  • Databases

Similar Reads

  • SQL SUM() Function
    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(
    5 min read
  • PL/SQL Functions
    PL/SQL functions are reusable blocks of code that can be used to perform specific tasks. They are similar to procedures but must always return a value. A function in PL/SQL contains:Function Header: The function header includes the function name and an optional parameter list. It is the first part o
    4 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
  • 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
  • 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
  • SQL LAG() Function
    The LAG() function in SQL is a powerful window function that allows you to retrieve the value of a column from the previous row in the result set. It is commonly used for tasks like calculating differences between rows, tracking trends, and comparing data within specific partitions. In this article,
    4 min read
  • PL/SQL AVG() Function
    The PL/SQL AVG() function serves as a powerful tool for performing aggregate calculations on numeric datasets within a database. By allowing developers to calculate average values while excluding NULL entries, it enhances data analysis capabilities. In this article, we will explore the AVG() functio
    5 min read
  • PL/SQL MAX() Function
    The PL/SQL MAX() function is an essential aggregate function in Oracle databases, enabling users to efficiently determine the largest value in a dataset. Whether working with numerical data, dates, or strings, the MAX() function is flexible and widely applicable. In this article, we will provide a d
    4 min read
  • PL/SQL MIN() Function
    PL/SQL means Procedural Language / relational Structured Query Language, the extended language of Oracle. It is primarily used to manage and manipulate databases. One of the most frequently utilized SQL functions is the MIN() function. This powerful aggregate function is essential for finding the sm
    6 min read
  • SUM() Function in SQL Server
    The SUM() function in SQL Server is an essential aggregate function used to calculate the total sum of values in a numeric column. It aggregates data by summing up all values in the specified column for the rows that match the criteria of the query. In this article, We will learn about SUM() Functio
    3 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