Abdul Wahab Abdul Wahab - 2 months ago 16
SQL Question

How to join duplicate column name in joins ms sql server?

I have two tables, one is

Employee
and other one is
Dept
.
Employee
table has columns, which are
ID
,
Name
,
DeptId
and
Dept
table has columns,
ID
,
DeptName
.
Now if write a query:

Select ID, Name, ID, DeptName
from Employee
Inner Join Dept
On Employee.DeptID = Dept.ID


It gives me error because it doesn't find ID columns so How do I uniquely define columns?

Answer

Just include explicit aliases to distiguish the ID column in the Employee table from the ID column in the Dept table. Actually, it is best practice to always refer to a column by an alias when doing a join, so your query should look something like this:

SELECT e.ID AS employeeID,
       e.Name,
       e.DeptId,
       d.ID AS deptID,
       d.DeptName
FROM Employee e
INNER JOIN Dept d
    ON e.DeptID = d.ID