Introduction: The INNER JOIN is a commonly used operation in SQL that allows you to combine rows from two or more tables based on a related column between them. It retrieves only the matching records between the tables, excluding any non-matching records. This documentation provides an overview of INNER JOIN, its syntax, and a code example to illustrate its usage.
Syntax: The syntax for performing an INNER JOIN in SQL is as follows:
sqlSELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Explanation:
SELECT column_name(s): Specify the column(s) you want to retrieve from the tables involved in the INNER JOIN operation.
FROM table1: Specify the first table involved in the JOIN operation.
INNER JOIN table2: Specify the second table involved in the JOIN operation. Additional tables can be included using multiple INNER JOIN statements.
ON table1.column_name = table2.column_name: Define the condition for joining the tables. It specifies the columns that are compared between the tables to identify matching records.
Example: Suppose we have two tables: "Customers" and "Orders". We want to retrieve the customer's name and their corresponding order details using the INNER JOIN operation. The tables and their respective columns are as follows:
Table: Customers
customer_id | customer_name |
---|---|
1 | John Smith |
2 | Emma Johnson |
3 | Robert Brown |
Table: Orders
order_id | customer_id | order_date |
---|---|---|
101 | 2 | 2023-05-10 |
102 | 1 | 2023-06-01 |
103 | 3 | 2023-06-15 |
To retrieve the customer's name and their order details, we can use the following SQL query:
sqlSELECT Customers.customer_name, Orders.order_id, Orders.order_date
FROM Customers
INNER JOIN Orders
ON Customers.customer_id = Orders.customer_id;
Explanation of the Example: The SQL query begins with the SELECT statement, where we specify the columns we want to retrieve: Customers.customer_name, Orders.order_id, and Orders.order_date.
Next, we use the FROM statement to indicate the first table involved in the JOIN operation, which is "Customers".
Then, we use the INNER JOIN statement to specify the second table, "Orders".
Finally, the ON statement establishes the condition for joining the tables, which is the equality of the customer_id column between the Customers and Orders tables.
The result of this query would be:
customer_name | order_id | order_date |
---|---|---|
John Smith | 102 | 2023-06-01 |
Emma Johnson | 101 | 2023-05-10 |
Robert Brown | 103 | 2023-06-15 |
The query successfully combines the relevant data from both tables based on the matching customer_id values, providing the customer's name along with their order details.
0 Comments