SQL Inner Join - Fetch Data From Two Tables in Single Query With Example
25-02-2018
SQL INNER JOIN joins two tables based on common column values
SQL inner join Syntax
SELECT column_name1,column_name2,...
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name = table_name2.column_name;
To Understand the INNER JOIN practically, we will create two tables and we will apply INNER JOIN on them.
Let's create a table users that store the user information like: UserID, Name, Email, and MobileNumber.
UserID | Name | MobileNumber | |
---|---|---|---|
1 | Taohid | taohidphp@gmail.com | 9131628365 |
2 | Sajid | sajidfreefire@gmail.com | 9589186366 |
Now, we will create another table orders that will store the user's orders.
OrderID | UserID | OrderDate | ItemName | Status |
---|---|---|---|---|
10 | 1 | 2027-12-01 | Dell Laptop | Delivered |
11 | 2 | 2027-12-10 | HP Laptop | Delivered |
In the both table, we can see there is a common column UserID. So, we can apply here Inner Join.
Normaly, if we select the order details from orders Table, we can only select OrderID, UserID, OrderDate, ItemName and Status. To view the User Details who made the order, we need to fire another query from users Table. But, using Inner Join We can select Order Details along with the user details in single query. Let's see the INNER JOIN query below to select order details and also uder details.
SELECT orders.OrderID,orders.OrderDate,orders.ItemName,orders.Status,users.Name,users.Email,users.MobileNumber FROM orders INNER JOIN users ON orders.UserID = users.UserID;
The above query will give output as:
OrderID | OrderDate | ItemName | Status | Name | MobileNumber | |
---|---|---|---|---|---|---|
10 | 2027-12-01 | Dell Laptop | Delivered | Taohid | taohidphp@gmail.com | 9131628365 |