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 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 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
How to implement NSNumberFormatter in Swift for currency?Swiftuser_can vs current_user_can in WordPressWordPressHow to get ACF values from custom post type?WordPressOrder By and Group By in PostgresPostgresWhat is the difference between Loosely Typed Language and Strongly Typed Language?MiscellaneousHow to define variables in SCSS (Sass)?SCSS