Senior
Tell me about the types of JOIN in SQL and explain the differences between them.
sobes.tech AI
Answer from AI
In SQL, there are several types of JOINs that allow combining data from two or more tables based on a specific condition.
Main types of JOIN:
- INNER JOIN — returns only the records that have matches in both tables.
- LEFT JOIN (LEFT OUTER JOIN) — returns all records from the left table and matching records from the right; if there are no matches, the right table fields will be NULL.
- RIGHT JOIN (RIGHT OUTER JOIN) — similar to LEFT JOIN, but returns all records from the right table.
- FULL JOIN (FULL OUTER JOIN) — returns all records from both tables; where there are no matches, NULLs will be in the respective fields.
The difference between them lies in which records are preserved when there are no matches:
- INNER JOIN excludes records without matches.
- LEFT JOIN preserves all from the left table.
- RIGHT JOIN preserves all from the right table.
- FULL JOIN preserves all from both tables.
Example:
SELECT * FROM A
INNER JOIN B ON A.id = B.a_id;
SELECT * FROM A
LEFT JOIN B ON A.id = B.a_id;
SELECT * FROM A
RIGHT JOIN B ON A.id = B.a_id;
SELECT * FROM A
FULL JOIN B ON A.id = B.a_id;
In Go, when working with databases through SQL queries or ORM, it is important to understand which JOIN to use to obtain the necessary data and optimize queries.