What is Self Join in SQL ?
In the previous section, we have discussed what is joining and its types, in this section we will discuss the rest of the types.
Self-join in SQL:
Sometime
we need to retrieve rows of the same table by applying some constraints to its
fields. In these types of cases, self-join is the best option. It is the type of
join in which one table is joined with itself depending on some condition that
is specified in WHERE CLAUSE, means that the rows of the same table are compared
for generating results. So self-join is used to merge the rows of the same
table by matching them. There might be an error while writing the Query of self-join
if the user will use the same table name twice after FROM keyword, so for resolving
that problem we can use the different Alias
of the same table.
Syntax of Self Join:
SELECT column_name(N)
FROM table1 T 1 , table1 T 2
WHERE condition;
Here T1 and T2 are the aliases of table1. So suppose we have Students
table.
Example of Self-join:
For example, if there is a student table and it
has the column CR (class representative) so we can apply the self-join to
extract the data of students along with their CR. In this case, we suppose that Std_Id
has the primary key and CR is the FOREIGN KEY that takes REFERENCE from Std_Id PK. So Foreign keys can have duplicate values. So we can apply the
self join in the table in which according to one specific column (in this case
Std_Id) we can have duplicate values in another column (in this case CR column)
and we can join the table on the basis of these two columns. So as we know the
class representative can represent more than one student of the class so we
can apply the self-join query on Students table.
Proctor name is a new column that is generated as the result of self-join. hope so self-join is concept is cleared. keep learning.
Comments
Post a Comment
your feedback is valuable.