SQL JOINS
If you are familiar with SQL, you might have written queries to fetch data using a single table. But SQL joins are used to fetch data from two or more tables. This can be considered as one of the most benefited features enable in SQL. Lets see how we can use SQL joins to fetch data .
Rather than storing the same data in multiple tables,by using this method one table will keep a reference to a ID of the other table. This approach is more efficient and lets see we can do this using SQL joins.
Types of Joins
In MySql we can see there are mainly three joins ,
- INNER JOIN
- LEFT JOIN
- RIGHT JOIN
01. INNER JOINS
In INNER JOIN,
the query selects all the rows from both tables where there is a match between the columns in both tables.
SQL Query
SELECT column_name(s)
FROM table1 INNER JOIN table2
ON table1.column_name=table2.column_name;
FROM table1 INNER JOIN table2
ON table1.column_name=table2.column_name;
Here the INNER JOIN is Specified by the ON keyword which is in the syntax.
Example : Lets see How the INNER JOIN works from the tables given below.
Now the query will be,
SELECT ID,Name,ProName,Quantity
FROM Customer INNER JOIN Order
ON Customer.ID=Order.ID;
FROM Customer INNER JOIN Order
ON Customer.ID=Order.ID;
Output:
02. LEFT JOINS
LEFT JOINS returns all rows from the left table, even if there are no matches in the right table.This means that a left join returns all the values from the left table, plus matched values from the right table or NULL in case of no matching
SQL Query
SELECT table1.column1, table2.column2...
FROM table1 LEFT JOIN table2
ON table1.column_name = table2.column_name;
FROM table1 LEFT JOIN table2
ON table1.column_name = table2.column_name;
Example : Lets see how the LEFT JOIN works with the above customer and order table
Now the query will be,
SELECT ID,Name,ProName,Quantity
FROM Customer LEFT JOIN Order
ON Customer.ID=Order.ID;
FROM Customer LEFT JOIN Order
ON Customer.ID=Order.ID;
03.RIGHT JOINS
RIGHT JOINS returns all rows from the right table, even if there are no matches in the left table.
SQL query
SELECT table1.column1, table2.column2...
FROM table1 RIGHT JOIN table2
ON table1.column_name = table2.column_name;
FROM table1 RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Now the query will be,
SELECT ID,Name,ProName,Quantity
FROM Customer RIGHT JOIN Order
ON Customer.ID=Order.ID;
FROM Customer RIGHT JOIN Order
ON Customer.ID=Order.ID;
This is how the Basic SQL JOINS works and hope you could get a better idea. Hope to see you soon
Comments
Post a Comment