Menu
Coddy logo textTech

Basic Join Part 1

Part of the Fundamentals section of Coddy's SQL journey — lesson 43 of 72.

As of now, we tackled problems of a single table. Now we will examine how to handle multiple tables.

Let's assume we have the following tables:

courses

course_idlecturer_id
11
21
32

lecturers

lecturer_idname
1Jhonas
2Malidos

The task is to present for each course with the corresponding lecturer's name.

There are two ways to achieve this. For each option, we match each row in one table to the other. we check a condition that must be met and if the condition is met we combine the two rows into one. The desired result for both options:

course_idlecturer_name
1Jhonas
2Jhonas
3Malidos

Option 1:

SELECT courses.course_id, lecturers.name AS lecturer_name
FROM courses, lecturers
WHERE courses.lecturer_id = lecturers.lecturer_id

Here we write two tables in the FROM keyword, and in the WHERE clause we request that the lecturer_id of both records must be the same. In the SELECT clause we now write table.column so that the database will know where to fetch the column.

Option 2:

SELECT courses.course_id, lecturers.name AS lecturer_name
FROM courses
JOIN lecturers ON courses.lecturer_id = lecturers.lecturer_id

Instead of WHERE we use JOIN table ON condition

This type of join is also called an inner join.

challenge icon

Challenge

Easy

Available tables and columns:

  • <strong>grades</strong>: <strong>course_id</strong>, <strong>student_id</strong>, <strong>grade</strong>
  • <strong>students</strong>: <strong>id</strong>, <strong>name</strong>

Create a query that fetches student_name, course_id, student_id and grade in one table. Order the result by grade in ascending order.

Cheat sheet

To combine data from multiple tables, use either the comma syntax with WHERE or JOIN syntax:

Option 1: Comma syntax with WHERE

SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.id = table2.id

Option 2: JOIN syntax

SELECT table1.column, table2.column
FROM table1
JOIN table2 ON table1.id = table2.id

Use table.column syntax to specify which table a column comes from when selecting from multiple tables. This type of join is called an inner join.

Try it yourself

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals