05 October 2016 Sudhanshu Ranjan 1.41k

Get manager name in employee table mostly asked in interview question

Mostly this question asked by interviewer to find the manager name of employee in employee table.

Today I am going to describe how to write the query to find the manager name of employee.

At first I am creating an Employee table and insert some dummy records into it. Please refer to the  CREATE and INSERT statements below:

CREATE TABLE [dbo].[Employee](
	[EmployeeId] [int] NULL,
	[EmployeeName] [varchar](50) NULL,
	[ManagerId] [int] NULL

Insert some data in table

INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [ManagerId]) VALUES (1, N'Sudhanshu Ranjan', 7)
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [ManagerId]) VALUES (2, N'Ravi Ranjan', 1)
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [ManagerId]) VALUES (3, N'Shashi', 1)
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [ManagerId]) VALUES (4, N'Amit', 9)
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [ManagerId]) VALUES (5, N'Nilesh Dubey', 7)
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [ManagerId]) VALUES (6, N'Ananta Patra', 2)
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [ManagerId]) VALUES (7, N'Arun Gupta', 9)
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [ManagerId]) VALUES (8, N'Pankaj', 9)
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [ManagerId]) VALUES (9, N'Niraj Roy', 7)
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [ManagerId]) VALUES (10, N'Suman', NULL)

Employee table data

Now we have some data in table.

Here is SQL Query to find the manager name.

SELECT A.EmployeeName AS 'Employee Name',B.EmployeeName AS 'Manager Name' FROM Employee AS A LEFT JOIN Employee AS B
ON B.EmployeeId=A.ManagerId

In above query we are using left join to find the manager name.


I hope this post would be helpful for you. Please feel free to leave your comments below in case if you have any suggestion or if you have better optimized solution.

You can share at :

About Author
Sudhanshu Kumar Ranjan | Lead Engineer at HCL Technologies | Expertise in Microsoft Technology | Author | Blogger | Programmer
Know More
Connect with him on Facebook | Google+ | LinkedIn | Twitter

Recommended Post

Leave a comment

About Dotnet Cube

It's my blog - Dotnet Cube, where you will learn and get solutions about programming, web designing and development. I started this website to share my knowledge and experience which might help someone.

You can get more details about me and my blog at About Us page.

Subscribe Newsletter

Subscribe to our monthly newsletter to get the latest industry news, Media Group updates and our current specials.

Follow On Us...

Home | About | Advertise | Copyrights | Privacy | Contact | Admin

Copyrights © 2015-2019 dotnetcube.com. All rights reserved