Yogesh Chauhan's Blog

How to reference an aliased column in the WHERE clause?

in SQL/MySQL on December 12, 2021

Read this post to learn more about SQL alias:

Learn how to give a temporary name to a column or to a table using SQL Aliases

SQL Column Alias Example

Let’s recap the post above and add column alias in a query.

SELECT firstname, userid AS id
FROM users

Reference alias

If you try to use that alias like this, you’ll get an error:


SELECT firstname, userid AS id
FROM users
WHERE id > 5

Why does this happen?

The WHERE clause is evaluated before the SELECT statement and at that point of execution, the alias id doesn’t exist in users table and you get an error.

How to fix this issue?

To fix this, we can create a virtual table using a subquery.

Subqueries are a way to perform SQL operations in multiple steps.

Since FROM is going to be evaluated before the WHERE clause, the virtual table will have id column by the time of execution of WHERE clause.

So, to make that work, you need to create a subquery like this:


from (
SELECT firstname, userid AS id
FROM users
) as results
WHERE id > 5

The results is the name for the subquery results. You can skip it if you’re not referencing it into your query.

Most Read

#1 How to add Read More Read Less Button using JavaScript? #2 How to check if radio button is checked or not using JavaScript? #3 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Common Table Expressions (CTE) in PostgreSQLPostgresHow to create two segues with two UIButtons on a single page (Swift 5.0)?SwiftHow different is Handling Events in React vs HTML DOM?ReactWindow setInterval() Method in JavaScriptJavaScriptHow to use GROUPING SETS to boost GROUP BY queries in Postgres?PostgresIs there a CSS parent selector?CSS