Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the per-row number of keys of hstore data in postgresql

I have a hstore column in my postgresql database. Each row of the database has a different number of keys/values in the hstore-column. How can i get the number of keys/values for each row?

like image 868
Funkwecker Avatar asked Sep 12 '13 13:09

Funkwecker


People also ask

What is PostgreSQL hstore and how to use it?

In order to consider the key-value pair as a single entity, the PostgreSQL hstore module implements the hstore data type, which can be used in various cases like data that is semi-structured or a row which is having multiple attributes that we cannot try to fetch very often. The data type of keys and values is a string.

What is the data type of keys and values in PostgreSQL?

The data type of keys and values is a string. The PostgreSQL hstore data type is a similar dictionary we are using with other programming languages; The PostgreSQL hstore is specific to the column. It is not necessary to define the keys beforehand. Explanation: The name of the column whose data type will be store.

How to query the value of a specific key from hstore?

Postgresql hstore provides the -> operator to query the value of a specific key from an hstore column. For example, if we want to know ISBN-13 of all available books in the books table, we can use the -> operator as follows:

How does PostgreSQL row_number () function work?

How does PostgreSQL ROW_NUMBER function work? The ROW_NUMBER () function operates on a set of rows which are termed s a window.mIf the PARTITION BY clause is specified then the row number will increment by one and will start with one.


2 Answers

select hstore_column, 
       array_length(akeys(hstore_column), 1) as num_keys
from the_table
like image 171
a_horse_with_no_name Avatar answered Oct 20 '22 19:10

a_horse_with_no_name


You can use one of hstore functions, to convert hstore to another data type that can retrieve number of elements. For instance, you can use avalue to count the number of keys on a hstore value:

SELECT id, array_length(avals(my_hstore_field), 1) AS count_keys
FROM mytable;

On the docs there is a nice example to get all the keys and the number of occurrences of it that may be useful for you:

SELECT key, count(*) FROM
  (SELECT (each(h)).key FROM testhstore) AS stat
  GROUP BY key
  ORDER BY count DESC, key;
like image 30
MatheusOl Avatar answered Oct 20 '22 18:10

MatheusOl