INNER JOIN

When working with databases, one of the most common tasks is retrieving data from multiple tables. This is where the JOIN operation comes into play. In SQL, the INNER JOIN is used to combine rows from two or more tables based on a related column between them.

Syntax

The syntax for an INNER JOIN in SQL is as follows:

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

The INNER JOIN clause is used to specify the tables to be joined and the ON keyword is used to define the condition for the join. The condition is usually based on matching values in a common column between the tables.

Example

Let’s say we have two tables: customers and orders. The customers table has columns customer_id, customer_name, and customer_city. The orders table has columns order_id, customer_id, and order_date.

To retrieve the customer_name and order_date for all customers who have placed an order, we can use an INNER JOIN as follows:

SELECT customers.customer_name, orders.order_date
FROM customers
INNER JOIN orders
ON customers.customer_id = orders.customer_id;

In this example, the customer_id column is common to both tables, serving as the basis for the join. The result will be a list of customer_name and order_date pairs for all matching rows in the customers and orders tables.

Conclusion

The INNER JOIN operation in SQL allows you to combine data from multiple tables using a common column. It is a powerful tool for retrieving related data and is widely used in database queries. By understanding the syntax and using appropriate conditions, you can effectively retrieve the desired information from your database.