Compute a Difference(Delta) Between Two Columns on Different Rows in PL/SQL
Last Updated :
30 Apr, 2024
Calculating the difference between two columns is useful in data analysis. It can help identify trends in various sectors such as finance, healthcare, and inventory management. It can also be used to analyze day-to-day changes in stock prices, and medical diagnoses, and identify bottleneck products.
In this article, we are going to explore different ways to compute a difference(delta) between two columns on different rows in PL/SQL. We will go through various real-world use cases with some clear and concise examples.
Compute a Difference(Delta) Between Two Columns on Different Rows in PL/SQL
We will use a very basic and easy approach. We will try to make it as simple as possible. We will start our PL/SQL block by defining our cursor. This cursor will store the basic table's information with its delta. Then in the same cursor, we will use JOIN() to join our table's current row with the same table's next row. Through this, we can simply calculate the difference by subtracting the next column from the previous column values.
In our next step, we will move to our main BEGIN block. In this block, we will open our defined cursor and display the corresponding values. At the end, we will close our cursor.
Let's set up an Environment
To understand how to Compute a Difference(Delta) Between Two Columns on Different Rows in PL/SQL we need a table on which we will perform our approach and examples related to it. Here we will consider a table called ‘Geeksforgeeks’ which contains information such as id, name, and score as Columns.
id | name | score |
---|
1 | Vishu | 200 |
2 | Aayush | 300 |
3 | Neeraj | 500 |
4 | Sumit | 800 |
5 | Vivek | 1200 |
Examples of Computing Differences Between Columns on Different Rows
In this, we will see various examples related to how to compute a difference between two columns on different rows in PL/SQL.
Example 1: Computing the difference between two scores in different rows without any condition.
As specified earlier, we will use a cursor to store our table's necessary information such as id, score, and difference. We will join the table with the table itself but with the row with an id+1. Through this, we can easily compute the difference between the two scores. Then, we will enter our main block and open our created cursor and we will display all the information stored in the cursor stored earlier. At the end, we will close our cursor.
Query:
DECLARE
--defining our cursor and storing the tables information along with is delta value.
CURSOR delta_info IS
SELECT g1.id, g1.score, g1.score - g2.score AS delta
FROM geeksforgeeks g1
-- joining the table geeksfirgeeks with current row with a row with id+1
JOIN geeksforgeeks g2 ON g1.id = g2.id + 1;
-- defining our variables
v_id NUMBER;
v_score NUMBER;
v_delta NUMBER;
BEGIN
-- displaying the column headeres
DBMS_OUTPUT.PUT_LINE('id | score | delta');
DBMS_OUTPUT.PUT_LINE('------------------');
--opening the cursor
OPEN delta_info;
LOOP
FETCH delta_info INTO v_id, v_score, v_delta;
EXIT WHEN delta_info%NOTFOUND;
-- displaying the necessary infromation with delta value
DBMS_OUTPUT.PUT_LINE(v_id||' |'|| v_score || ' | ' || v_delta );
END LOOP;
--closing the cursor
CLOSE delta_info;
END;
Output:
id | Score | delta |
---|
2 | 300 | 100 |
3 | 500 | 200 |
4 | 800 | 300 |
5 | 1200 | 400 |
Explanation: In the above image, as we can see there is no data for id 1. This is because there is no previous value to id 1. So we have nothing to calculate the delta between two scores of different rows. We can also see that all the scores are displayed with their corresponding delta values. As we know that id 1 has a 200 score and id 2 has a 300 score. So its delta difference is 100 and we can see that all the rows have done the same calculation for their delta values. You can refer to the above-displayed output to have a more clear understanding of the output.
Example 2: Computing difference between two scores in different rows with a specified condition (odd id's).
We will use a similar approach to calculate the delta. The difference is that, in this example, we will specify a condition in the statement. We will calculate the delta for some specific id's such as odd id's (say 1,3,5). Lets see the query for more clearer understanding.
Query:
DECLARE
--defining our cursor and storing the tables information along with is delta value.
CURSOR delta_info IS
SELECT g1.id, g1.score, g1.score - g2.score AS delta
FROM geeksforgeeks g1 ,geeksforgeeks g2 WHERE g1.id = g2.id + 2 and g1.id IN (1,3,5);
-- joining the table geeksfirgeeks with current row with a row with id+1
-- defining our variables
v_id NUMBER;
v_score NUMBER;
v_delta NUMBER;
BEGIN
-- displaying the column headeres
DBMS_OUTPUT.PUT_LINE('id | score | delta');
DBMS_OUTPUT.PUT_LINE('------------------');
--opening the cursor
OPEN delta_info;
LOOP
FETCH delta_info INTO v_id, v_score, v_delta;
EXIT WHEN delta_info%NOTFOUND;
-- displaying the necessary infromation with delta value
DBMS_OUTPUT.PUT_LINE(v_id||' |'|| v_score || ' | ' || v_delta );
END LOOP;
--closing the cursor
CLOSE delta_info;
END;
Output:
id | score | delta |
---|
3 | 500 | 300 |
5 | 1200 | 700 |
Explanation: In the above query, we have incremented the id with +2. This will help us to get the odd id's only. As we can see in the output table, for id 1 score is 200, and for id 3 score is 500. Their difference is 300. Same for id 5, (1200-500 ) 700 is displayed. We have made a little modification in our query, in lines 5 and 6. You can refer to the output table and query, for more clearer understanding.
Conclusion
Overall, computing a difference(delta ) between two columns on different rows has many advantages and real-life use cases. It is used in various such as finance sectors, medical sectors, and many more. In different sectors, it is very important to have a brief look at the fluctuation of data. Through this query, we can easily calculate this fluctuation.
In this article, we have seen how we can calculate the delta between two columns on different rows with and without condition. PL/SQL, being a procedural extension of SQL provides us the flexibility to write our custom scripts. We have seen various examples with their respective explanations. Now you can write queries related to it and can get the desired result.
Similar Reads
Compute a Difference (Delta) Between Two Columns on Different Rows in SQL Server
Delta computation is a process used in SQL Server to derive the difference between values in a specific column across different rows within the same table. This method is important for analyzing historical data stored in relational databases and allowing users to gain insights by comparing data attr
5 min read
Compute a Difference (Delta) Between Two Columns on Different Rows
MySQL is an open-source, Relational Database Management System that stores data in a structured format using rows and columns. Itâs software that enables users to create, manage, and manipulate databases. Similar to SQL we use queries to store and access data in the MySQL databases. In this article,
6 min read
Compute a Difference (Delta) Between Two Columns on Different Rows in postgreSQL
In PostgreSQL the modern relational database system, two types of queries are supported: SQL for the traditional relational databases and JSON for the non-relational databases. It is free and anybody can use it. The difference (delta) computation between the values of two columns of PostgreSQL at di
5 min read
Compare and Find Differences Between Two Tables in SQL
Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, etc. Here we are going to see how to Compare and Find Differences Between Two Tables in SQL Here, we will first create a database name
3 min read
How to compare columns in two different tables in SQL
Here we are going to see how we can compare the columns of two different tables in SQL. We will be taking a few examples to see how we can do this in different ways. Overview :In this, we will understand overview of SQL query for required operation to perform How to compare columns in two different
4 min read
Find the Difference Between Two Rows in Pandas
Finding the difference between two rows in Pandas typically involves calculating how values in columns change from one row to the next i.e the difference in sales data from past month to current month. This task is especially important in time-series data or datasets where temporal progression, rank
4 min read
How to Efficiently Convert Rows to Columns in PL/SQL?
In Oracle PL/SQL, converting rows into columns is a common operation, especially useful for reporting, data analysis, and reformatting data for easy visualization. PL/SQL, or Procedural Language/Structured Query Language, is a powerful procedural extension to SQL, created by Oracle, that integrates
5 min read
Difference Between Distinct and Group By in PL/SQL
In PL/SQL, knowing the difference between DISTINCT and GROUP BY is important for working with data effectively. Although DISTINCT and GROUP BY might seem similar, they serve different purposes. In this article, we'll explore DISTINCT and GROUP BY Clause with the syntax and various examples along the
5 min read
Difference of two columns in Pandas dataframe
Difference of two columns in pandas dataframe in Python is carried out by using following methods : Method #1 : Using â -â operator. Python3 import pandas as pd # Create a DataFrame df1 = { 'Name':['George','Andrea','micheal', 'maggie','Ravi','Xien','Jalpa'], 'score1':[62,47,55,74,32,77,86], 'score2
2 min read
Difference Between Cube and Rollup in SQL Server
In SQL Server, both ROLLUP and CUBE are sub-clause of the GROUP BY clause and are used in conjunction with aggregate functions to produce summary reports. It helps to generate multiple group sets using the hierarchy. To enhance the capabilities of grouping and aggregation, SQL Server provides two po
3 min read