Retrieving data from multiple tables using JOIN

Result:

| first_name | last_name | department_name | |------------|-----------|-----------------| | John | Doe | HR | | Jane | Smith | IT | | Michael | Brown | HR |

LEFT JOIN example

Using a LEFT JOIN, we'll retrieve all employees and their matching department names (if any):

SELECT employees.first_name, employees.last_name, departments.department_name
FROM employees
LEFT JOIN departments
ON employees.department_id = departments.department_id;

Result:

| first_name | last_name | department_name | |------------|-----------|-----------------| | John | Doe | HR | | Jane | Smith | IT | | Michael | Brown | HR |

In this example, the LEFT JOIN result is the same as the INNER JOIN because all employees have a matching department.

RIGHT JOIN example

Using a RIGHT JOIN, we'll retrieve all departments and their matching employee names (if any):

SELECT employees.first_name, employees.last_name, departments.department_name
FROM employees
RIGHT JOIN departments
ON employees.department_id = departments.department_id;

Result:

| first_name | last_name | department_name | |------------|-----------|-----------------| | John | Doe | HR | | Michael | Brown | HR | | Jane | Smith | IT |

In this example, the RIGHT JOIN result is the same as the INNER JOIN because all departments have a matching employee.

Now you should have a clear understanding of how to retrieve data from multiple tables using JOINs in SQL. Practice using INNER JOIN, LEFT JOIN, and RIGHT JOIN to become more comfortable with these powerful operations.

Give more examples of joins

Sure, here are some more examples of joins in SQL:

  1. FULL OUTER JOIN: This join returns all records from both tables and joins on matching records. If there are any unmatched records, they will still be returned, with NULL values in the columns from the other table.

Syntax: SELECT * FROM table1 FULL OUTER JOIN table2 ON table1.column = table2.column;

Example: SELECT * FROM orders FULL OUTER JOIN customers ON orders.customer_id = customers.customer_id;

  1. SELF JOIN: This join is used to join a table to itself, in order to compare rows within the same table.

Syntax: SELECT * FROM table1 JOIN table1 AS t2 ON table1.column = t2.column;

Example: SELECT e.first_name, m.first_name AS manager FROM employees e JOIN employees m ON e.manager_id = m.employee_id;

  1. CROSS JOIN: This join returns the Cartesian product of the two tables, which means that every possible combination of rows from both tables is returned.

Syntax: SELECT * FROM table1 CROSS JOIN table2;

Example: SELECT * FROM colors CROSS JOIN sizes;

Last updated