SQL JOINS are used to combine records from two or more tables in a database based on a related column between them. Joins allow you to retrieve meaningful information by linking data from different tables.
The different types of SQL JOINs are:
An Inner Join returns only the rows where there is a match between both tables based on a specified condition (like matching IDs or values). If there is no match for a row in one of the tables, that row is excluded from the results. This type of join is used when you only want the data that exists in both tables.
A Left Join returns all the rows from the left table (the first table) and the matching rows from the right table (the second table). If there is no match for a row in the left table, the result will still include that row, but with NULL
values for the columns of the right table. This join ensures that no data from the left table is lost, even if there’s no matching data in the right table.
NULL
values in the order-related columns.A Right Join is the opposite of a Left Join. It returns all the rows from the right table (the second table) and the matching rows from the left table (the first table). If there is no match for a row in the right table, the result will still include that row, but with NULL
values for the columns from the left table.
NULL
values in the customer-related columns.A Full Join returns all the rows from both tables, whether or not there is a match between them. If a row in one table doesn’t have a matching row in the other table, the result will include that row with NULL
values for the missing side. This join is useful when you want to make sure no data is excluded from either table.
A Cross Join returns the Cartesian product of both tables, meaning it combines every row from the first table with every row from the second table. There is no condition or matching requirement in a Cross Join. This can result in a very large number of rows if both tables have a lot of data, as each row from the first table is combined with every row from the second table.
A Self Join is when a table is joined with itself. This is useful when a table contains hierarchical data or when you need to compare rows within the same table. For example, if you have an employee table where each employee has a manager (who is also an employee), you can use a Self Join to match employees with their managers.
employee_id
and a manager_id
. If you want to find each employee along with their manager, you would perform a Self Join, comparing the manager_id
with the employee_id
in the same table.