In this lesson, you will learn why SQL doesn’t process your code in the order you write it, and why this matters for writing correct queries.
When you write a SQL query, you list commands in a specific syntax (like SELECT first, then FROM, then WHERE). However, the database engine ignores your reading order. Instead, it follows a strict logical execution order to build your result set.
Imagine you are a chef in a kitchen. You don't serve the plate before you've found the ingredients. Similarly, the database engine must follow these steps:
FROM: The engine first identifies the source table(s).WHERE: It filters the raw rows based on your criteria.SELECT: Finally, it identifies which columns you actually want to see.
Why does this matter?
Because of this order, you cannot filter by an alias created in the SELECT clause using the WHERE clause. The engine processes WHERE before it even knows what your alias is!
Consider this example:
SELECT first_name AS name
FROM employees
WHERE name = 'Alice'; -- This will cause an error!
Why it fails:
The engine looks at FROM employees first. Then, it moves to WHERE name = 'Alice'. But at this moment, the engine has no idea what name is because it hasn't reached the SELECT clause where you defined the alias yet. The database is still looking for a physical column called name in the table, which doesn't exist.
To fix this, you must use the original column name in your WHERE filter:
SELECT first_name AS name
FROM employees
WHERE first_name = 'Alice'; -- Success!
By understanding that the engine filters your data before it formats your display, you can write queries that don't confuse the database engine and avoid common "invalid column" errors.
Key Takeaway: SQL engines process data from the source (FROM) to the filter (WHERE) before they ever calculate your final output (SELECT), meaning you cannot use aliases in your filters.