sql_join_inner
SQL INNER JOIN Keyword
Section titled “SQL INNER JOIN Keyword”Understanding SQL INNER JOIN
Section titled “Understanding SQL INNER JOIN”The INNER JOIN keyword selects records that have matching values in both tables. It is the most common type of join.
If a row in table1 finds a corresponding row in table2 based on the join condition, the INNER JOIN combines columns from both rows into a single result row. If there’s no match, the rows are excluded from the result.
SQL INNER JOIN Syntax
Section titled “SQL INNER JOIN Syntax”SELECT column_name(s)FROM table1INNER JOIN table2ON table1.join_column = table2.join_column;Alternatively, you can often just use JOIN (which defaults to INNER JOIN in most SQL databases):
SELECT column_name(s)FROM table1JOIN table2ON table1.join_column = table2.join_column;Visually, an INNER JOIN can be thought of as the intersection of two sets – only the elements (rows) that exist in both sets (based on the join condition) are returned.
Demo Database: Northwind
Section titled “Demo Database: Northwind”We’ll use the Northwind sample database with its Customers and Orders tables.
A simplified view of the “Customers” table:
CustomerID | CustomerName | Country-----------|-----------------------------------|---------1 | Alfreds Futterkiste | Germany2 | Ana Trujillo Emparedados y helados| Mexico3 | Antonio Moreno Taquería | Mexico...A simplified view of the “Orders” table:
OrderID | CustomerID | OrderDate--------|------------|-----------10308 | 2 | 1996-09-1810309 | 37 | 1996-09-1910310 | 77 | 1996-09-20...SQL INNER JOIN Example
Section titled “SQL INNER JOIN Example”The following SQL statement will return only customers who have placed orders, along with their order IDs:
SELECT c.CustomerName, o.OrderIDFROM Customers cINNER JOIN Orders o ON c.CustomerID = o.CustomerIDORDER BY c.CustomerName;A selection from the result set might look like this:
CustomerName | OrderID-----------------------------------|---------Ana Trujillo Emparedados y helados| 10308Antonio Moreno Taquería | 10365... (other customers with orders)Important Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match on the join condition (Customers.CustomerID = Orders.CustomerID). If there are customers in the “Customers” table that do not have any matching orders in the “Orders” table, those customers will NOT be listed in the result. Similarly, any orders without a matching customer (orphaned data, if possible) would also be excluded.
Common Use Cases:
Section titled “Common Use Cases:”- Retrieving related data from multiple tables (e.g., user profiles and their posts).
- Filtering records based on the existence of related data (e.g., products that have been ordered).
- Combining information for comprehensive reports where a direct relationship exists.