An INNER JOIN in SQL is used to retrieve rows from two or more tables based on a specified condition, and it returns only the rows that have matching values in both tables.
Here's how to perform an INNER JOIN:
1.Basic Syntax:
SELECT columns
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;
SELECT columns
: List the columns you want to retrieve in the result.table1
andtable2
: The names of the tables you want to join.ON
: Specifies the join condition, which is a comparison between columns in both tables.table1.column_name
andtable2.column_name
: The columns you want to compare to determine the matching rows.
Example:
Suppose you have two tables, "orders" and "customers," and you want to retrieve information about orders along with the corresponding customer names. The "customer_id" column in the "orders" table matches the "customer_id" column in the "customers" table. You can use an INNER JOIN to achieve this:
SELECT orders.order_id, customers.customer_name
FROM orders
INNER JOIN customers ON orders.customer_id = customers.customer_id;
In this example:
- We're selecting columns from both the "orders" and "customers" tables.
- We specify the join condition with the
ON
clause, matching rows where the "customer_id" in the "orders" table equals the "customer_id" in the "customers" table. - The result will include only the rows that have matching customer IDs in both tables, and it will include the order ID and customer name for those matching records.
INNER JOINs are commonly used in SQL to retrieve data from related tables, ensuring that you only get data where there is a match between the specified columns in both tables.
No comments:
Post a Comment
If you have any doubts. Please let me know