Joins
Joins
SQL joins are the foundation of database management systems, enabling the
combination of data from multiple tables based on relationships between columns.
Joins allow efficient data retrieval, which is essential for generating meaningful
observations and solving complex business queries.
It can access data from multiple tables simultaneously using common key values shared
across different tables.
We can use SQL JOIN with multiple tables. It can also be paired with other clauses,
the most popular use will be using JOIN with WHERE clause to filter data retrieval.
Student:
StudentCourse Table
Both these tables are connected by one common key (column) i.e ROLL_NO. We can perform
a JOIN operation using the given SQL query:
Query:
SELECT s.roll_no, s.name, s.address, s.phone, s.age, sc.course_id FROM Student s
JOIN
StudentCourse sc ON s.roll_no = sc.roll_no;
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
Ex:
Ex:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Ex:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
SQL FULL JOIN
FULL JOIN creates the result-set by combining results of both LEFT JOIN and RIGHT
JOIN. The result-set will contain all the rows from both tables. For the rows for which there is
no matching, the result-set will contain NULL values.
Syntax
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
Ex:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
NAME COURSE_ID
HARSH 1
PRATIK 2
RIYANKA 2
NAME COURSE_ID
DEEP 3
SAPTARHI 1
DHANRAJ NULL
ROHIT NULL
NIRAJ NULL
NULL 4
NULL 5
NULL 4