SQL inner join
Created By: chatGPT
In SQL, an INNER JOIN is used to combine rows from two or more tables based on a related column between them. This means that if there is no match between the tables, those records will not be included in the result. The INNER JOIN keyword selects records that have matching values in both tables. To perform an inner join, you can follow this structure:
SELECT table1.column1, table2.column2
FROM table1
INNER JOIN table2 ON table1.common_column = table2.common_column;
Let’s break down the SQL statement:
SELECT
specifies the columns you want to retrieve.FROM
indicates the main table from which data will be retrieved.INNER JOIN
allows you to specify the second table you want to join.ON
specifies the condition that determines how the rows from the tables relate to each other, which is commonly based on a foreign key and a primary key relationship.
SELECT employees.name, departments.department_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.id;
In this example, the employees table has a column department_id which corresponds to the id column in the departments table. The result set will contain only the employees who belong to a department, filtering out any employees who do not have a corresponding department record.
SELECT products.product_name, categories.category_name
FROM products
INNER JOIN categories ON products.category_id = categories.id;
This query fetches the product_name and the respective category_name from the products and categories tables, respectively. Again, only those products that belong to a category will be displayed in the results. Using INNER JOIN effectively helps maintain data integrity by ensuring that the combined records are meaningful.
SELECT orders.order_id, customers.customer_name, products.product_name
FROM orders
INNER JOIN customers ON orders.customer_id = customers.id
INNER JOIN products ON orders.product_id = products.id;