Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easily output the hstore format of a table row

Is there a better way to get a row of a table into hstore format than going

SELECT hstore(ARRAY['col1','col2','col3'], ARRAY[col1::text, col2::text, col3::text]) FROM tbl;

It works, but I figure there has to be a better way than typing out each column. hstore takes a record type for input, but I couldn't figure out how to feed the single-row producing query into the function and make it happy. Postgres version 9.0.4.

like image 690
EvilAmarant7x Avatar asked Jan 10 '12 20:01

EvilAmarant7x


People also ask

What is Hstore format?

This module implements the hstore data type for storing sets of key/value pairs within a single PostgreSQL value. This can be useful in various scenarios, such as rows with many attributes that are rarely examined, or semi-structured data. Keys and values are simply text strings.

How to store key value in PostgreSQL?

Introduction to Key-Value StoreCreate a database schema for any situation with the power of JSON. Working with geospatial data in Postgres. PostgreSQL has several extensions so spatial and geometry data can be treated as first-class objects within your PostgreSQL database.


1 Answers

Yes - you can cast row to hstore type with hstore() function.

SELECT hstore(tbl.*) FROM tbl;

Works for me:

filip@filip=# select hstore(foo.*) from foo;
         hstore
------------------------
 "bar"=>"1", "baz"=>"2"
(1 row)

See http://www.postgresql.org/docs/9.0/static/hstore.html#HSTORE-FUNC-TABLE

like image 140
filiprem Avatar answered Sep 19 '22 19:09

filiprem