1

I want to rewrite the following query by assigning a "variable name" to the nested query.

select lastname 
  from table2 
 where firstname = (select name from table1 where val="whatever")

I want the query to look something like this:

( select name 
    from table1 
   where val = "whatever") as retrieved_name;

select lastname 
  from table2 
 where firstname = retrieved_name

Is it possible in pure SQL?

1
  • 1
    @a_horse_with_no_name. I guess making SQL looks like every other programming language which have variables... Commented May 6, 2012 at 13:18

3 Answers 3

3

Is it possible in pure SQL?

No.

You don't have variables with "pure SQL". You can have variables with Oralce-PL\SQL and etc'.

Sign up to request clarification or add additional context in comments.

Comments

1

Sort of, if you're willing to use a join instead of a sub-select and you're not using MySQL you can use a CTE (Common Table Expression):

with retrieved_name as ( 
  select name 
    from table1 
   where val = "whatever" 
         )
select lastname
  from table2 t2
  join retrieved_name t1
    on t2.firstname = t1.name

As a_horse_with_no_name pointed out this is identical to:

select lastname
  from table2 t2
  join ( select name 
           from table1 
           where val = "whatever" ) t1
    on t2.firstname = t1.name

I actually prefer the inline view of the second example rather than a CTE unless the query is ridiculous but it's just a personal preference.

2 Comments

In this case the CTE can easily be replaced by a derived table ("inline view"). Just replace the retrieved_name with the select from the with clause.
@a_horse_with_no_name, of course! I'm assuming the actual query is more complicated.
0

You can do something like this instead

select name as retrieved_name from table1 where val="whatever"); select lastname from table2 where firstname=retrieved_name

1 Comment

No you can not. (Not just because of the unmatched ))

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.