Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
1. Introduction
Exercises with artists, museums and their pieces of art
Exercises with the band members table
Exercises with employees, salaries and benefits

Instruction

Welcome to the third part of our SQL Practice Set. Here we'll focus on strengthening our JOINing skills with different tables. Before we continue, here's a brief reminder.

You can query more than one table with JOIN. In the ON clause you specify the joining condition.

SELECT first_name, last_name, brand
FROM person
JOIN car
  ON person.id = car.owner_id

This query selects the first and last name of the person, and the brand of the car they own. We use the dot (.) notation to reference the columns of specific tables.

If you'd like to list not only people with a car, but also those who have no car, you can use a LEFT JOIN. It selects ALL rows from the left table (person), even if there are no corresponding rows in the right table.
Here's an example:

SELECT first_name, last_name, brand
FROM person
LEFT JOIN car
  ON person.id = car.owner_id

The result of this query can look like this:

first_name last_name brand
Anne Summers Ford
John Wilkinson Volvo
Emily Brown null

Observe that the column brand is NULL for people who don't have a car.

We can also rename tables in a JOIN query using aliases, like so:

SELECT c1.model as newer, c2.model as older
FROM car c1
JOIN car c2
  ON c1.age < c2.age

Here, we joined the car table twice to list new and old models together. Note the use of table aliases in the query. Observe that the JOIN condition is a bit non-standard: it's a comparison instead of an equality. Such JOINs are called non-equi JOINs.

Exercise

Click the Next exercise button to continue.