Chapter 8 · Lesson 2 of 8

FROM and JOIN Build the Rows First

See how FROM and JOIN assemble the working rows before WHERE filters them, then filter joined employee and department data.

The first big step is FROM plus JOIN. SQL first decides which tables participate and how their rows connect.

Only after the joined row set exists does WHERE filter it.

That is why a query like this works:

SELECT e.name AS employee_name, d.name AS department_name
FROM employees AS e
JOIN departments AS d
  ON e.department_id = d.id
WHERE d.name = 'Engineering'

The WHERE clause can filter on department data because the JOIN has already happened logically.

Sample data

This lesson loads the employees + departments tables into DuckDB in your browser with one click, so you can run every example without uploading anything.

Setup SQL for employees, departments
CREATE OR REPLACE TABLE departments (
    id INTEGER,
    name VARCHAR
  );

INSERT INTO departments VALUES
    (1, 'Engineering'),
    (2, 'Marketing'),
    (3, 'Sales'),
    (4, 'Support');

CREATE OR REPLACE TABLE employees (
    id INTEGER,
    name VARCHAR,
    department_id INTEGER,
    manager_id INTEGER
  );

INSERT INTO employees VALUES
    (1, 'Alice', 1, NULL),
    (2, 'Bob', 2, 1),
    (3, 'Charlie', 1, 1),
    (4, 'Diana', 3, 2),
    (5, 'Eve', NULL, 2),
    (6, 'Frank', 1, 3);

Practice challenge

Return the Engineering employees after joining employees and departments. Show employee_name and department_name, ordered by employee_name.

Hint: JOIN employees to departments on the department id, then filter to department_name = 'Engineering'.

Run your query in the editor and the lesson checks the result automatically.

Open this lesson in the SQL editor

Lessons in Execution Order

Understand the logical order in which SQL evaluates FROM, WHERE, GROUP BY, HAVING, window functions, SELECT, ORDER BY, and LIMIT.

  1. 01 · Written Order vs Logical Order
  2. 02 · FROM and JOIN Build the Rows First
  3. 03 · WHERE Filters Before GROUP BY
  4. 04 · HAVING Filters After GROUP BY
  5. 05 · Where Window Functions Fit
  6. 06 · Why Window Functions Cannot Go Directly in WHERE
  7. 07 · Why SELECT Aliases Work in ORDER BY
  8. 08 · LIMIT Happens at the End

Related guides