3

Can I define a new column and use it in the same query?

For example,

Select 
    student, age + 10 as trueage, 
    case when trueage < 25 then 'False' else 'True' end
From 
    class

Thank you in advance for helping!

4
  • 2
    It is not possible. You probably don't understand the order of sql clause evaluation. Where conditions are evaluated first, matching rows are returned, then columns specified after select clause are evaluated. I think you can use "age + 10" in both places (in select clause and in where clause). Most of SQL engines will take care of it. Commented Aug 2, 2015 at 17:58
  • What RDBMS are you using? Netezza apparently allows this for example stackoverflow.com/q/24246283/73226 Commented Aug 2, 2015 at 18:10
  • I'm using SQL Server. It's funny because Microsoft Access allows it, too. Commented Aug 2, 2015 at 18:46
  • 2
    @Konrad, here is a good article showing many ways to use CROSS APPLY. One of them is to "Introduce New Columns". Commented Aug 3, 2015 at 1:01

3 Answers 3

4

CROSS APPLY would be handy here. Here is a nice article showing many uses of it.

Select
    student
    ,trueage
    ,case when trueage < 25 then 'False' else 'True' end
From
    class
    CROSS APPLY
    (
        SELECT age + 10 as trueage
    ) AS CA

It is mostly useful when you have complex formulas with several levels, something like this:

Select
    student
    ,trueage
    ,AgeFlag
From
    class
    CROSS APPLY
    (
        SELECT age + 10 as trueage
    ) AS CA1
    CROSS APPLY
    (
        SELECT case when trueage < 25 then 'False' else 'True' end AS AgeFlag
    ) AS CA2
Sign up to request clarification or add additional context in comments.

Comments

1

If you consider using a subquery "same query" then yes.

select student,
       trueAge,
       case when trueAge < 25 then 'false' else 'true' end as someColumn
from ( 
    select student, age + 10 as trueAge
    from table
) thingy

There are likely other ways to do this as well, this is only one of them.

Comments

1

Something like:

  Select student, age + 10 as trueage, 
   case when (age + 10) < 25 then 'False' else 'True' end 
   from class

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.