📊 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 |
|---|---|---|---|---|
| 1 | Anna | IT | 45000 | 3 |
| 2 | Ben | Sales | 38000 | 5 |
| 3 | Cara | IT | 52000 | 7 |
| 4 | Dan | HR | 35000 | 2 |
| 5 | Emma | Sales | 42000 | 4 |
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.
| id | name | department | salary | years |
|---|---|---|---|---|
| 1 | Anna | IT | 45000 | 3 |
| 2 | Ben | Sales | 38000 | 5 |
| 3 | Cara | IT | 52000 | 7 |
| 4 | Dan | HR | 35000 | 2 |
| 5 | Emma | Sales | 42000 | 4 |
Step 2
WHERE (first condition): department = 'IT'
Filter to only IT department employees:
| id | name | department | salary | years | Matches? |
|---|---|---|---|---|---|
| 1 | Anna | IT | 45000 | 3 | YES |
| 2 | Ben | Sales | 38000 | 5 | NO |
| 3 | Cara | IT | 52000 | 7 | YES |
| 4 | Dan | HR | 35000 | 2 | NO |
| 5 | Emma | Sales | 42000 | 4 | NO |
Remaining: Anna, Cara (2 records)
Step 3
WHERE (AND): salary > 40000
From the IT employees, now filter by salary > 40000:
| name | department | salary | salary > 40000? |
|---|---|---|---|
| Anna | IT | 45000 | YES (45000 > 40000) |
| Cara | IT | 52000 | YES (52000 > 40000) |
Both Anna and Cara pass this filter too!
Step 4
SELECT: Choose columns
Finally, select only the name and salary columns:
| name | salary |
|---|---|
| Anna | 45000 |
| Cara | 52000 |
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:
- Which employees have years >= 4?
- Which employees are in HR?
- With OR, if EITHER condition is true, they're included
- 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:
| name | years |
|---|---|
| Ben | 5 |
| Cara | 7 |
| Dan | 2 |
| Emma | 4 |
Note: Anna is excluded because she has 3 years (< 4) AND is in IT (not HR).