How to Compare Rows and Columns in the Same Table in SQL
Last Updated :
20 Dec, 2024
In SQL, comparing rows and columns in the same table is a common task for data analysis, identifying relationships, and calculating differences. By using techniques like self-joins and conditional queries, we can extract meaningful insights from a single table. This enables efficient querying, allowing database administrators and developers to address various analytical and operational needs effectively.
In this article, we will explore how to compare rows and columns in SQL with examples to demonstrate various approaches. With practical demonstrations and explanations, we will learn how to make the most out of these techniques in real-world scenarios.
Examples of Compare Rows and Columns in SQL
Let’s start by creating a sample table named orders with data to use in our examples. This table will include details like order_id
, order_date
, amount
, customer
, and city
. These fields allow us to explore various SQL comparison techniques effectively.
Query:
CREATE TABLE orders (
order_id INT AUTO_INCREMENT PRIMARY KEY,
order_date DATE,
amount INT,
customer VARCHAR(50),
city VARCHAR(50)
);
INSERT INTO orders(order_date, amount, customer, city) VALUES
('2020-10-01',100, 'john', 'london'),
('2020-10-02',125,'philip', 'ohio'),
('2020-10-03',140,'jose', 'barkley'),
('2020-10-04',160, 'tom', 'north carolina');
('2020-11-02',128,'duck', 'ohio'),
('2020-09-04',150, 'tucker', 'north carolina');
SELECT * FROM orders;
Output
orders tableExample 1: Comparing Rows in the Same Table
In the example, we compare rows to calculate the daily sales difference by subtracting the amount
values of consecutive orders. This technique helps analyze trends or changes in sales over time by evaluating adjacent rows in the table.
Syntax
SELECT column_name(s)
FROM table1 t1 INNER JOIN table1 t2
on t1.column1 = t2.column1;
Query:
SELECT g1.order_id, g1.order_date,g1.amount,
(g2.amount - g1.amount) AS daily_amount
FROM orders g1
INNER JOIN orders g2
ON g2.order_id = g1.order_id + 1;
Output

Explanation:
- The query uses a self-join to compare the
amount
of one row with the amount
of the next row.
- The difference is calculated as
g2.amount - g1.amount
.
Example 2: Comparing Columns in the Same Table
Comparison of columns in the same table is possible with the help of joins. Here we are comparing all the customers that are in the same city using the self join in SQL. Self-join is a regular join where a table is joined by itself. Similarly, a table may be joined with left join, right join, inner join, and full join.
Syntax
SELECT column_name(s)
FROM table1 t1, table1 t2
WHERE condition1 and condition2 ... ;
Query:
SELECT A.customer AS CustomerName1, B.customer AS CustomerName2, A.city
FROM orders A, orders B
WHERE A.order_id <> B.order_id
AND A.city = B.city
ORDER BY A.city;
Output

Explanation:
- The self-join is used to find rows where
city
matches across different order_id
s.
- The condition
A.order_id
<>
B.order_id
ensures that we are comparing different rows.
Example 3: Comparing Amounts Between Rows
In this example, we are comparing all the order_id where the amount of the first order_id is greater than the amount of the second order_id's amount. We are using the self join to perform this comparison of columns in the same table.
Query:
SELECT A.customer AS CustomerName1, B.customer AS CustomerName2,
A.order_id AS order_id_1, B.order_id AS order_id_2, A.amount AS Amount_by_1,
B.amount AS Amount_by_2, (A.amount - B.amount) AS difference
FROM orders A, orders B
WHERE A.order_id <> B.order_id
AND A.amount > B.amount;
Output

Explanation:
- This query identifies rows where
amount
in one row is greater than amount
in another.
- The
difference
column shows the numerical difference between the two amounts.
Conclusion
By using techniques like self-joins and conditional comparisons, SQL makes it easy to compare rows and columns within the same table. These methods are essential for advanced data analysis, finding trends, and identifying unique patterns within a dataset. Mastering these approaches not only enhances our ability to query data efficiently but also provides powerful tools for maintaining data integrity, improving insights, and making informed decisions based on our SQL database
Similar Reads
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
SQL Query to Find the Number of Columns in a Table
SQL stands for a structure query language, which is used in the database to retrieve data, update and modify data in relational databases like MySql, Oracle, etc. And a query is a question or request for data from the database, that is if we ask someone any question then the question is the query. S
4 min read
How to Get the Datatype of Table Columns in MySQL?
When working with MySQL databases, knowing the datatype of table columns is essential to maintain data integrity and avoid errors. This guide covers methods to check column datatypes, such as using SHOW COLUMNS and querying INFORMATION_SCHEMA.COLUMNS. Understanding column datatypes helps in designin
4 min read
How to Remove Duplicate Values Based on Only One Column of the Table in SQL?
In SQL, managing duplicate records is a crucial task for maintaining data integrity. Often, we may encounter scenarios where there are duplicate rows based on a single column, and it becomes necessary to remove duplicates to ensure accuracy and efficiency. In this article, we will explain how to del
3 min read
How to Perform SQL Join on Multiple Columns in Same Table?
To perform a SQL JOIN on multiple columns in the same table, we use the Self Join. This technique allows us to create connections between different columns of the same table by comparing them directly. We can implement a Self Join using various types of joins such as âinner,â âleft,â âright,â âfull,
4 min read
How to Select Row With Max Value on a Column in SQL?
SQL is a powerful language for managing and handling relational databases. A common requirement in database management is to retrieve rows where a specific column has the maximum value. Here, we will look at different ways to do this, depending on different situations and database environments. This
5 min read
How to Select Rows from a Table that are Not in Another Table?
In MySQL, the ability to select rows from one table that do not exist in another is crucial for comparing and managing data across multiple tables. This article explores the methods to perform such a selection, providing insights into the main concepts, syntax, and practical examples. Understanding
3 min read
How to Check if a Column Exists in a SQL Server Table?
In this article, we will look at how to check if a particular column exists in a database table or not. For checking the existence of a column we need to create the table first. So, let us create a table with some columns and data. Creating table: Syntax: CREATE TABLE table_name ( column1 datatype,
2 min read
SQL Query to Convert Rows to Columns in SQL Server
In this article we will see, how to convert Rows to Column in SQL Server. In a table where many columns have the have same data for many entries in the table, it is advisable to convert the rows to column. This will help to reduce the table and make the table more readable. For example, Suppose we h
2 min read
How to Convert Rows into Columns in MySQL?
Converting rows into columns, also known as pivoting or transposing, is a common operation in DBMS, and MySQL provides robust functionality for achieving this transformation. This process is useful to reshape data for better analysis or reporting. This guide will explore the syntax, usage, and examp
3 min read