0

I have what will end up being a complex query where certain parts will often be repeated. I would therefore like to store the results of some sub queries into variables which can then be used in the main query.

For example I would like to set the variable 'variable_id' to be equal to a SELECT query and variable_school_id to be equal to another SELECT query:

variable_id integer := (SELECT id FROM account WHERE email = '[email protected]');
variable_school_id integer := (SELECT school FROM account WHERE email = '[email protected]');

Then I would like to make use of those variables in a query that would look like:

select * from doctor where account_id = variable_id AND school = variable_school_id ;

How do I go about doing this?

1 Answer 1

1

Can't you just use CTEs?

with params as (
      SELECT id, school
      FROM account
      WHERE email = '[email protected]'
     )
select d.*
from params cross join
     doctor d
     on d.account_id = params.id and d.school = params.school;
Sign up to request clarification or add additional context in comments.

4 Comments

That works for this basic example but I'm going to end up with a much more complex query with many more variables and CASE instances. So would like to do it with variables if possible?
@Charlie . . . I don't understand what you need. You can make the params CTE as complex as you like.
I didn't think that you could reference the params within a subquery. I get the error, ERROR: invalid reference to FROM-clause entry for table "params" HINT: There is an entry for table "ref_user", but it cannot be referenced from this part of the query.
@Charlie . . . You have to include the parameters in any subquery where you reference them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.