EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Data Science Data Science Tutorials MySQL Tutorial MySQL Self Join
 

MySQL Self Join

Aanchal Sharma
Article byAanchal Sharma
EDUCBA
Reviewed byRavi Rathore

Updated May 11, 2023

MySQL Self Join

 

 

Introduction to MySQL Self Join

The MySQL Self JOIN is an SQL statement that joins or intersects a table in the database to itself. Basically, a JOIN function combines two or more tables in SQL, but here Self Join is a regular Join that allows combining records within a table based on a certain conditional expression. We can refer to the act of joining records with other records in the same table, when a condition is matched, as a Unary relationship. Especially, here the Foreign key that exists in the table refers to the table’s own Primary Key.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

This means that a table row will join with every other row under a condition and this process is queried by a Self-Join SQL command. This Self Join in MySQL is a special kind of Join that is useful to query the hierarchical data and comparing records in the rows within a table. In the SQL statement query, we use Inner Join or Left Join Clauses with the Self Join to return a result set using any condition that satisfies. This is because it is difficult to refer more than one query for the same table. So, we have to use a different table alias to add a different name for the table when we use Self Join in MySQL otherwise the query displays an error when executed.

Syntax:

Following is the basic syntax of Self Join query in MySQL:

SELECT A.Column_Name, B.Column_Name,….FROM TableA T1, TableA T2 WHERE A.Common_Field = B.Common_Field;

In the database, there is a table named Table A that is assigned two aliases, T1 and T2. The WHERE clause specifies a conditional expression for filtering the results.

How does MySQL Self Join work?

  • In MySQL, Self-Join is important to query ordered data by comparing rows in the same table. The SQL query for Self-Join is applied in a table to itself showing as if there are two tables where using temporary names as alias for the same table in SQL statement.
  • Therefore, the main application of this query in MySQL is when we have a table reference data rows in itself. Suppose, we have a table named Employee and there is a Supervisor_ID column that refers to the employee which is the head of the current employees in any particular company.
  • To apply Self Join in MySQL within the same table, there must be a relationship between the rows of data stored in the table.
  • Let us consider a table named Persons with columns (PersonID, Name, Contact, Address, City).
  • Suppose, we want to match persons that are from the same city in the table then, we use the following SQL Statement for Self-Join command in MySQL:
SELECT A.Name AS Name1, B.Name AS Name2, A.City FROM Persons A, Persons B WHERE A.PersonID <> B.PersonID AND A.City = B.City ORDER BY A.City;

Examples of MySQL Self Join

Given below are the examples of MySQL self Join: Let us consider a table named Persons.

Example #1 – MySQL Self Join using Inner Join Clause

Let us create a table Persons and insert some data as a sample to execute the query on them using Self Join in MYSQL with the following SQL commands:

CREATE TABLE Persons (PersonID int NOT NULL PRIMARY KEY, LastName varchar(255) NOT NULL, FirstName varchar(255), ReportsTo int, Title varchar(255));

Output:

MySQL Self Join - 1

Now, let us fetch the whole organization structure details. We are joining the Person table with itself based on the PersonID and ReportsTo column from the table which determines the job title with employees.

SELECT CONCAT (a.LastName, ', ', a.FirstName) AS Manager, CONCAT(b.LastName, ', ', b.FirstName) AS 'Direct Reporting' FROM persons b INNER JOIN persons a ON a.PersonID = b.ReportsTo ORDER BY Manager;

Output:

MySQL Self Join - 2

The result set will define the table of Persons with two different roles: ‘Manager’ and ‘Direct Reporting’ and only those employees who have a manager. The Inner Join clause filters out the name and does not display ‘Marketing’ because the Reports to the column is NULL, and the applied condition does not have a value to match.

Example #2 – MySQL Self Join using Left Join Clause

It is possible to display the person with the Marketing title even if they have no value for manager. This is because they are not included in the above result set, owing to the Left Join.

SELECT IFNULL (CONCAT (a.LastName, ', ', a.FirstName), 'Top Manager') AS 'Manager', CONCAT(b.LastName, ', ', b.FirstName) AS 'Direct report' FROM Persons b LEFT JOIN Persons a ON a.PersonID = b.ReportsTo ORDER BY Manager DESC;

Output:

Left Join Clause

Here, we can assign the value of ‘Top Manager’ to the Marketing person as its ‘Manager’ since the value for ‘Reports To’ was NULL.

Example #3 – Use for comparing successive rows

For example, let us use Self Join in MySQL to fetch the rows by comparing the records within the same table. Let us consider another table named ‘Customer_Data’ with fields (ID, name, Age, Address, Salary) for this SQL query:

comparing successive

The SQL statement is as follows:

SELECT k.ID, l.Name, k.Salary FROM customer_data k, customer_data l WHERE k.Salary < l.Salary;

Output:

MySQL Self Join - 5

Example #4 – With Inner Join for comparing successive rows

We have taken the ‘Customers’ table with fields (CustomerID, Name, CustomerNum, Payment_purpose, Amount, City) as an example or sample table to run the query using Self Join and comparing the rows in the table.

successive rows

Here, the list of persons from Customers table is fetched who are located in the same city by joining the table to itself and using comparing operators like <,> and = for City column.

SELECT c1.city, c1.Name, c2.Name FROM customers c1 INNER JOIN customers c2 ON c1.city = c2.city AND c1.Name > c2.Name ORDER BY c1.city;

Output:

MySQL Self Join - 7

You can see there the result table a city column and two Name columns which contain different names of customers residing in the same place or city using the Join conditions where:

  • city = c2.city ensures that both customers have the same city.
  • Name > c2.Name ORDER BY c1.city checks that no same name of customers are included in the result rows.

Thus, likewise, we can apply it to fetch results from the same table under certain joining predicates and using Inner or Left Joins as well as comparison operators to query correct data from the table in the database.

Conclusion

In MySQL, a Self-Join takes a ‘Selfie’ of itself and produces results by considering the table as two using an alias to avoid repeating the table name twice, which could result in an error. This type of regular join is useful for modeling an organized structure data form from a table and also allows comparing the rows and does needful to produce the required result.

Recommended Articles

We hope that this EDUCBA information on “MySQL Self Join” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. Joins in PostgreSQL
  2. Joins in Oracle
  3. ANY in MySQL | Examples
  4. Examples of MySQL Subquery

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - 🎁 ENROLL NOW