The Wayback Machine - https://web.archive.org/web/20241105021946/https://www.geeksforgeeks.org/how-to-compare-columns-in-two-different-tables-in-sql/
Open In App

How to compare columns in two different tables in SQL

Last Updated : 28 Apr, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 tables in SQL. We will understand each concept with the help of examples. 

Step-1: Creating database :
To create the database use the following SQL query as follows.

Syntax  –

create database_name;

Example –

create STUDENTS_DATA

Step-2: Using the database :
To use this database as follows.

Syntax –

use database_name;

Example –

use STUDENT_DATA

Step-3: Creating table :
Creating Table for making queries as follows.

Table-1: Syntax – 

create table table_name
(
column1 type, 
column2 type, 
... 
);

Example –

create table studentData1 
(
roll_number int primary key, 
firstname varchar(100), 
lastname varchar(100), 
marks int
);

Step-4: Inserting records :
Inserting records in table studentData1 as follows.
Syntax –

insert into table_name(column1, column2 ...) values (value1, value2 ...);

Inserting into studentData1 table –

insert into studentData1 (roll_number, firstname, lastname, marks) 
values (1, 'albert', 'einstein',356);
insert into studentData1 (roll_number, firstname, lastname, marks) 
values (2, 'isaac', 'newton',412);
insert into studentData1 (roll_number, firstname, lastname, marks) 
values (3, 'marie', 'curie',436);
insert into studentData1 (roll_number, firstname, lastname, marks) 
values (4, 'philip', 'jsam',389);
insert into studentData1 (roll_number, firstname, lastname, marks) 
values (5, 'tom', 'jsam',452);
insert into studentData1 (roll_number, firstname, lastname, marks) 
values (6, 'tucker', 'jose',412);
insert into studentData1 (roll_number, firstname, lastname, marks) 
values (7, 'drawn', 'caste',389);

Step-5: Creating table2 :
Here, we will create the studentData2 using SQL query as follows.

create table studentData2 
(
id int primary key, 
firstname varchar(100), 
lastname varchar(100), 
marks int
);

Step-6: Inserting records :
Inserting records in the table studentData2 as follows.

insert into studentData2 (id, firstname, lastname, marks) 
values (2, 'isaac', 'newton',412);
insert into studentData2 (id, firstname, lastname, marks) 
values (3, 'marie', 'curie',436);
insert into studentData2 (id, firstname, lastname, marks) 
values (6, 'tucker', 'jose',412);
insert into studentData2 (id, firstname, lastname, marks) 
values (4, 'philip', 'jsam',389);

Example-1 :
Using the where clause to compare columns of two different tables. It cannot handle the null values.
Syntax :
(to select all the records with all columns)

select * from table1, table 
where 
table1.col1 = table2.col2 and table1.col1 > someValue;

Syntax(Alternative) :
(to select specific columns from the tables)

select t1.col1, t2.col2,t3. col3 ...., t2.col1, t2.col2, t2.col3....  
from table1 t1, table t2 where t1.col1 = t2.col2 and t1.col1 <> t2.col2;

Query –

select * from studentData1, studentData2 
where studentData1.roll_number = studentData2.id;

Output :
Result based on the comparison of roll_number and id as follows.

roll_number firstname lastname marks id
2 isaac newton 412 2
3 marie curie 436 3
4 philip jsam 389 4
6 tucker jose 412 6

Example-2 :
Using joins to compare columns by priority among the table. For example, left join returns all values from the first table and null value for the not-matched records from the second table. Similarly, we can use right join, inner join, full join and self join as per our requirements. In the below example we have compared two tables based on the columns roll_number and id using the left join.

Syntax –

select t1.col1, t1.col2... , t2.col1, t2.col2... , 
from table1 as t1 left 
join table2 as t2 on 
tabe1.col1 = table2.col1;

Query –

select a.roll_number, a.firstname, b.id 
from studentData1 as a left 
join 
studentData2 as b on 
a.roll_number = b.id;

Output :
Join based on left table i.e. sutdentData1 as follows.

roll_number firstname id
1 albert  
2 isaac 2
3 marie 3
4 philip 4
5 tom  
6 tucker 6
7 drawn  

Example-3 :
UNION allows us to compare two same types of tables or datasets. We can use union to compare the columns once we can have the union of both the tables. It can quickly check what are the data missing or changed in either table. It is capable of handling null values which cannot be handled by where clause.

Note – 
This is only used when we have the same type of tables.

Syntax –

select col1, col2, col3 ....  
from (select col1, col2, col3 ... 
from Table1 union all select col1, col2, col3 ... 
from Table2) 
cmpr order by ID;

Example –

select * from 
(select * from studentData1 
where roll_number > 4 
union all 
select * from studentData2 where id < 6) 
cmpr order by marks;

