MySQL LEFT JOIN

MySQL LEFT JOIN


A LEFT JOIN in MySQL is used to retrieve all records from the left table (first table) and the matching records from the right table (second table).


  • If there is no match found in the right table, NULL values are returned for the right table's columns.
  • It is also known as a Left Outer Join.


LEFT JOIN Syntax


SELECT table1.column_name, table2.column_name
FROM table1
LEFT JOIN table2
ON table1.common_column = table2.common_column;


  • table1 → Left table
  • table2 → Right table
  • ON → Specifies the relationship between columns in both tables


Example Scenario:


Students Table:

student_id

name 

gender

city

age

score

course_id

email

phone_number

1

Alice

Female

Delhi

20

85

101

NULL

1234567890

2

Bob

Male

Mumbai

22

75

NULL

bob@email.com

NULL

3

Charlie

Male

Delhi

21

95

102

NULL

NULL

4

David

Male

Bangalore

23

65

101

david@email.com

NULL

5

Eve

Female

Mumbai

20

80

103

NULL

NULL

6

Frank

Male

Delhi

22

90

103

NULL

NULL

7

Alice

Female

Mumbai

19

60

102

NULL

NULL

Courses Table:

course_name

course_name

101

Math

102

Science

103

History

104

English

The following SQL statement will select all students, and any courses they might have:

Example
SELECT courses.course_name,students.name
FROM courses
LEFT JOIN students
ON students.course_id = courses.course_id;

Try it yourself

Output:

name

course_name

Alice

Math

Bob

NULL

Charlie

Science

David

Math

Eve

History

Frank

History

Alice

Science

Explanation:


  • Alice is matched with the Math course.
  • Charlie is matched with the Science course.
  • Bob has no course (NULL in course_id), so the result shows NULL in course_name.

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.