📊 Investigate: Trace SQL Query Execution

Understand how SQL processes queries by working through them step by step!

Reference: employees table

id name department salary years
1AnnaIT450003
2BenSales380005
3CaraIT520007
4DanHR350002
5EmmaSales420004

How SQL Processes a Query

Let's trace through this query step by step:

SQL Query
SELECT name, salary
FROM employees
WHERE department = 'IT' AND salary > 40000;
Step 1

FROM: Identify the table

SQL starts by looking at the employees table with all 5 records.

idnamedepartmentsalaryyears
1AnnaIT450003
2BenSales380005
3CaraIT520007
4DanHR350002
5EmmaSales420004
Step 2

WHERE (first condition): department = 'IT'

Filter to only IT department employees:

idnamedepartmentsalaryyearsMatches?
1AnnaIT450003YES
2BenSales380005NO
3CaraIT520007YES
4DanHR350002NO
5EmmaSales420004NO

Remaining: Anna, Cara (2 records)

Step 3

WHERE (AND): salary > 40000

From the IT employees, now filter by salary > 40000:

namedepartmentsalarysalary > 40000?
AnnaIT45000YES (45000 > 40000)
CaraIT52000YES (52000 > 40000)

Both Anna and Cara pass this filter too!

Step 4

SELECT: Choose columns

Finally, select only the name and salary columns:

namesalary
Anna45000
Cara52000

Final result: 2 rows, 2 columns

Your Turn: Trace This Query

Work through this query on paper, then check your answer:

SQL Query
SELECT name, years
FROM employees
WHERE years >= 4 OR department = 'HR';

Think about:

  1. Which employees have years >= 4?
  2. Which employees are in HR?
  3. With OR, if EITHER condition is true, they're included
  4. Which columns will be in the final result?
Click to reveal answer

Step-by-step solution:

Condition 1 (years >= 4): Ben (5), Cara (7), Emma (4)

Condition 2 (department = 'HR'): Dan

OR means either condition: Ben, Cara, Dan, Emma

SELECT name, years:

nameyears
Ben5
Cara7
Dan2
Emma4

Note: Anna is excluded because she has 3 years (< 4) AND is in IT (not HR).

Next: Build SQL Queries → ← Back to Worked Example