i
SQL Select, Select distinct
Select Distinct Clause
SQL Where Clause
SQL And, Or, Not
SQL Aliases
SQL Like
SQL In
SQL Between
Order By Clause
Aggregate Functions (Min, Max, Avg, Sum, Count)
Count
AVG() Syntax
SUM
MIN
MAX
Group By
HAVING Clause
SQL Insert Into
SQL Create Table
SQL Drop Table
SQL Alter Table
SQL Constraints
SQL Not Null
SQL Unique
SQL Primary Key
SQL Foreign Key
SQL Default
SQL Self Join allows the programmer to join a table to itself. It is useful for querying hierarchical data or comparing rows within the same table.
Syntax
SELECT column_name(s) |
Tbl1 and Tbl2 are different table aliases for the same table.
Consider the below EMPLOYEES table where the employer and manager information is stored in the same table.
EMPLOYEE_ID |
FIRST_NAME |
LAST_NAME |
MANAGER_ID |
100 |
Steven |
King |
108 |
101 |
Neena |
Kochhar |
108 |
102 |
Lex |
De Haan |
108 |
103 |
Alexander |
Hunold |
108 |
104 |
Bruce |
Ernst |
108 |
105 |
David |
Austin |
108 |
106 |
Valli |
Pataballa |
108 |
107 |
Diana |
Lorentz |
108 |
108 |
Nancy |
Greenberg |
109 |
109 |
Daniel |
Faviet |
109 |
The below query can be used to retrieve the employee details along with their manager details
SELECT
tbl1.first_name as employee,
tbl2.first_name as manager
FROM
employees tbl1
INNER JOIN employees tbl2 ON tbl1.employee_id = tbl2.manager_id;
Output:
EMPLOYEE |
MANAGER |
Steven |
Nancy |
Neena |
Nancy |
Lex |
Nancy |
Alexander |
Nancy |
Bruce |
Nancy |
David |
Nancy |
Valli |
Nancy |
Diana |
Nancy |
Nancy |
Daniel |
Daniel |
Daniel |
Don't miss out!