SQL SELECT inner join

When working with databases, it is common to have multiple tables containing related information. In such cases, we often need to combine the data from different tables into a single result set. SQL provides various types of JOIN operations to accomplish this, with the INNER JOIN being the most widely used.

The INNER JOIN allows us to select records from two or more tables based on a related column between them. It returns only the rows where the specified column values match in both tables.

Syntax

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

SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2 
ON table1.column = table2.column;

Example

Let’s consider a simple example to demonstrate the usage of INNER JOIN. Suppose we have two tables customers and orders with the following structure and records:

customers:

id name email
1 John Doe john@example.com
2 Jane Lee jane@example.com
3 Alex Tan alex@example.com

orders:

id customer_id product quantity
1 1 Smartphone 2
2 2 Laptop 1
3 2 Headphones 3
4 3 Smartwatch 1

To retrieve a result set containing the customer’s name and their corresponding order details, we would use the following SQL query:

SELECT customers.name, orders.product, orders.quantity
FROM customers
INNER JOIN orders
ON customers.id = orders.customer_id;

This query will merge the customers and orders tables based on the matching customer_id and id columns. The result will be:

name product quantity
John Doe Smartphone 2
Jane Lee Laptop 1
Jane Lee Headphones 3
Alex Tan Smartwatch 1

Conclusion

By using the INNER JOIN operation in SQL, we can combine data from multiple tables based on a common column. It allows us to retrieve information that is spread across different tables in a single result set. Understanding how to use INNER JOIN is essential for anyone working with relational databases.

#SQL #Database #InnerJoin