Write a query to show the names of students with their course names

Description: Show each student with the name of the course that they have joined.

Tables: the exercises use the students (id, name, city, marks, course_id) and courses (id, course_name) tables, with the data from our MySQL INSERT chapter. The students are: Robin (Delhi, 85), Maria (Mumbai, 92), John (Pune, 78), Asha (Jaipur, 88), Vikram (Delhi, 65), Neha (Mumbai, 45).

Hint:

  • Join students.course_id with courses.id.

MySQL query for students with course names

SELECT s.name, c.course_name
FROM students s
INNER JOIN courses c ON s.course_id = c.id
ORDER BY s.id;

Output:

Tutorials Class - Output Window
name course_name
Robin Python
Maria Java
John Python
Asha Web Design
Neha Java

How it works

  • INNER JOIN keeps only the students that have a matching course.
  • Vikram has no course, so he is not in the result. Use LEFT JOIN to include him.

Read MySQL JOINs.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.