EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MySQL Tutorial MySQL Self Join
Secondary Sidebar
MySQL Tutorial
  • Joins
    • Joins in MySQL
    • MySQL Outer Join
    • Left Outer Join in MySQL
    • MySQL Self Join
    • Natural Join in MySQL
    • MySQL DELETE JOIN
    • MySQL Update Join
    • MySQL Cross Join
  • Basic
    • MySQL floor
    • MySQL DESCRIBE table
    • MySQL encryption
    • Introduction to MySQL
    • Is SQL Server a Database?
    • What is MySQL
    • Is MySQL Programming Language
    • MySQL Server
    • MySQL Community Server
    • How To Install MySQL
    • MySQL Versions
    • MySQL OpenSource
    • MySQL GUI Tools
    • MySQL Grant
    • MySQL Error 1064
    • MySQL Drop Database
    • MySQL not equal
    • MySQL SELECT INTO Variable
    • MySQL Commands
    • MySQL Operators
    • What is MySQL Schema
    • Wildcards in MySQL
    • MySQL Constraints
    • MySQL Administration
    • MySQL Data Type
    • MYSQL COMMIT
    • MySQL FORMAT
    • Timestamp to Date in MySQL
    • MySQL DATEDIFF
    • MySQL?Incremental Backup
    • MySQL JSON Data Type
    • MySQL ENUM
    • MySQL Default Port
    • Cheat Sheet MySQL
  • Queries
    • MySQL Queries
    • MySQL Query Commands
    • SELECT in MySQL
    • MySQL INSERT IGNORE
    • MySQL having
    • ORDER BY in MySQL
    • MySQL Cheat Sheet
    • MySQL ORDER BY Random
    • MySQL ORDER BY DESC
    • MySQL GROUP BY
    • MySQL GROUP BY Count
    • MySQL GROUP BY month
    • MySQL WHERE Clause
    • MySQL WITH
    • MySQL FETCH
    • MySQL DDL
    • MySQL DML
    • MySQL WHERE IN Array
    • MySQL Fetch Array
    • MySQL ISNULL
    • MySQL Index Types
    • Mysql? Export Schema
    • Amazon RDS for MySQL
    • MySQL greatest
  • Database
    • What is Data Modeling
    • What is Data Processing
    • DBMS Architecture
    • DBMS Keys
    • Careers in Database Administration
    • What is MySQL Database
    • MySQL Relational Database
    • How to Connect Database to MySQL
    • MySQL Database Repair
    • RDBMS Interview Questions
    • DBMS Interview Questions
  • Functions
    • MySQL Function
    • MySQL Aggregate Function
    • MySQL String functions
    • MySQL Date Functions
    • MySQL Window Functions
    • MySQL Math Functions
    • MySQL Boolean
    • Cursor in MySQL
    • Condition in MySQL
    • MySQL BETWEEN
    • Insert in MySQL
    • MySQL IFNULL()
    • MySQL TIMESTAMPDIFF()
    • MySQL COALESCE()
    • MySQL count()
    • MIN() in MySQL
    • MySQL Numeric
    • MySQL field()
    • MySQL FIND_IN_SET()
    • MySQL avg()
    • MySQL MAX() Function
    • MySQL BIN()
    • MySQL Concat
    • MySQL DECODE()
    • MySQL REGEXP_REPLACE()
    • MySQL Asynchronous
    • MySQL innodb_buffer_pool_size
    • MySQL key_buffer_size
    • MySQL TRUNCATE()
    • MySQL ROW_NUMBER()
    • NOT in MySQL
    • MySQL IN Operator
    • LIKE in MySQL
    • ANY in MySQL
    • MySQL NOT IN
    • MySQL CHECK Constraint
    • MySQL DISTINCT
    • MySQL ALL
    • MySQL Union
    • MySQL UNION ALL
    • MySQL EXISTS
    • MySQL ON DELETE CASCADE
    • MySQL REGEXP
    • MySQL Index
    • MySQL Add Index
    • MySQL REINDEX
    • MySQL UNIQUE INDEX
    • MySQL Clustered Index
    • MySQL? InnoDB Cluster
    • Table in MySQL
    • ALTER TABLE MySQL
    • MySQL Temporary Table
    • MySQL Clone Table
    • MySQL Repair Table
    • MySQL Lock Table
    • MySQL Optimize Table
    • TRUNCATE TABLE MySQL
    • MySQL Table Dump
    • MySQL Update Set
    • MySQL ALTER TABLE Add Column
    • MySQL RANK()
    • MySQL CTE
    • MySQL LAG()
    • MySQL GROUP_CONCAT()
    • MySQL EXTRACT()
    • MySQL REPLACE
    • MySQL AUTO_INCREMENT
    • MySQL SYSDATE()
    • MySQL NULLIF()
    • MySQL Substring
    • MySQL SUBSTRING_INDEX()
    • MySQL LOWERCASE
    • MySQL Row
    • MySQL NOW
    • MySQL CEIL
    • MySQL Alias
    • MySQL Trigger
    • MySQL SHOW Triggers
    • MySQL UPDATE Trigger
    • MySQL DELETE Trigger
    • MySQL AFTER UPDATE Trigger
    • MySQL Stored Procedure
    • ROLLUP in MySQL
    • MySQL? INSTR()
    • MySQL Subquery
    • MySQL Timestamp
    • MySQL? Hour()
    • MySQL MOD()
    • MySQL DATE_FORMAT()
    • ALTER Column in MySQL
    • MySQL Rename Column
    • MySQL Interval
    • MySQL CURDATE
    • MySQL BIT
    • MySQL Binlog
    • MySQL Average
    • MySQL TEXT
    • MySQL SHOW
    • MySQL Offset
    • MySQL Timezone
    • mysql_real_escape_string
    • MySQL Datetime
    • MySQL DATE_SUB()
    • MySQL FULLTEXT
    • MySQL DATE_ADD()
    • MySQL sum()
    • MySQL Merge
    • MySQL BigInt
    • MySQL ROUND
    • MySQL VARCHAR
    • MySQL Decimal
    • MySQL Limit
    • MySQL today()
    • MySQL WEEKDAY
    • MySQL Split
    • MySQL Create Function
    • MySQL BLOB
    • MySQL encode()
    • MySQL Primary Key
    • MySQL Foreign Key
    • Unique Key in MySQL
    • MySQL Drop Foreign Key
    • MySQL DROP TRIGGER
    • MYSQL Database
    • Delete Database MySQL
    • MySQL Root
    • MySQL Root Password
    • MySQL Client
    • MySQL Users
    • MySQL?User Permissions
    • MySQL add user
    • MySQL List User
    • MySQL Show Users
    • MySQL User Password
    • MySQL?Cardinality
    • MySQL Workbench
    • MySQL Backup
    • MySQL REVOKE
    • MySQL Dump
    • MySQL Cluster
    • MySQL Partitioning
    • MySQL Full Text Search
    • MySQL Admin Tool
    • MySQL Export Database
    • MySQL Export to CSV
  • Advanced
    • MySQL Formatter
    • MySQL TINYINT
    • MySQL Grant All Privileges
    • MySQL DROP TABLE
    • MySQL rename database
    • MySQL Flush Privileges
    • MySQL super Privilege
    • MySQL Character Set
    • MySQL Log File
    • MySQL Flush Log
    • Grant Privileges MySQL
    • MySQL WHILE LOOP
    • IF Statement in MySQL
    • MySQL CASE Statement
    • MySQL IF Function
    • MySQL IF EXISTS
    • MySQL UUID
    • Views in MySQL
    • MySQL Replication
    • MySQL Partition
    • Toad for MySQL
    • Navicat for MySQL
    • MySQL AES_Encrypt
    • MySQL Performance Tuning
    • MySQL Transaction
    • MySQL? sort_buffer_size
    • MySQL? Sync
    • MySQL? Query Cache
    • MySQL Collation
    • MySQL ODBC Driver
    • MySQL Partitioning
    • MySQL InnoDB
    • MySQL Float vs Decimal
    • MySQL Union vs Union All
  • Interview Questions
    • MySQL Interview Questions

