Abdul Wahab Abdul Wahab - 2 months ago 12
SQL Question

How to join duplicate column name in joins in SQL Server?

I have two tables, one is

Employee
and other one is
Dept
.

The
Employee
table has columns which are
ID
,
Name
, and
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


I get an error because it doesn't know which
ID
column I mean. 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