DerrickHo328
DerrickHo328

Reputation: 4886

Postgresql is this 1 query or multiple?

I am new to postgresql (and SQL in general) and my biggest concern right now is optimization. Below I have a simple query. However I believe that it is just one query. However, it could also be the case that it is just 3 queries (the ones that exist new the union all). Or it might actually be 6 queries since there are actually 6 select statements.

with foo as (
    select * from tableA
), bar as (
    select * from tableB
), zeta as (
    select * from tableC
)
select * from foo
union all
select * from bar
union all
select * from zeta

How many queries is the above query?


also...

The reason this question is important is because, I do not know whether I should write my query like the above or to simply just make all the queries separate.

select * from tableA; --query 1
select * from tableB; --query 2
select * from tableC; --query 3

Upvotes: 0

Views: 50

Answers (1)

klin
klin

Reputation: 121834

Formally it is one complex query (as 'complex sentence'), which contains six 'simple' queries. You do not need these with statements though, as in fact they do nothing. Your first query should look like this:

select * from tableA
union all
select * from tableB
union all
select * from tableC;

In this case you'll obtain one set of rows as a result. If you execute

select * from tableA;
select * from tableB;
select * from tableC;

you will have three separate sets of rows.

Upvotes: 1

Related Questions