AdBlock Detected!
Our website is made possible by displaying ads to our visitors. Please supporting us by whitelisting our website.
SQL Self Join |
|
SQL > SQL JOIN >
Self Join
Earlier we have examined the different types of joins in SQL such as inner join, outer join, left outer join, and cross join. In all the examples, we joined on two different tables. Can we write a SQL query that joins a table to itself? The answer is a definitive YES. When we join a table to itself, it's called a self join. A SQL self join joins a table to itself using two different aliases, allowing you to compare rows within the same table — commonly used for calculating rankings, finding hierarchies, or detecting related records.
We join a table to itself when we want to find information that is contained in the table, but cannot be easily retrieved via a simple SELECT statement. For example, to find the rank of a row of data in a table, we used self join to find the rank of each row in a table. In that particular example, we have a table, Total_Sales, which has two columns: Name and Sales. To find the rank of each person based on the amount of sales, we use the following SQL: Please notice that in this case, we joined the table to itself. We are really treating this as though there are two different tables, even though these two tables have the same structure, same data, and same name. Frequently Asked Questions
|
Our website is made possible by displaying ads to our visitors. Please supporting us by whitelisting our website.