If you’re getting an error that reads something like “The objects “employees” and “employees” in the FROM clause have the same exposed names. Use correlation names to distinguish them’” in SQL Server, it could be that you’re trying to do a self-join without assigning table aliases.
When doing self-joins, we need to provide aliases for the tables so that SQL Server can distinguish between each instance.
To fix this issue, be sure to use unique table aliases in your query.
Example of Error
Here’s an example of code that produces the error:
SELECT
employees.employee_id,
employees.first_name AS employee_first_name,
employees.last_name AS employee_last_name,
employees.first_name AS manager_first_name,
employees.last_name AS manager_last_name
FROM
employees
LEFT JOIN
employees ON employees.manager_id = employees.employee_id
ORDER BY
employees.employee_id;
Output:
Msg 1013, Level 16, State 1, Line 1
The objects "employees" and "employees" in the FROM clause have the same exposed names. Use correlation names to distinguish them.
I was doing a self-join but I didn’t provide table aliases for the tables, which caused the issue.
Solution
To fix this issue, we must provide unique table aliases:
SELECT
e.employee_id,
e.first_name AS employee_first_name,
e.last_name AS employee_last_name,
m.first_name AS manager_first_name,
m.last_name AS manager_last_name
FROM
employees e
LEFT JOIN
employees m ON e.manager_id = m.employee_id
ORDER BY
e.employee_id;
Output:
employee_id employee_first_name employee_last_name manager_first_name manager_last_name
----------- ------------------- ------------------ ------------------ -----------------
1 Hank Blankfield null null
2 Boz Whittle Hank Blankfield
3 Mike Johnson Hank Blankfield
4 Emily Fields Boz Whittle
5 David Pease Boz Whittle
6 Sesh Lee Mike Johnson
7 Fitch Davis Mike Johnson
No error.
In this query I reference the employees
table twice in the FROM
clause, and so I gave the first one an alias of e
and the second one m
. Then I used those aliases whenever I referred to columns from the tables. This fixed the error, and the query returned its result as intended.