SQL - Self Join
SQL - Self Join
htm
As we can see in the figure below, the information regarding the colors assigned and a
color each employee picked is entered into a table. The table is joined to itself using self
join over the color columns to match employees with their Secret Santa.
Self Join is a type of inner join, which is performed in cases where the comparison
between two columns of a same table is required; probably to establish a relationship
between them. In other words, a table is joined with itself when it contains both
Foreign Key and Primary Key in it.
Unlike queries of other joins, we use WHERE clause to specify the condition for the
table to combine with itself; instead of the ON clause.
1 of 6 12/4/2024, 4:51 PM
SQL - Self Join https://www.tutorialspoint.com/sql/sql-self-joins.htm
Syntax
SELECT column_name(s)
FROM table1 a, table1 b
WHERE a.common_field = b.common_field;
Here, the WHERE clause could be any given expression based on your requirement.
Example
Self Join only requires one table, so, let us create a CUSTOMERS table containing the
customer details like their names, age, address and the salary they earn.
Open Compiler
Now, insert values into this table using the INSERT statement as follows −
Open Compiler
2 of 6 12/4/2024, 4:51 PM
SQL - Self Join https://www.tutorialspoint.com/sql/sql-self-joins.htm
Now, let us join this table using the following Self Join query. Our aim is to establish a
relationship among the said Customers on the basis of their earnings. We are doing this
with the help of the WHERE clause.
Open Compiler
Output
The resultant table displayed will list out all the customers that earn lesser than other
customers −
3 of 6 12/4/2024, 4:51 PM
SQL - Self Join https://www.tutorialspoint.com/sql/sql-self-joins.htm
Syntax
SELECT column_name(s)
FROM table1 a, table1 b
WHERE a.common_field = b.common_field
ORDER BY column_name;
4 of 6 12/4/2024, 4:51 PM
SQL - Self Join https://www.tutorialspoint.com/sql/sql-self-joins.htm
Example
Let us join the CUSTOMERS table with itself using self join on a WHERE clause; then,
arrange the records in an ascending order using the ORDER BY clause with respect to a
specified column, as shown in the following query.
Open Compiler
Output
5 of 6 12/4/2024, 4:51 PM
SQL - Self Join https://www.tutorialspoint.com/sql/sql-self-joins.htm
Not just the salary column, the records can be sorted based on the alphabetical order of
names, numerical order of Customer IDs etc.
6 of 6 12/4/2024, 4:51 PM