Using an Alias column in the where clause in PostgreSQL
Filter by an alias in PostgreSQL by putting your query inside a subquery or using a CTE (Common Table Expression) method.
Example using subquery:
Example using CTE:
Both strategies offer the power to reference the alias directly outside its initial SELECT statement.
CTEs, Subqueries & Complex Cases
Utilizing CASE inside CTEs
When your alias requires sophisticated logic, employ the CASE statement inside a CTE.
Addressing NULLs with COALESCE
Combat those pesky NULL values by integrating the COALESCE function into the alias definition.
Optimizing performance through expression duplication
Lift performance by duplicating the CASE statement or the expression from the SELECT clause right inside the WHERE clause.
Organizing Data and Columns
Observing the order of operations
Sort data concerning an alias column by including it in the outer scope.
Using LEFT JOINs with aliases
Employ LEFT JOIN whilst avoiding implicit filtering with a standard JOIN.
More Tips, Tricks, and Practical Examples
Avoiding the "Column does not exist" heartbreak
Prevent the "Column doesn't exist" error by defining the alias in a subquery or CTE before the WHERE clause.
Leveraging on PostgreSQL's extra features
Expand your capabilities with PostgreSQL's WITH and RETURNING in data modification queries.
Taking a bold path: Reusing SELECT expressions
Choosing not to use subqueries or CTEs? You can directly reuse SELECT expressions in the WHERE condition.
Was this article helpful?