Related Courses

MS SQL Certification Courses

Oracle Certification Courses

PL/SQL Certification Courses

MySQL Self Join

By Aanchal SharmaAanchal Sharma

MySQL Self Join

Introduction to MySQL Self Join

MySQL Self JOIN is an SQL statement that is used to intersect or join 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 to combine records within a table based on a certain conditional expression. This type of joining of records with other records in the same table when a condition is matched is also called as a Unary relationship. Specially, here the Foreign key that exists in the table refers to the tables own Primary Key.

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.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax:

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

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,171 ratings)

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

Here, T1 and T2 are two aliases used for the same table named Table A in the database and the WHERE clause denotes any given conditional expression.

How MySQL Self Join works?

  • 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.
  • Thus, there is a requirement of any relationship between the rows data that is stored in the table to apply the Self Join in MySQL within the same 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. However, the ‘Marketing’ is not displayed because the name is filtered out by the Inner Join clause as Reports to column is NULL with no value to match the condition applied.

Example #2 – MySQL Self Join using Left Join Clause

Since the Marketing titled person has no Manager and is not included in the above result set but in the Left Join, we can display it even if it has no value for Manager.

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, the Marketing person is provided with ‘Top Manager’ as ‘Manager’ as its value for Reports To was NULL.

Example #3 – Use MySQL Self Join 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 – Use MySQL Self Join 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

Hence, we can say that a Self-Join in MySQL takes a ‘Selfie’ to itself but producing results considering the table as two using an alias so that the table name is not repeated twice which may produce 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

This is a guide to MySQL Self Join. Here we discuss the introduction, examples, and how MySQL Self Join works with proper code and output? You may also have a look at the following articles to learn more –

  1. Joins in PostgreSQL
  2. Joins in Oracle
  3. Hive Group By
  4. What Is Oracle Database
  5. ANY in MySQL | Examples
  6. Examples of MySQL Subquery
Popular Course in this category
MySQL Training Program (12 Courses, 10 Projects)
  12 Online Courses |  10 Hands-on Projects |  92+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

MS SQL Training (16 Courses, 11+ Projects)4.9
Oracle Training (14 Courses, 8+ Projects)4.8
PL SQL Training (4 Courses, 2+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

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

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

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

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

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

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

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

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more