Ticker

6/recent/ticker-posts

Inner Join in SQL

Inner Join in SQL


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:

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

Explanation:

  1. SELECT column_name(s): Specify the column(s) you want to retrieve from the tables involved in the INNER JOIN operation.

  2. FROM table1: Specify the first table involved in the JOIN operation.

  3. INNER JOIN table2: Specify the second table involved in the JOIN operation. Additional tables can be included using multiple INNER JOIN statements.

  4. 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_idcustomer_name
1John Smith
2Emma Johnson
3Robert Brown

Table: Orders

order_idcustomer_idorder_date
10122023-05-10
10212023-06-01
10332023-06-15

To retrieve the customer's name and their order details, we can use the following SQL query:

sql
SELECT 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_nameorder_idorder_date
John Smith1022023-06-01
Emma Johnson1012023-05-10
Robert Brown1032023-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.

Post a Comment

0 Comments