How to Perform SQL Join on Multiple Columns in Same Table?
Last Updated :
12 Dec, 2024
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,” or “cartesian” join.
This article will explore how to effectively use a Self Join to connect multiple columns within the same table, making it easier to analyze complex data relationships.
Performing SQL Join on Multiple Columns
This section demonstrates the process of joining multiple columns in a single table using Self Join. It includes the creation of a table, data insertion, and queries to retrieve and analyze employee information across departments and locations.
Step 3: Create a Table.
Create a table CORPORATE inside the database GeeksForGeeks. This table has 4 columns namely 'E_NAME', 'E_ID', 'E_DEPT', and 'E_LOC' containing the name, id, department, and location of various employees.
Query:
CREATE TABLE CORPORATE(
E_NAME VARCHAR(10),
E_ID INT,
E_DEPT VARCHAR(10),
E_LOC VARCHAR(10)
);
Step 5: Insert Data into the Table
This step involves inserting sample data into the CORPORATE table. The data represents employees who may work in multiple departments or locations, setting up the conditions to demonstrate Self Join later.
Query:
INSERT INTO CORPORATE VALUES('RAM',1,'HR','DELHI');
INSERT INTO CORPORATE VALUES('RAM',1,'SALES','DELHI');
INSERT INTO CORPORATE VALUES('VARUN',2,'IT','BANGALORE');
INSERT INTO CORPORATE VALUES('VARUN',2,'MARKETING','HYDERABAD');
INSERT INTO CORPORATE VALUES('RAVI',3,'FINANCE','KOCHI');
INSERT INTO CORPORATE VALUES('RAVI',3,'FINANCE','TRIVANDRUM');
Step 6: Display All Rows of the Table
To verify the inserted data, use the SELECT query to fetch all rows. This ensures the data is correctly populated in the CORPORATE table.
Query:
SELECT *
FROM CORPORATE;
Output
CORPORATE tableStep 7: Perform Self Join to Retrieve Specific Employee Details
Retrieve the details of all the employees who have worked in at least 2 departments and at least 2 locations. Use of AS for making 2 aliases of the table CORPORATE with C1 and C2 for comparing the IDs, departments, and locations of the employees.
Query:
SELECT C1.E_NAME,C1.E_ID,C1.E_DEPT,C1.E_LOC
FROM CORPORATE AS C1, CORPORATE AS C2
WHERE C1.E_ID=C2.E_ID
AND C1.E_DEPT<>C2.E_DEPT
AND C1.E_LOC<>C2.E_LOC;
Output
Self Join to retrieve specific Employee Details
Explanation:
- The result shows that VARUN has worked in two different departments and two different locations. RAM and RAVI are not displayed because they do not meet both criteria.
- Here RAM is not displayed although he has worked at 2 different departments as his location was the same. Similarly, RAVI is not displayed although he has worked at 2 different locations as his department was the same.
Step 8: Display Distinct Employee Names
To display just the name(s) of the employees who have worked in at least 2 departments and at least 2 locations, use SELECT just for the E_NAME column and keep that is DISTINCT to avoid redundant rows. Only VARUN appears in the result as he meets the criteria of working in different departments and locations
Query:
SELECT DISTINCT (C1.E_NAME)
FROM CORPORATE AS C1, CORPORATE AS C2
WHERE C1.E_ID=C2.E_ID
AND C1.E_DEPT<>C2.E_DEPT
AND C1.E_LOC<>C2.E_LOC;
Output
Points to remember
- A self join is used to join a table to itself, allowing for comparison within the same table.
- Self joins can utilize inner, left, right, full, or cartesian joins.
- Use table aliases to differentiate between the instances of the table in the join.
Conclusion
In this article, we have covered how to join multiple columns in a table using SQL, specifically focusing on the Self Join method. By understanding how to use the LIKE operator and the Self Join technique, we can effectively filter data based on patterns and analyze relationships between the same table’s columns. This is a crucial skill for SQL beginners and professionals working with complex data sets, as it allows for more advanced queries and better data management practices.
Similar Reads
How to join on multiple columns in Pyspark?
In this article, we will discuss how to join multiple columns in PySpark Dataframe using Python. Let's create the first dataframe: Python3 # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app
3 min read
SQL Query for Matching Multiple Values in the Same Column
Querying multiple values within a single column is a vital skill in SQL, enabling users to filter and retrieve data based on specific criteria. Whether we're working with large datasets or simple tables, mastering techniques like the IN clause, LIKE operator, and comparison operators (e.g., >=) e
4 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
3 min read
How to Alter Multiple Columns at Once in SQL Server?
In SQL, sometimes we need to write a single query to update the values of all columns in a table. We will use the UPDATE keyword to achieve this. For this, we use a specific kind of query shown in the below demonstration. For this article, we will be using the Microsoft SQL Server as our database an
3 min read
How to SELECT DISTINCT on Multiple Columns in SQL?
In the world of databases, data duplication can lead to confusion and inefficiency. SQL provides a powerful tool, SELECT DISTINCT, to retrieve unique values from columns. However, when dealing with multiple columns, the approach becomes more detailed. In this article, we will explain how to use SELE
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. Efficiently combining data from different tables allows developers to create complex queries and extract valuable insights from interconnected datasets. In this article, we will explore multiple approaches t
5 min read
How to Query Multiple Tables in SQL
SQL (Structured Query Language) is a powerful tool for managing and querying relational databases. One of its most valuable features is the ability to query multiple tables simultaneously, allowing us to retrieve and integrate related data efficiently. In this article, we will explain how to query m
4 min read
How to Retrieve Data from Multiple Tables in PL/SQL
PL/SQL is âProcedural Language extensions to the Structured Query Languageâ. SQL is a popular language for both querying and updating data in relational database management systems (RDBMS). PL/SQL adds many procedural constructs to SQL language to overcome some limitations of SQL. In addition, PL/SQ
5 min read
How To Update Multiple Columns in MySQL?
To update multiple columns in MySQL we can use the SET clause in the UPDATE statement. SET clause allows users to update values of multiple columns at a time. In this article, we will learn how to update multiple columns in MySQL using UPDATE and SET commands. We will cover the syntax and examples,
3 min read
How to Update Multiple Columns in Single Update Statement in SQL?
The SQL UPDATE statement is a important operation for modifying existing records in a database table. It allows us to change the values of one or more columns in a table based on specific conditions. In many cases, we may need to update multiple columns in a single operation to keep our data consist
4 min read