SQL Joins SQL Topic exerciseEasyVerified answerSQLite + PostgreSQL + MySQL + SQL Server live · 1 guided

Employees with Department Names (INNER JOIN)

Return employee_id, first_name, last_name, and department_name for matched employees, ordered by employee_id.

  • Joins
  • Sorting

Exercise brief

Understand the request

People operations analyst A directory export needs the department label for every employee whose department relationship is valid.

List every employee with their department name. Only include employees that ARE assigned to a department. Return employee_id, first_name, last_name, department_name — ordered by employee_id.

Return

  • Return one row per matched employee.
  • Order by employee_id.

Constraints

  • Use an explicit equality INNER JOIN on department_id.

Data you will use

Review the relevant tables before deciding how to join, filter, or aggregate them.

employees

  • employee_idINTEGER
  • first_nameVARCHAR(50)
  • last_nameVARCHAR(50)
  • department_idINTEGER

departments

  • department_idINTEGER
  • department_nameVARCHAR(50)

Hints, when you need them

Open one clue at a time so you still do the reasoning.

Hint 1

INNER JOIN syntax: `FROM table1 a INNER JOIN table2 b ON a.key = b.key`. Only rows with matches on BOTH sides survive.

Hint 2

Aliases (e, d) let you write short column references and disambiguate when both tables share a column name.

Hint 3

ON e.department_id = d.department_id is the join predicate — it's HOW the rows pair up.

Verified SQL answer

Attempt the problem first, then compare structure and reasoning—not just syntax.

Reveal solution and explanation
SELECT e.employee_id, e.first_name, e.last_name, d.department_name FROM employees e INNER JOIN departments d ON e.department_id = d.department_id ORDER BY e.employee_id;

Why this works

INNER JOIN is the workhorse — it keeps only the intersection. If an employee has NULL department_id (or a value with no match in departments), they will NOT appear. That's by design; switch to LEFT JOIN if you want to keep them anyway.

Success check

Every employee with a valid department appears exactly once with the correct department name.

Expected result

Use this output to verify values, aliases, ordering, and row count.

employee_idfirst_namelast_namedepartment_name
100JohnSmithIT
101AliceJohnsonIT
102BobWilsonIT
103CarolDavisHR
104DavidBrownFinance
105EmmaTaylorMarketing
106FrankGreenMarketing
107GraceWhiteIT
108HenryClarkHR
109IvyMartinezFinance

Learn the concepts behind this answer

Strengthen your understanding with these targeted learning topics:

Continue practicing

SQL Practice Online

Open the interactive workspace and practice across SQL topics.