T-SQL Tutorial

T-SQL Table Self Join


Self Join Example:

Users Table

IDUSER_NAMEDEPARTMENT_NAMEMANAGER_ID
1SYSTEMIT1
2TOMSALES2
3STEVESALES2
4ELLENSALES2
5JOHNIT1

SELECT u.id, u.user_name, m.id manager_id, m.user_name manager
 FROM users u, users m
WHERE u.manager_id = m.id
ORDER BY u.id ;

Result:

IdUser_NameManager_IdManager
1SYSTEM1SYSTEM
2TOM2TOM
3STEVE2TOM
4ELLEN2TOM
5JOHN1SYSTEM