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
SQL Interview Questions Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970's, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
SQL Tutorial SQL is a Structured query language used to access and manipulate data in databases. SQL stands for Structured Query Language. We can create, update, delete, and retrieve data in databases like MySQL, Oracle, PostgreSQL, etc. Overall, SQL is a query language that communicates with databases.In this S
11 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
SQL Joins (Inner, Left, Right and Full Join) SQL joins are fundamental tools for combining data from multiple tables in relational databases. Joins allow efficient data retrieval, which is essential for generating meaningful observations and solving complex business queries. Understanding SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JO
6 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
ACID Properties in DBMS In the world of DBMS, transactions are fundamental operations that allow us to modify and retrieve data. However, to ensure the integrity of a database, it is important that these transactions are executed in a way that maintains consistency, correctness, and reliability. This is where the ACID prop
8 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read