Output :
Compared same records where roll_number > 4 and id < 6 as follows.

roll_number firstname lastname marks
7  drawn caste 389
4 philip jsam 389
6 tucker jose 412
3 marie curie 436
5 tom jsam 452


Similar Reads

How to Compare Data in All Tables in Two Different Databases in Oracle?
Oracle is a versatile database and it is highly secured and hence to a large extent used in banking and insurance applications. Though NoSQL database dominates in many industries, still oracle has its own significance because most the legacy applications still like to go with oracle like RDBMS only. Distributed systems will have the usage of 2 or m
2 min read
How to Compare Indexes of Tables From Two Different Databases in Oracle?
Structured Query Language supported by RDBMS(Relation Database Management Systems) such as Oracle, Mysql, PostgreSQL, and SQL Server. All relational database system support objects such as databases, tables, schema, indexes, views, functions, procedures, and many more. RDBMS system performs best when the schema is on write. To make these systems pe
3 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 named “geeks” then we will create two tables “departme
3 min read
How to Compare Two Columns For Equality in SQL Server?
In SQL, problems require us to compare two columns for equality to achieve certain desired results. This can be achieved through the use of the =(equal to) operator between 2 columns names to be compared. For this article, we will be using the Microsoft SQL Server as our database. Syntax: SELECT * FROM TABLE_NAME WHERE COLUMN1_NAME=COLUMN2_NAME;The
2 min read
How to Compare Rows and Columns in the Same Table in SQL
In this article, we are going to see how we can compare the rows and columns of the same table in SQL. We will be taking a few examples to see how we can do this in different ways. To create the database: Syntax : CREATE database_name;CREATE Shopping To use this database: Syntax : USE database_name;USE Shopping Creating Table for making queries: Sy
2 min read
SQL - SELECT from Multiple Tables with MS SQL Server
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we consider table1 contains m rows and table2 contains n
3 min read
SQL Server | Convert Tables in T-SQL into XML
XML (Extensible Markup Language) is a widely-used markup language designed to store and transfer structured data between different systems and platforms. While HTML focuses on the visual representation of data OverviewXML is similar to HTML which is designed to structure and store data for sharing across different systems and platforms.Unlike HTML,
3 min read
Show the Rows That Are Different Between Two Tables or Queries
Structured Query Language (SQL) is a common database language for building, managing, and retrieving data from relational databases such as MySQL, Oracle, and others.Here we are going to see how to get the Rows That Are Different Between Two Tables or Queries. Here, we will first create a database named “geeksdb” then we will create two tables “Gee
2 min read
SQL Query to Combine Two Tables Without a Common Column
In most of the queries in the learning process, we usually use to join those tables which have some common columns or relationships between them. But when it comes to real-life problems, then such easiest conditions are rarely found. Complex tasks like joining two tables without a common column is majorly found. Let's first have a look at our table
3 min read
How to Append Two Tables and Put the Result in a Table 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, SQL Server, PostGre, etc. In this article, we will learn how to append two tables and store the result into a new table using UNION, UNION ALL. UNION: Syntax: SELECT column_one, column
2 min read
How to Pull Data From Two Tables SQL Based on Date?
In this article, we will see, How to write SQL queries to pull data from two tables based on date. We can perform the above function by performing the UNION operation on the tables. UNION operation appends the results of two queries and returns the result as a single set. Ways to use the UNION keyword: UNION ALL: Includes duplicates.UNION: Excludes
2 min read
How to Update Two Tables in One Statement in SQL Server?
To update two tables in one statement in SQL Server, use the BEGIN TRANSACTION clause and the COMMIT clause. The individual UPDATE clauses are written in between the former ones to execute both updates simultaneously. Here, we will learn how to update two tables in a single statement in SQL Server. SyntaxUpdating two tables in one statement in SQL
3 min read
How to Querying Two Tables For Duplicate Values in SQL?
When working with relational databases, it's common to identify duplicate values across multiple tables. SQL provides efficient ways to query such data using different techniques. In this article, we demonstrate how to query two tables for duplicate values using two methods such as the INNER JOIN and the WHERE clause. These methods help filter reco
4 min read
How to Compare Two Queries in SQL
Queries in SQL :A query will either be an invitation for data results from your info or for action on the info, or each. a question will provide you with a solution to a straightforward question, perform calculations, mix data from totally different tables, add, change, or delete data from info. Creating a Database :We use CREATE DATABASE command t
2 min read
Compare SQL Server Results of Two Queries
SQL Server is a versatile database, and it is the most used Relational Database that is used across many software industries. In this article, let us see the comparison of SQL Server Results of Two Queries briefly. By using Azure Data Studio, let us see the concepts by starting with creating the database, table creation, locks, etc., Azure Data Stu
5 min read
SQL Query to Compare Two Strings
SQL stands for Structured Query Language. It is used to communicate with the database. There are some standard SQL commands like 'select', 'delete', 'alter' etc. To compare two strings in SQL Server, there is no direct way. In this article, we will learn how to compare two strings in an MS SQL server and we will provide some examples. A string func
2 min read
SQL Query to Compare Two Dates
In SQL, dates are complicated for newbies, since while working with the database, the format of the date in the table must be matched with the input date in order to insert. In various scenarios instead of date, DateTime (time is also involved with date) is used. Here we will see, SQL Query to compare two dates. This can be easily done using equals
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 have a table given below: NAMECOLLEGEROLL NUMBERSUB
2 min read
Joining three or more tables in SQL
There may occur some situations sometimes where data needs to be fetched from three or more tables. This article deals with two approaches to achieve it. Example: Creating three tables: student marks details Note: Click on image if not clear to view in bigger size. Table 1: student create table student(s_id int primary key, s_name varchar(20)); ins
3 min read
Copy tables between databases in SQL Server using Import-and-Export Wizard
Introduction to Import-and-Export Wizard : The wizard allows easy steps through a process, and to execute the data copy process with writing very little or no code. However, for importing and exporting data from one source into another, the below steps could be followed - Open the Object Explorer, select the database, right-click on the database na
2 min read
SELECT data from Multiple Tables in SQL
The statement is used to retrieve the fields from multiple tables and with the help of JOIN operations we easily fetch the records from multiple tables, Generally JOINS are used when there are common records between two tables. In this article, we will look into various types of JOIN that are used in SQL. SQL JoinsSQL joins combine two or more tabl
3 min read
How to Left Join Multiple Tables in SQL
Left Join is one of the Keywords used while writing queries in SQL. In SQL we normally use Join for the purpose of forming a new table by taking out common data like rows or records or tuples from both the tables which are having matching records in general. Here when it comes to Left Join in SQL it only returns all the records or tuples or rows fr
3 min read
Joining 4 Tables in SQL
The purpose of this article is to make a simple program to Join two tables using Join and Where clause in SQL. Below is the implementation for the same using MySQL. The prerequisites of this topic are MySQL and the installment of Apache Server on your computer. Introduction :In SQL, a query is a request with some instruction such that inserting, re
3 min read
Querying Multiple Tables in SQL
Here, we are going to see how to query multiple tables in SQL. For example, here, we will first create a database named “geeks” then we will create 2 tables “department” and "employee" in that database. After, that we will execute our query on the tables. Creating a Database : Use the below SQL statement to create a database called geeks: CREATE DA
2 min read
SQL Query to select Data from Tables Using Join and Where
The aim of this article is to make a simple program to Join two tables using Join and Where clause using MySQL. Below is the method to do the same using MySQL. The prerequisites of this article are MySQL and Apache Server on your computer are installed. What is a Query in SQL? A SQL query is a request passed for data/information from a table in a d
3 min read
Magic Tables in SQL Server
Magic tables are the temporary logical tables that are created by the SQL server whenever there are insertion or deletion or update( D.M.L) operations. The recently performed operation on the rows gets stored in magic tables automatically. These are not physical table but they are just temporary internal tables. These magic tables can't be retrieve
3 min read
SQL Query to DELETE Certain Rows Based on Comparisons with Other Tables
In this article, we will see, how to delete certain rows based on comparisons with other tables. We can perform the function by using a subquery in place of the condition in WHERE Clause. A subquery is a query that appears inside another query. It can also be called a nested query. Syntax: SELECT * FROM table_name WHERE column_name= ( SELECT column
2 min read
System Tables in SQL
In addition to the user-defined table, we have the option to work with various unique sorts of tables in addition to the fundamental user-defined table. System Tables are a unique class of tables that the SQL Server Engine uses to hold data that can be accessed through system views regarding the configurations and objects of SQL Server instances. T
4 min read
How to Retrieve Data from Multiple Tables in SQL?
In SQL, Retrieving data from multiple tables is a common requirement in database operations. In this article, we will explore multiple approaches to retrieving data from multiple tables in SQL. We will provide an introduction to the topic, explain two distinct approaches with their respective syntax, present detailed examples for each approach with
4 min read
How to Implement Relationships While Designing Tables in SQL?
In database design, understanding and implementing relationships between entities is crucial. These relationships, such as one-to-one, one-to-many, and many-to-many, establish connections between tables using key constraints. Let's explore each type of relationship with examples and SQL implementation. One-to-One RelationshipIn this relationship, e
7 min read
Article Tags :
three90RightbarBannerImg