1

I would like to write a Postgres function which takes various stats from other tables and combines the results into a single row.

e.g.

select count(*) as acount from tableA
select count(*) as bcount from tableB
select count(*) as ccount from tableC

returning

acount, bcount, ccount   as a single record

Obviously the "count" functions listed above are a lot more complex than that, and may even be different amounts of counts for each table.

So ideally is it possible to store them as variables and then build a record from the variables ?

3 Answers 3

3

No need for variables, you can just combine everything into one select statement with subqueries:

select
(select count(*) from tableA) as acount,
(select count(*) from tableB) as bcount,
(select count(*)  from tableC) as ccount;
Sign up to request clarification or add additional context in comments.

3 Comments

Good, and useable but doesn't like if I make one of them have 2 cols like count(*), sum(items) . Anyway to cater for that ?
@blissweb just add another select for the sum.
For performance hack, discovered this works ... CONCAT(CAST(sum(noitems) AS VARCHAR(10)) , '-' , CAST(count(*) AS VARCHAR(10))) Maybe someone knows if that will save resources over 2 SELECTS.
2

You can use cross join

select * from
(select count(*) as acount from tableA) as a
,(select count(*) as bcount from tableB) as b
,(select count(*) as ccount from tableC) as c

2 Comments

Actually, this seems faster and allows for multiple aggregates on each subquery. Yay !
you can use a up-to-date version of cross join as well, happy to help select * from (select count(*) as acount from tableA) as a cross join (select count(*) as bcount from tableB) as b cross join (select count(*) as ccount from tableC) as c
0

You can also create a new type that consist of 3 bigint type.

CREATE TYPE mutli_count AS (
    _countt1 bigINT,
    _countt2 bigint,
    _countt3 bigINT
);

select( 
    (select count(*) from country),
    (select count(*) from states),
    (select count(*) from cities))::mutli_count;

Comments

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.