So lets say i have a query like this
SELECT a as d,b,c FROM myTable
WHERE a=1;
Is it possible instead of a=1 to type something like SELECTED.1 = 1 or to somehow extract allias original name since d=1 doesn't work
Column aliases can be used for derived columns. Column aliases can be used with GROUP BY and ORDER BY clauses. We cannot use a column alias with WHERE and HAVING clauses.
In PROC SQL, a column alias can be used in a WHERE clause, ON clause, GROUP BY clause, HAVING clause, or ORDER BY clause. In the ANSI SQL standard and ISO SQL standard, the value that is associated with a column alias does not need to be available until the ORDER BY clause is executed.
Note: The WHERE clause is not only used in SELECT statements, it is also used in UPDATE , DELETE , etc.!
Standard SQL disallows references to column aliases in a WHERE clause. This restriction is imposed because when the WHERE clause is evaluated, the column value may not yet have been determined.
It's not possible to do this because of internal complexities about when the WHERE clause gets evaluated. But if the thing you are aliasing is a long expression that you'd rather not repeat, there is a typical solution to this. From https://forums.oracle.com/forums/thread.jspa?threadID=1107532:
The standard solution to this is, you move the query into an inline view (without the where-clause predicate), and then add the where-clause predicate, using the alias, in the outer query.
So something like this:
select ... from (select ... here complex expression that is aliased ... from ... where ) A where ... here condition that uses the A.alias column ...
In your example case, that would be:
SELECT d, b, c
FROM ( SELECT a AS d, b, c FROM myTable ) AS myAliasedTable
WHERE d = 1
But of course, this wouldn't make sense in your literal example. If the thing you are aliasing is just a column name, then just use the actual column name in the WHERE, no real drawback in that case.
Also note that if you do use this method, you should put as much of the WHERE clause as you can in the internal query (meaning the parts that don't reference an aliased column) to limit the size of the resulting aliased table. For example, if you also wanted to test on b
in your example, that would be:
SELECT d, b, c
FROM (
SELECT a AS d, b, c
FROM myTable
WHERE b = 1
) AS myAliasedTable
WHERE d = 1
Use a common table expression (CTE) e.g.
WITH T
AS
(
SELECT a as d, b, c
FROM myTable
)
SELECT *
FROM T
WHERE d = 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With