---
title: "Find the sum of digits of a number in PL/SQL."  
description: "Find the sum of digits of a number in PL/SQL."  
author: "Revati S Misra"  
published: 2023-04-04  
updated: 2023-04-19  
canonical: https://www.mindstick.com/forum/157685/find-the-sum-of-digits-of-a-number-in-pl-sql  
category: "database"  
tags: ["database", "mysql", "sql server", "plsql"]  
reading_time: 2 minutes  

---

# Find the sum of digits of a number in PL/SQL.

Find the [sum of digits](https://www.mindstick.com/forum/158772/write-a-python-program-to-calculate-the-sum-of-digits-in-a-given-number) of a number in PL/SQL.

## Replies

### Reply by Aryan Kumar

```php
DECLARE
 num NUMBER := 12345;
 sum NUMBER := 0;
BEGIN
 WHILE (num > 0) LOOP
   sum := sum + MOD(num, 10);
   num := TRUNC(num / 10);
 END LOOP;

 DBMS_OUTPUT.PUT_LINE('The sum of digits is ' || sum);
END;
```

In this code, the variable **num** is assigned the value of the number whose digits we want to sum, and the variable **sum** is initialized to 0. The code uses a while loop to extract the digits of the number one by one and add them to the sum.

### Reply by Krishnapriya Rajeev

Given below is the program to find the [sum](https://www.mindstick.com/forum/159332/how-can-i-use-sum-in-linq) of digits of a program using pl/sql.

```plaintext
set serveroutput on
declare		//
 declaring all variables
n number;
sum number:=0;
i number;

begin

n:=123;		// initializig variables
i:=0;
while i<n LOOP
    r := MOD(n, 10);	// finding last digit of the number
    sum := sum + r; 	// adding last digit to the sum
    n := Trunc(n / 10); // removing last digit of the number
end LOOP;
dbms_output.put_line('Sum of digits of number '||n||' is '||sum||'.');
end;
/
# OUPUT - Sum of digits of number 123 is 6.
```

This program uses a loop to find the last digit of a number by calculating the remainder when the number is divided by 10. After finding the remainder, it adds it to the sum and removes the digit in the unit's place by dividing the number by 10. This process is repeated until the number becomes less than or equal to 0. Finally, the program returns the sum as the result of the calculation.


---

Original Source: https://www.mindstick.com/forum/157685/find-the-sum-of-digits-of-a-number-in-pl-sql

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
