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
MySQL JOINs
MySQL Subqueries
MySQL UNION
Exercises & Assignments
Write a query to show the student name who has the second highest marks
Write a query to show the names of students with their course names
Write a query to count the students of each course, including empty courses
Write a query to find the students who scored above the average marks
Interview Questions & Answers
What is the difference between INNER JOIN and LEFT JOIN?
What is the difference between UNION and UNION ALL?
What are the types of JOINs in MySQL?
How to find the second highest marks in MySQL?
What is a subquery in MySQL?