Sobes.tech
Junior

What types of table joins exist in SQL?

sobes.tech AI

Answer from AI

In SQL, the following types of table joins exist:

  • INNER JOIN (or simply JOIN): Returns rows when there is a match in both tables.

    SELECT *
    FROM table1
    INNER JOIN table2 ON table1.column_name = table2.column_name;
    
  • LEFT JOIN (or LEFT OUTER JOIN): Returns all rows from the left table and matching rows from the right table. If there is no match in the right table, the result for columns from the right table will be NULL.

    SELECT *
    FROM table1
    LEFT JOIN table2 ON table1.column_name = table2.column_name;
    
  • RIGHT JOIN (or RIGHT OUTER JOIN): Returns all rows from the right table and matching rows from the left table. If there is no match in the left table, the result for columns from the left table will be NULL.

    SELECT *
    FROM table1
    RIGHT JOIN table2 ON table1.column_name = table2.column_name;
    
  • FULL JOIN (or FULL OUTER JOIN): Returns rows when there is a match in either table. Returns all rows from both tables, filling in NULLs where there are no matches.

    SELECT *
    FROM table1
    FULL JOIN table2 ON table1.column_name = table2.column_name;
    
  • CROSS JOIN: Returns the Cartesian product of the rows of both tables. Each row from the first table is combined with each row from the second table. The ON condition is not used here.

    SELECT *
    FROM table1
    CROSS JOIN table2;
    

In addition to these main types, a self-join can be performed, where a table is joined with itself. This is implemented by using aliases for the same table.

SELECT t1.column_name, t2.column_name
FROM table_name t1, table_name t2
WHERE t1.column_name = t2.column_name; // or another comparison condition within the table