Combining Rows From Two Or More Tables Based On Related Columns
JOIN is combining rows from two or more tables based on related columns
Type of join
LEFT JOIN (Left Outer Join)
Returns all rows from the left table and matched rows from the right table, filling with NULL if there’s no match
INNER JOIN / JOIN
Returns matched rows in both tables
RIGHT JOIN (Right Outer Join)
Returns all rows from the right table and matched rows from the left table, filling with NULL if there’s no match
FULL JOIN (Full Outer Join)
Returns all rows, filling with NULL where there is no match
CROSS JOIN
Returns the Cartesian product of rows from the tables in the join
Combining each row of the first table with each row of the second table
SELF JOIN
We can join a table to itself as if it were two separate tables
SELECT*FROMtable1_nameLEFTJOINtable2_nameONtable1_name.col_name=table2_name.col_name;SELECT*FROMtable1_nameINNERJOINtable2_nameONtable1_name.col_name=table2_name.col_name;SELECT*FROMtable1_nameRIGHTJOINtable2_nameONtable1_name.col_name=table2_name.col_name;SELECT*FROMtable1_nameFULLJOINtable2_nameONtable1_name.col_name=table2_name.col_name;SELECT*FROMtable1_nameCROSSJOINtable2_name;-- we do not neeed join condition here
-- self join
SELECT*FROMtable1_namet1INNERJOINtable1_namet2ONt1.col1_name=t2.col2_name;-- can be either an inner join, left join, or any other type of join
CREATETABLECustomers(idINTIDENTITY(1,1)PRIMARYKEY,nameVARCHAR(100));CREATETABLEOrders(idINTIDENTITY(1,1)PRIMARYKEY,customerIdINTFOREIGNKEYREFERENCESCustomers(id));INSERTINTOCustomers(name)VALUES('Alice');INSERTINTOCustomers(name)VALUES('Bob');INSERTINTOCustomers(name)VALUES('Charlie');INSERTINTOOrders(customerId)VALUES(1);INSERTINTOOrders(customerId)VALUES(1);INSERTINTOOrders(customerId)VALUES(2);INSERTINTOOrders(customerId)VALUES(2);|Customers||Orders||--------- | --- || --- | ---------- |
|id|name||id|customerId||1|Alice||1|1||2|Bob||2|1||3|Charlie||3|2||4|2|SELECTCustomers.nameASCustomerName,Orders.idASOrderIDFROMCustomersLEFTJOINOrdersONCustomers.id=Orders.customerId;/*
CustomerName OrderID
Alice 1
Alice 2
Bob 3
Bob 4
Charlie NULL
*/SELECTOrders.idASOrderID,Customers.nameASCustomerNameFROMOrdersLEFTJOINCustomersONOrders.customerId=Customers.id;/*
OrderID CustomerName
1 Alice
2 Alice
3 Bob
4 Bob
*/SELECTCustomers.nameASCustomerName,Orders.idASOrderIDFROMCustomersINNERJOINOrdersONCustomers.id=Orders.customerId;/*
CustomerName OrderID
Alice 1
Alice 2
Bob 3
Bob 4
*/SELECTOrders.idASOrderID,Customers.nameASCustomerNameFROMOrdersINNERJOINCustomersONOrders.customerId=Customers.id;/*
OrderID CustomerName
1 Alice
2 Alice
3 Bob
4 Bob
*/SELECTCustomers.nameASCustomerName,Orders.idASOrderIDFROMCustomersFULLJOINOrdersONCustomers.id=Orders.customerId;/*
CustomerName OrderID
Alice 1
Alice 2
Bob 3
Bob 4
Charlie NULL
*/SELECTOrders.idASOrderID,Customers.nameASCustomerNameFROMOrdersFULLJOINCustomersONOrders.customerId=Customers.id;/*
OrderID CustomerName
1 Alice
2 Alice
3 Bob
4 Bob
NULL Charlie
*/