2

When I am running a query like that it works perfectly:

SELECT 10 as a;

But when I am using the column a

SELECT 10 as a, (a - 1) as b

I get following error: Unknown column 'a' in 'field list'

Why isn't it working that way?

3
  • 1
    You can't use an alias in the same select query
    – Manav
    Commented Sep 17, 2017 at 13:55
  • because a is not a column Commented Sep 17, 2017 at 14:04
  • "An alias can be used in a query select list to give a column a different name. You can use the alias in GROUP BY, ORDER BY, or HAVING clauses to refer to the column" (Problems with Column Aliases). Commented Sep 17, 2017 at 15:11

3 Answers 3

6

You can't reuse an alias in the same SELECT statement in which it was defined. Perhaps the closest thing to what you want to do here would be this:

SELECT
    t.a,
    (t.a - 1) AS b
FROM (SELECT 10 AS a FROM dual) t;
3

You could also be using user variables.

SET @a := 10;
SELECT
     @a AS a
  , (@a - 1) AS b
FROM DUAL;

Rewritten to one query

SELECT
     @a AS a
  , (@a - 1) AS b
FROM
 (SELECT @a := 10) AS init_user_param ;

More optimal

SELECT 10 AS a , 9 AS b FROM DUAL;

0

You can try like below.

select t1.a,(t1.a-1) as b from  (SELECT 10 as a) t1;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.