I have a big sql query and its difficult to manage, what I need help ifI can do anything like -
store the inner queries in variables and use variable as reference in the outer queries example
var1 = select * from customer
var2 = select * from product
var3= select custid from var1
and finally
select a.customername,b*,c* from var1 as a, var2 as b , var3 as c where a.custid = c.c_id and
a.custid = b.custid
Note I am not a database person, I am a java programmer
CodePudding user response:
You can use CTEs (Common Table Expressions) to simplify the main query. For example, your query can be rephrased as:
with
a as (
-- big complex query #1 here
),
b as (
-- big complex query #2 here
),
c as (
-- big complex query #3 here
)
select a.customername, b.*, c.* -- the main query starts at this line
from a
join b on b.custid = a.custid
join c on c.c_id = a.custid
The main query can have references to any of the CTEs (a
, b
, or c
). Each CTE can alse have references to the previously defined CTEs; in your example, the third one will probably reference the first one.