What types of join queries exist in SQL?
sobes.tech AI
Answer from AI
There are four main types of JOIN queries in SQL:
-
INNER JOIN: Returns only the rows where there are matches in both tables based on the specified condition. -
LEFT JOIN(orLEFT OUTER JOIN): Returns all rows from the left table and the matching rows from the right table. If there are no matches in the right table,NULLis returned for the right table's columns. -
RIGHT JOIN(orRIGHT OUTER JOIN): Returns all rows from the right table and the matching rows from the left table. If there are no matches in the left table,NULLis returned for the left table's columns. -
FULL JOIN(orFULL OUTER JOIN): Returns all rows when there is a match in one of the tables. If there are no matches,NULLis returned for the respective columns.
Syntax examples:
-- Example of INNER JOIN
SELECT
*
FROM
table1 t1
INNER JOIN
table2 t2 ON t1.column = t2.column;
-- Example of LEFT JOIN
SELECT
*
FROM
table1 t1
LEFT JOIN
table2 t2 ON t1.column = t2.column;
-- Example of RIGHT JOIN
SELECT
*
FROM
table1 t1
RIGHT JOIN
table2 t2 ON t1.column = t2.column;
-- Example of FULL JOIN
SELECT
*
FROM
table1 t1
FULL JOIN
table2 t2 ON t1.column = t2.column;
There is also CROSS JOIN, which returns the Cartesian product of two tables (each row from the first table is combined with each row from the second). It does not require an ON condition.
-- Example of CROSS JOIN
SELECT
*
FROM
table1 t1
CROSS JOIN
table2 t2;