Wednesday, February 25, 2026

SQL JOIN

 

SQL JOIN

In SQL, a JOIN clause is used to combine rows from two or more tables based on a related column between them. Since relational databases often store data across multiple tables, JOINs are essential for retrieving meaningful combined results.


🌍 Types of SQL JOINs

INNER JOIN

  • Returns rows when there is a match in both tables.
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

LEFT JOIN

  • Returns all rows from the left table and matched rows from the right table.
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

RIGHT JOIN

  • Returns all rows from the right table and matched rows from the left table.
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
RIGHT JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

FULL OUTER JOIN

  • Returns all rows when there is a match in one of the tables.
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

CROSS JOIN

  • Returns the Cartesian product of both tables (every possible combination).
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
CROSS JOIN Orders;

SELF JOIN

  • A table joins itself, useful for hierarchical data.
SELECT A.EmployeeName AS Manager, B.EmployeeName AS Employee
FROM Employees A
INNER JOIN Employees B ON A.EmployeeID = B.ManagerID;

📊 Comparison Table

JOIN TypeDescriptionExample Use Case
INNER JOINMatches in both tablesOrders with valid customers
LEFT JOINAll rows from left + matchesCustomers with or without orders
RIGHT JOINAll rows from right + matchesOrders with or without customers
FULL OUTER JOINAll rows from both tablesComplete dataset with all customers and orders
CROSS JOINCartesian productTesting combinations
SELF JOINTable joins itselfEmployee-manager relationships

📖 Conclusion

SQL JOINs are the backbone of relational queries, enabling developers to combine data across multiple tables. By mastering INNER, LEFT, RIGHT, FULL OUTER, CROSS, and SELF JOIN, you can handle complex queries and extract meaningful insights from relational databases.

No comments:

Post a Comment

Support Vector Machines in Machine Learning

Support Vector Machines in Machine Learning Introduction Support Vector Machines (SVMs) are powerful supervised learning algorithms used ...