Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use aggregate functions on PostgreSQL HStore values?

Can I perform aggregate queries on values in an hstore column? For example, I'd like to determine the SUM of a count field in the store.

like image 324
Carson Avatar asked Nov 18 '11 23:11

Carson


People also ask

What is Hstore in Postgres?

hstore is a PostgreSQL extension that implements the hstore data type. It's a key-value data type for PostgreSQL that's been around since before JSON and JSONB data types were added.

What are PostgreSQL aggregate functions?

Like most other relational database products, PostgreSQL supports aggregate functions. An aggregate function computes a single result from multiple input rows. For example, there are aggregates to compute the count , sum , avg (average), max (maximum) and min (minimum) over a set of rows.

Which of the following is not PostgreSQL aggregate functions select one like min avg count?

Which of the following is not a built in aggregate function in SQL? Explanation: SQL does not include total as a built in aggregate function. The avg is used to find average, max is used to find the maximum and the count is used to count the number of values. 2.


1 Answers

Yes. But values are stored as text, so you have to cast them to an appropriate data type first. So, to sum heights in inches, which are stored in an hstore in the column "other"

CREATE TABLE my_table (
  id integer primary key,
  other hstore
);
insert into my_table values 
(1, hstore('height_in', '72') || hstore('weight_lbs', '180')),
(2, hstore('height_in', '65') || hstore('girth_in', '42'));

select sum((other->'height_in')::integer) sum_of_height
from my_table;

sum_of_height
--
137
like image 150
Mike Sherrill 'Cat Recall' Avatar answered Sep 27 '22 23:09

Mike Sherrill 'Cat Recall'