Logo

K-Learn

SQL JOIN

< Previous Next >

A JOIN combines rows from two or more tables into a single result set based on a related column between them. The related column(s) is called the "join condition".

JOIN Syntax

SELECT column_name(s)
FROM table1
JOIN table2
ON table1.column_name = table2.column_name;

Now, let's consider the following tables that as an example:

  • student (id, name, email, phone, address)

  • subject (id, name)

  • exam (id, student_id, subject_id, score)

Here, the "student_id" column in the "exam" table relates to the "id" column in the "student" table, and the "subject_id" column in the "exam" table relates to the "id" column in the "subject" table.

Suppose we want to find the name of each student along with the subject and their exam score. To do this, we need to combine data from both the "student" and "exam" tables, using the "id" column in the "student" table and the "student_id" column in the "exam" table as the join condition. We also need to combine data from the "subject" table, using the "id" column in the "subject" table and the "subject_id" column in the "exam" table as the join condition.

Here's an example query that achieves this:

SELECT student.name, subject.name, exam.marks
FROM student
JOIN exam ON student.id = exam.student_id
JOIN subject ON exam.subject_id = subject.id

OUTPUT

The above example,

This query uses the "JOIN" keyword to combine rows from the "student", "exam", and "subject" tables based on the join conditions. The "ON" keyword is used to specify the join conditions. So, the above query returns the name, subject and marks of each student.


< Previous Next >