Home > Database > Mysql Tutorial > Why Can't I Use Aliases in the WHERE Clause of a PostgreSQL Query?

Why Can't I Use Aliases in the WHERE Clause of a PostgreSQL Query?

Linda Hamilton
Release: 2024-12-27 12:45:11
Original
899 people have browsed it

Why Can't I Use Aliases in the WHERE Clause of a PostgreSQL Query?

Referencing Alias in WHERE Clause: An Exploration

In PostgreSQL (psql), it's not directly possible to reference aliases in the WHERE clause due to the execution order. The WHERE clause is executed before aliases are applied, leading to the error "column "_year" does not exist."

This occurs because the WHERE clause operates on the original column names, and the alias is only applied later, during the result set generation. Therefore, the alias is not recognized when the WHERE clause is executed.

To resolve this issue, the query must be rewritten to use the original column name directly in the WHERE clause. For example, consider the query:

SELECT
    SUBSTRING(pk, 6, 2)::INT AS _year
FROM
    listing
WHERE
    _year > 90;
Copy after login

This query will fail with the error "column "_year" does not exist." To fix it, the alias must be replaced with the original column name in the WHERE clause:

SELECT
    SUBSTRING(pk, 6, 2)::INT AS _year
FROM
    listing
WHERE
    SUBSTRING(pk, 6, 2)::INT > 90;
Copy after login

The above is the detailed content of Why Can't I Use Aliases in the WHERE Clause of a PostgreSQL Query?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template