Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store query result in variables to use in another query in Postgresql

Tags:

postgresql

I am new to Postgresql. Please help me to solve it.

Suppose I have three table called 'table_1', 'table_2' & 'table_3'

I want to get data from table_3 that is related to table_1 and table_2

Such as I am retrieving value_1 and value_2 from table_1 and table_2

Query 1:

Select value_1 From table_1

Query 2:

Select value_2 From table_2

Now I want to use these values in table_3

Query 3:

Select * from table_3 where column_1 = value_1 and column_2 = value_2

How to store first 2 values in variables and use it in third query?

like image 550
Devil's Dream Avatar asked Jan 04 '16 07:01

Devil's Dream


People also ask

How do I assign a SQL query result to a variable in PostgreSQL?

In PostgreSQL, the select into statement to select data from the database and assign it to a variable. Syntax: select select_list into variable_name from table_expression; In this syntax, one can place the variable after the into keyword.

How do I assign a variable in PostgreSQL?

Variables can be assigned default values within the declaration section of a PL/pgSQL code block. This is known as default value assignment, and is done by using the assignment operator (:=) on the same line as the variable's declaration.


1 Answers

You can use the following query:

with v1 as (select value_1 from table_1),
     v2 as (select value_2 from table_2)
select * from table_3 where column_1 = (select value_1 from v1) 
and column_2 = (select value_2 from v2);

If v1 and v2 are having multiple rows you can use 'in' operator instead of '=' operator.

For more information, please check the PostgreSQL documentation here.

You can also check a post similar to this on Stackoverflow here.

like image 175
Abhishek Anand Avatar answered Oct 04 '22 20:10

Abhishek Anand