JOIN is a SQL operation that combines rows from two or more tables based on a related column between them. There are several types of JOINs, including INNER JOIN, LEFT JOIN, and RIGHT JOIN.
INNER JOIN: An INNER JOIN returns only the rows that have matching values in both tables. The join condition is specified using the ON keyword. Here is an example:
SELECT customers.customer_name, orders.order_id
FROM customers
INNER JOIN orders
ON customers.customer_id = orders.customer_id
In this example, the INNER JOIN retrieves all customers who have placed an order, and their corresponding order IDs. The join condition ensures that only customers who have a matching record in the orders table are included in the result.
LEFT JOIN: A LEFT JOIN returns all the rows from the left table and the matching rows from the right table. If there is no matching row in the right table, the result will contain null values for the right table columns. Here is an example:
SELECT customers.customer_name, orders.order_id
FROM customers
LEFT JOIN orders
ON customers.customer_id = orders.customer_id
In this example, the LEFT JOIN retrieves all customers, including those who have not placed an order. If a customer has not placed an order, the result will contain null values for the order ID column.
RIGHT JOIN: A RIGHT JOIN returns all the rows from the right table and the matching rows from the left table. If there is no matching row in the left table, the result will contain null values for the left table columns. Here is an example:
SELECT customers.customer_name, orders.order_id
FROM customers
RIGHT JOIN orders
ON customers.customer_id = orders.customer_id
In this example, the RIGHT JOIN retrieves all orders, including those that do not have a corresponding customer record. If an order does not have a corresponding customer record, the result will contain null values for the customer name column.
In summary, INNER JOIN returns only the matching rows between two tables, LEFT JOIN returns all rows from the left table and matching rows from the right table, and RIGHT JOIN returns all rows from the right table and matching rows from the left table. These JOIN types are important for combining and querying data from multiple tables in a relational database.