Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

226
Views
Postgresql get the most common value in array

I have a table with column with array values (after group by and array_agg function)

COLUMN_VALUE          | other_columns...
-----------:          | -------:
 {0.45,0.45,0.97,0.99}|        ..
 {0.45,0.45,0.85,0.99}|        ..
 {0.45,0.45,0.77,0.99}|        ..
 {0.45,0.45,0.10,0.99}|        ..

How do I get the most frequent value? (0.45 for each row for this case)

My guess goes to unnest and groupby again but I am trying to find something more robust and faster.

Query I am using to build the table


select column1, column2, column3, array_agg(column4) as prices
from tb
where some conditions
group by 1, 2, 3
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can get the most frequent value during aggregation using the mode() aggregate:

select column1, column2, column3, 
       array_agg(column4) as prices
       mode() within group (order by column4 desc) as most_frequent_price
from tb
where ...
group by 1, 2, 3

Online example

over 4 years ago · Santiago Trujillo Report

0

You can use unnest() and some aggregation logic:

select t.*, m.mode
from t cross join lateral
     (select el as mode
      from unnest(t.column_value) el
      group by el
      order by count(*) desc
      limit 1
     ) m;

I've called this mode because that is the statistical term for the most common value.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!