I am planning to migrate a large application from SAP (formerly Sybase) SQL Anywhere to Postgres.
SQL Anywhere does let you use an Alias in the WHERE clause. That has been supported for over 10 years, and we use it a lot to write nice, clear queries.
See: https://help.sap.com/doc/06af1adfbfbc491fabc14f005dfe15dc/17.0/en-US/SQL-Anywhere-Server-Users-Guide-en.pdf
Page 173 says:
Name space occlusion
Aliases can be used anywhere in the SELECT block in which they are defined, including other SELECT list expressions that in turn define additional aliases.
Cyclic alias references are not permitted. If the alias specified for an expression is identical to the name of a column or variable in the name space of the
SELECT block, the alias definition occludes the column or variable.
The manual shows this example, which is legal in SQL Anywhere:
SELECT DepartmentID AS DepartmentName
FROM Departments
WHERE DepartmentName = 'Marketing'
I can provide additional proof that this works. Here is a bug report:
https://sqlanywhere-forum.sap.com/questions/28899/select-aliases-not-working-properly-inside-other-statements-referenced-by-a-where-clause
My existing application uses this feature extensively.
I have seen a lot of other posts asking to use an Alias in the WHERE clause, not only in Postgres but for SQL Server, Oracle and mySQL.
In my many years using SQL Server, I have run into the need to write duplicate expressions many, many times, and it seems like something which the parser could be enhanced to handle.
Basically, the feature set which SQL Anywhere has is:
- Allow a Column Alias in the WHERE clause
- Allow a Column Alias in the HAVING clause
- Allow a Column Alias in the GROUP BY clause (Postgres already allows this)
- Allow a Column Alias in the ORDER BY clause (Postgres already allows this)
I know how to write CTEs, and I think they are very nice, so yes, there is a workaround. And yes, I see the syntax above, which is OK.
Sincerely,
Victor Reinhart