5

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.

1 Answer 1

14

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
Sign up to request clarification or add additional context in comments.

2 Comments

What if any one row contain value which can not be cast in integer? It will give ERROR: invalid input syntax for integer: so how to get desired result by skipping that row?
@RockStar: Use a WHERE clause and a regular expression: where (other->'height_in') ~ '^\d+$'. The need to do this points to an error in your application code, though. Fix that.

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.