SQL join
Created By: chatGPT
In SQL, a join operation allows you to combine rows from two or more tables based on a related column between them. There are several types of joins: INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN. Each type of join serves a different purpose based on how you want to retrieve data.
SELECT a.column1, b.column2
FROM tableA a
INNER JOIN tableB b ON a.common_column = b.common_column;
The INNER JOIN returns only the rows that have matching values in both tables. If there is no match, those rows will not be included in the results. Here’s a basic example:
SELECT employees.name, departments.department_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.id;
On the other hand, a LEFT JOIN returns all rows from the left table and the matched rows from the right table. If there is no match, the result will contain NULL for columns from the right table.
SELECT employees.name, departments.department_name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.id;
A RIGHT JOIN works similarly but includes all rows from the right table and the matched rows from the left table. This means if a row in the right table doesn't match, you will get NULL for the left table's columns.
SELECT employees.name, departments.department_name
FROM employees
RIGHT JOIN departments ON employees.department_id = departments.id;
Lastly, a FULL OUTER JOIN returns all rows when there is a match in either left or right table records. This means it will return all records and fill in NULL where there is no match.
SELECT employees.name, departments.department_name
FROM employees
FULL OUTER JOIN departments ON employees.department_id = departments.id;
To effectively use joins, make sure that your tables are related logically, and always specify the exact columns you wish to retrieve to improve performance. Combining joins with filtering using the WHERE clause can also refine your query results.
SELECT employees.name, departments.department_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.id
WHERE departments.department_name = 'Sales';