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:


// THIS WILL NOT WORK

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:


// THIS WILL WORK

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

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
What is React? Learn the basicsReactHow to convert an object from API to JSON array in Angular 9?AngularMIN, MAX, COUNT, AVG and SUM in SQLSQL/MySQLHow to use a Subquery to Insert Multiple Rows in SQL Table?SQL/MySQLHow to use HTML picture Tag?HTMLHow to make a UILabel clickable in Swift 5?Swift