Welcome to Appsloveworld Technologies, In this session, we’ll talk about self join, which is nothing but joining a table with itself, will also talk about self joined classification and Purpose of Self-Join.
Most of the people think self-join is a different type of join altogether, which is not true. Self-join can be classified as inner, outer, cross join depending on how you write the self join.
Before continuing with the session. I strongly recommend reading SQL join tutorial first. In this post, we have already discussed how to join different tables.
What is Self Join?
If you look at the table here that we have, it has got three columns, EmpId, EmployeeName, and Manager_Id.
Now let’s say I want you to write a query which gives me an output like this. I want the employee’s name as well as his manager’s name.
If you need SQL script to create these two tables, you can find the script at end of the post.
Now if you look at the table on the left-hand side, if you look at Michael, Michael’s manager ID is 5 and you take this 5 and look up in the employee ID column, 5 is Grayson.
That’s means Michael’s manager is Grayson and along the same lines, if you look at Jackson, his manager ID 6 and you take this 6 and look up in the employee ID column 6 is Gabriel.
so Jackson’s manager is Gabriel. So if you look at the situation here, we are using the Manager_Id column and looking up in the employee ID column within the same table, which means we are referencing the same table.
You can say that i want a sql query to get the employee name and their manager name from the same table.
If we want this kind of output like employee name and manager’s name, there is a need to join this employee table with itself.
Now you might be wondering how can we join the same table with itself. if you look at below query, we have done exactly the same thing.
How to get the employees with their managers from the same table?
Select Emp.EmployeeName as Employee, Mng.EmployeeName as Manager
from TblEmployeeManager Emp
Left Join TblEmployeeManager Mng
On Emp.Manager_Id = Mng.EmpId
So if you look at the output, we want the employee name and the manager’s name. So select employee name, manager name will come to those in the column list, in the select clause.
Query Explanation:
If you look at the form clause, we are saying TblEmployeeManager and we are giving it a table alias Emp and we are saying, join this table left join, we are doing a left join with TblEmployeeManager again.it can be inner join left join whatever.
So select whatever columns you want from TblEmployeeManager give it an alias emp join with the same table TblEmployeeManager and give it another alias Mng, emp for the employee, mng for the manager.
So you can assume now we have two instances of this table and one for employee and then another table like the manager Table.both of the structures will be identical and you’re basically referencing the same table.
And then what you are doing is in the employee table, take the managerId column in the employee table, take the manager Id column and look up the employee ID in the manager’s table, which is nothing but another copy of the same table. and then from the employee table, which is nothing but emp I want the name which is nothing but the employee name.
So I’m giving it alias as an employee and from the manager’s table, I’m getting the name which is nothing but the manager’s name.So that’s how we get this output.
But if you look at the join here, we are joining with the same table. So this is nothing but a self-join.
So when we execute this query, we get the output as we expect.
Get List all employee’s names and their managers by manager name using an inner join
As we know that inner join, will only give the matching rows between the two tables.When we were using left join, we were getting Anthony’s record as well and we get 9 rows.
but when I change it to an inner join.
Select Emp.EmployeeName as Employee, Mng.EmployeeName as Manager
from TblEmployeeManager Emp
Inner Join TblEmployeeManager Mng
On Emp.Manager_Id = Mng.EmpId
Now, when I execute this one, look at what’s going to happen. I only get 8 rows. what happens to the record. It’s not retrieved anymore. Why? Because if you look at Anthony’s record, the managerId does not match with any of the employee Id.
There is no matching record. And if you remember, the inner join will only give you the matching records between the two tables.
Now, you might be wondering where are two tables here? But remember, in the join, we are joining this table with itself. So we are treating a single table like two tables.So you can call this as an inner self join.
why is it called a self join? because you are joining the same table with itself and you are doing an inner join, inner self join.
So along the same lines, you can do it right outer self join and full outer self join. So a self-join is not a different type of join all together. It can be classified under any type of join,inner-outer,left, right, and cross join as well.
Cross join in SQL example employee manager
Select Emp.EmployeeName as Employee, Mng.EmployeeName as Manager
from TblEmployeeManager Emp
Cross Join TblEmployeeManager Mng
So if you want to convert this into a cross, join the first thing you have to do, get rid of the on the clause, and then convert inner join into the cross join. That’s about it. Since we are joining the same table with itself, we call it, you know, a self join .But since we are using cross join, it’s called Let’s Cross Self Join.
OK, now remember in the TblEmployeeManager, we’ve got 9 rows. And if you remember from the definition of the cross, join when you do across, join between two tables, you’ll get the Cartesian product i.e 9*9=81 rows as shown in image.
Let’s say we want to write a SQL query to display all employees under each manager. Let’s say we need to get all employees starting from ManagerId=7 i.e from the super manager.
;WITH QueryResult (Manager_Id, EmpId, LEVEL)
AS
(
SELECT DISTINCT Manager_Id, EmpId AS EmployeeId, 0 AS LEVEL
FROM TblEmployeeManager
UNION ALL
SELECT tbl.Manager_Id, tbl.EmpId, LEVEL + 1 AS LEVEL
FROM TblEmployeeManager tbl
INNER JOIN QueryResult T
ON tbl.Manager_Id = T.EmpId
WHERE tbl.Manager_Id <> tbl.EmpId
)
SELECT DISTINCT EmpId, Manager_Id, LEVEL FROM QueryResult ORDER BY Manager_Id
Sql Table Script
--Self join Table
CREATE TABLE [dbo].[TblEmployeeManager](
[EmpId] [int] IDENTITY(1,1) NOT NULL,
[EmployeeName] [nvarchar](max) NULL,
[Manager_Id] [int] NULL,
CONSTRAINT [PK_TblEmployeeManager] PRIMARY KEY CLUSTERED
(
[EmpId] ASC
)
)
GO
SET IDENTITY_INSERT [dbo].[TblEmployeeManager] ON
GO
INSERT [dbo].[TblEmployeeManager] ([EmpId], [EmployeeName], [Manager_Id]) VALUES (1, 'Michael', 5)
GO
INSERT [dbo].[TblEmployeeManager] ([EmpId], [EmployeeName], [Manager_Id]) VALUES (2, 'Jackson', 6)
GO
INSERT [dbo].[TblEmployeeManager] ([EmpId], [EmployeeName], [Manager_Id]) VALUES (3, 'Jacob', 6)
GO
INSERT [dbo].[TblEmployeeManager] ([EmpId], [EmployeeName], [Manager_Id]) VALUES (4, 'Luke', 5)
GO
INSERT [dbo].[TblEmployeeManager] ([EmpId], [EmployeeName], [Manager_Id]) VALUES (5, 'Grayson', 8)
GO
INSERT [dbo].[TblEmployeeManager] ([EmpId], [EmployeeName], [Manager_Id]) VALUES (6, 'Gabriel', 9)
GO
INSERT [dbo].[TblEmployeeManager] ([EmpId], [EmployeeName], [Manager_Id]) VALUES (7, 'Anthony', NULL)
GO
INSERT [dbo].[TblEmployeeManager] ([EmpId], [EmployeeName], [Manager_Id]) VALUES (8, 'Lincoln', 7)
GO
INSERT [dbo].[TblEmployeeManager] ([EmpId], [EmployeeName], [Manager_Id]) VALUES (9, 'Ryan', 7)
GO
The post What is SELF JOIN ? with Realtime Example appeared first on Software Development | Programming Tutorials.
Read More Articles
- Linq to SQL Group by and Sum in Select | Linq To SQL Group By and Sum
- How send an HTTP POST request to a server from Excel using VBA?
- What is Difference between where and having clauses in SQL server
- How to Use EXCEPT Operator with an example in Sql
- How to use merge statement in the SQL server
- How to write Re-runnable SQL server query
- How to create Cursor in sql server with example
- How to generate random data in sql server for performance testing
- How to write subquery in select statement in Sql
- How to Log record changes in SQL server in an audit table
- # in SQL Query
- Troubles creating assembly in MS SQL Server
- two triggers on insert of same table
- restore from differential backup file to a new server with multiple files
- Joining multiple tables with same identifier & pulling in a field based on shared identifier
- find row number by group in SQL server table with duplicated rows
- SQL Select Where date in (Jan and March) but not in Feb
- SQL Summary of Status total values by Month of Type2 SC Dimension
- Passing operator as a parameter in stored proc while preventing the risk of SQL injection
- How does SQL Server Update rows with more than one value?
- Fail to run sp_prepare over ADODB from Visual Basic
- Publishing Local DB Changes to Remote DB SQL Server 2012
- SQL Server Insert Varbinary
- Update table using stored procedure
- Return multiple tables from a T-SQL function in SQL Server 2008
- provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified No fix?
- Create a new database problem
- What is a good practice for save value in database int or char?
- How to pass a DateTime from NodeJS Sequelize to MSSQL
- How to use transaction with typed dataset in C#?
- Combine two table for one output sql query
- Insert Multiple Images into a Image column in sql server
- SQL: Delete all nested self referencing records
- Recursive CTE Problem
- Find all table names with column name?
- I can not restore my database SQL Server Management Studio can't recognize my .bak files
- How to specify custom sorting order for primary key in Sql Server
- How do I update tables in SQL so that related strings match?
- SQL Query Performance Optimization
- How to ensure independency of a database copy in SQL Server Management Studio?
- Unexpected error converting text to date in SQL Server
- Include data in resultset not fulfilling the filter condition without using temp tables
- How to avoid a column if it contains null without mentioning its name
- Convert decimal number to INT SQL
- Data migration from MySQL to SQL Server is taking huge time using pandas library
- Using cursor in OLTP databases (SQL server)
- How to get sum of first three rows then next three rows in a new column
- Way to find data of a sql table with same status for consecutive 3 days
- Optimising SQL involving IF EXISTS
- staircase behavior with pivoted data
- Is a JOIN more/less efficient than EXISTS IN when no data is needed from the second table?
- Compare TWO tables with same schema for data differences
- Sql Server 2008 express recursive query
- Need a tweak in SQL Server
- Add 1 for to a field for every record in table
- How to generate script for my database and tables in SQL Server
- SQLBulkCopy causing deadlock
- Database login failed for user
- Find Root disk Path with SQL query
- TransactionScope locking table and IsolationLevel
- Select N random records in SQL Server without repetition
- Insert values from same table is it possible?
- Getting the Id of a row I updated in Sql Server
- How to speed up current query with index
- SET statement considers 0 as null
- Use SQL Server database in ASP.Net without server installation?
- Select the lowest n values from a group
- How to detect READ_COMMITTED_SNAPSHOT is enabled?
- SQL Server: how to add case statement to select
- Deleting duplicate row that has earliest date
- SQL Server - cannot select rows with Sum > 0
- Who was called?
- performance difference between User Defined Function and Stored Procedures
- SQL Server : there are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key 'FK'
- SQL Server Compiling and Calculating Data from Multiple Tables
- cancel an sql server query from SSMS
- Data Sync between tables from SQL Server & Db2 - how to delete rows
- Connect to Docker SQL Server 2017 Container on MAC OSX via SQL Operations Studio
- Dynamic WHERE condition SQL SERVER
- No direct access to data row in clustered table - why?
- SQL Server, Returning a summed data set grouped by a single column for a merge query
- Calculate free time Slots from reservation table
- PHP CLI not picking up changes to freetds.conf for ODBC connection
- How to remove repeated add log from table?
- A connection was successfully established with the server, but then an error occurred during the pre-login handshake / Login process
- Who is accesing my sql table?
- Create a non-clustered index in Entity Framework Core
- Sql convert string of numbers to int
- How come the only value ever entered in the SQL Server field is 0?
- SQL Server efficiently filter rows where times are not near another table's times
- Slow performance of Latitude/Longitude conversion in query
- procedure to take information from one table and write to another table
- Row is listed twice in simple query
- How to update a db table field with a looping sequence of numbers (2-4)
- Update Column based on Bulk insert from CSV SQL
- Sql Server doing a full table scan when first field in PK has few distinct values
- How to get sum of numbers using SQL query in ASP.NET C#?
- Error - "Invalid attempt to read when no data is present." while using SQLDataReader even if data is present
- CASE Expression with T-SQL
- Can in-memory tables be added to a database diagram
- How to get all records having maximum value in a SQL Server table
- How do I replicate data from the Common Data Service to SQL Server on Azure?
- Help with recursive query
- Is it possible to manipulate xml in a column?
- DrillThrough in SSRS
- SQL - Using a Trigger to occasionally allow row deletions
- Connecting to database and getting some info from db in Katalon Studio
- How to reuse selection result in SQL SERVER PROCEDURE
- How can I lock a table on read, using Entity Framework?
- JBoss cluster with Apache, AJP change's date eventualy
- Generate SessionID based on given rules using SQL
- Not able to use DESC command in SQL Server 2012 Management Studio
- Transaction in function sql server 2012
- how to set insert string values in sql server?
- Zend_Db_Select order by random, compatible in mssql / mysql
- SQL: using case when to change column values
- how to check if stored procedure exists or not in sql server using c# code
- Arithmetic overflow error...Please Help. SQL
- How to assign null value in datetime field
- How to save MSSQL query output to .txt or .json file?
- Extract the name of a Database which is used in a view (refering other Database)
- Sending dbmail with a query result with an okay format
- my c# code throws an exception on accessing sql server
- Calculator vs SQL Server giving different results
- SQL: Split comma separated string list with a query?
- How do I map a column to uppercase in .NET 4.5 C# Entity Framework 6 using both Oracle and SQL Server?
- Change report data visibility based on rendering format in Reporting Services
- extract data with minimum time difference between each 2 samples
- How to add a third piece to a "Case" statement
- Automatically create database compare scripts and execute
- SQL Server big amout of data in one or more tables
- What is the fastest way to query from a historical EAV database
- No sum() with null values
- Loops in SQL to create table
- Choosing proper database for a few users application
- SQL Server 2008 resolving localhost to a computer name
- SQLBulkCopy inserts using Entity Framework with Foreign Key object
- parametrization in VBScript/ASP Classic and ADO
- Get the remaining days between two dates
- How to select data from 2 tables and convert NULL to 0?
- SQL Server : inserting Player vs Player names in to new table from tblEntrants
- Create different filegroup for different Schema
- sp_send_dbmail Column Header Format Issue (Incorrect syntax near '@Column1Name')
- why my node js is not getting connected to sql server?
- C# SQL Geometry Error: Invalid operator for data type. Operator equals equal to, type equals geometry
- Crosstab multi columns
- SQL Server: Issue with BETWEEN clause
- ColdFusion 9.01 -> Lucee 5.3.3.62 and <cfinsert> / <cfupdate>
- con.Open() fails exception Transactions with IsolationLevel Snapshot cannot be promoted
- Cannot use Stored Procedure in SQL Server 2012 within VS2013 Report Designer, always returns blank?
- SQL Function for averaged time elapsed between variables when it's over 24 hours
- sql server graph query, find all paths to node
- Integration tests Entity Framework, need for a different database server?
- Is SQL Server smart enough not to UPDATE if values are the same?
- Which DB driver to use DbVisualiser with Azure SQL?
- Trimming any Leading or trailing characters
- Data rows plus totals row in a single scan
- How to retrieve data from a SQL Server database in C#?
- Combining Columns With Different Filters
- TFS 2012 backup database restore in TFS 2014