Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use Aggregate Function on Unnested Array in Postgres?

Trying to use Postgres var_samp() function on multiple columns in my db and want to do it without subqueries/CTEs, desire speed.

I’ve tried this:

select
var_samp(array[obs1,obs2]) as varsample
    from my_table

Tried this based off another answer, couldn’t get it to work (I’m sure I’m the issue):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

select
var_samp(my_col)
    from (select unnest(array[obs1, obs2])as my_col from my_table)

I’ve had success is using CTEs, but trying to avoid them:

WITH cte_raw_data as (
        select
            unnest(array[obs1, obs2])as my_col
        from my_table
        ),
cte_var_samp as (
        select
            var_samp(my_col) as my_var_samp
        from cte_raw_data   
)
SELECT * FROM cte_var_samp

my_table data below, thank you for helping me:

"obs1" "obs2"
74.002 74.03
73.992 73.995
74.024 73.988
73.996 74.002
74.007 73.992
73.994 74.009
74.006 73.995
74.003 73.985
73.995 74.008
74 73.998
73.998 73.994
74 74.004
74.002 73.983
73.967 74.006
74.014 74.012
73.984 74
74.012 73.994
74.01 74.006
74.002 73.984
74.01 74
74.001 73.988
73.999 74.004
73.989 74.01
74.008 74.015
73.984 73.982

>Solution :

You can simplify that query to

WITH cte_raw_data AS (
    SELECT unnest(array[obs1, obs2]) AS my_col
    FROM my_table
)
SELECT var_samp(my_col) AS my_var_samp
FROM cte_raw_data;

or

SELECT var_samp(my_col) AS my_var_samp
FROM (
    SELECT unnest(array[obs1, obs2]) AS my_col
    FROM my_table
) AS cte_raw_data;

but really you just want to use unnest as a lateral table function:

SELECT var_samp(my_col) AS my_var_samp
FROM my_table, unnest(array[obs1, obs2]) AS my_col;

Notice that all these queries are doing the same thing and will have the same query plan and same execution speed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading