SQL Investigation

Lesson 5 of 6

Connecting the Dots

Concept:

Using INNER JOIN to combine data from multiple related tables.
Detective Indecks: I've got employee names and department IDs, but IDs don't mean anything to me. I need actual department names—Engineering, Marketing, the works.
Database: That information lives in two separate tables, detective. Employees in one, departments in another. You need to join them together.
Detective Indecks: Join? How does that work?
Database: INNER JOIN connects tables using a common key. Here, `employees.department_id` matches `departments.id`. You link them with ON: `SELECT employees.first_name, departments.name FROM employees INNER JOIN departments ON employees.department_id = departments.id`.
Detective Indecks: So it's like cross-referencing files? One file has names, another has department details, and I match them up?
Database: Exactly. INNER JOIN only shows rows where there's a match in both tables. If an employee has no department, they won't appear. If a department has no employees, it won't show either.
Detective Indecks: What if I want to see employees even if they don't have a department assigned?
Database: That's LEFT JOIN, detective. But stick with INNER JOIN for now—it gives you clean, complete connections.
Detective Indecks: Got it. Let's link these tables and see the full picture.
Example Code:
SELECT employees.first_name, employees.last_name, departments.name FROM employees INNER JOIN departments ON employees.department_id = departments.id;

Your Assignment

Connect employees to their department names. Join the employees table with the departments table to see which department each employee belongs to.

Sql Console
sql>