Can you use an alias in the WHERE clause in mysql?
In MySQL, column aliases can't be used directly within the WHERE
clause. For those instances where you need to filter data based on a calculated column, you must either repeat
the actual expression
involved or utilize a subquery
. While aliases are supported by the ORDER BY
clause, this convenience does not extend to WHERE
. Here's how you would use a subquery:
or directly use the expression in WHERE
:
Wrap your head around WHERE and HAVING
Where is my alias in WHERE?
You might have encountered frustration when your alias, defined in the SELECT
clause, is not recognized in your WHERE
clause. WHY? Because WHERE
clause gets evaluated before the SELECT
clause, it absolutely has no clue about any aliases that you might have defined later in the SELECT clause.
Aggregate Functions: Let's 'HAVE' some fun
When dealing with aggregated data such as SUM()
, AVG()
, COUNT()
, etc., we don't use WHERE. Instead, we embrace our friend HAVING
clause. Since HAVING
clause swings into action after the aggregation phase, it has no problem recognizing aliases!
Subqueries: Our Secret Weapon
When you need to wield some calculated power, say hello to subqueries to conjure up a derived table that filters out data based on the alias named in the outer query.
Into the depths of aliasing in SQL
Subqueries: Labeling made easy
You can keep your SQL neat and tidy with the magic wand of subqueries!
This method creates a clean label within your subquery and uses it for the outer query's WHERE
clause.
CASE: The "switchblade" of SQL
CASE expressions can save you from repeatedly referencing external aliases:
In this case, (pardon the pun!) the CASE expression is replicated in both SELECT
and WHERE
.
Post-aggregation filtering with HAVING
Filtering after aggregation is a common requirement in data analysis. HAVING
is ready to tackle this job!
Was this article helpful?