Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update PostgreSQL hstore field with sql variable

I have table files which has hstore column details. In my sql statement I insert data to it:

  UPDATE files SET details =  'new_users=>new_users_count'::hstore where id = v_file_id;

but I want to update this hstore field not with string but with variable that is available in my sql statement. How can I do this?

like image 668
Mateusz Urbański Avatar asked Oct 20 '15 07:10

Mateusz Urbański


People also ask

How to query data from an hstore column in PostgreSQL?

Querying data from an hstore column is similar to querying data from a column with native data type using the SELECT statement as follows: Postgresql hstore provides the -> operator to query the value of a specific key from an hstore column.

How to update data in a PostgreSQL table using update?

Use the PostgreSQL UPDATE statement to update data in one or more columns of a table. Use the RETURNING clause to return the updated rows from the UPDATE statement Was this tutorial helpful ? What is PostgreSQL?

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.

Can I DUMP/RESTORE PostgreSQL hstore?

As of PostgreSQL 9.0, hstore uses a different internal representation than previous versions. This presents no obstacle for dump/restore upgrades since the text representation (used in the dump) is unchanged. In the event of a binary upgrade, upward compatibility is maintained by having the new code recognize old-format data.


1 Answers

PL/pgSQL can't detect variables inside a string literal. You need to use the "constructor" method of the hstore type to pass a variable:

UPDATE files 
   SET details = hstore('new_users', p_new_user_count)
where id = v_file_id;

If p_new_user_count is defined as a number (rather than a varchar or text) you need to cast this to a text value:

UPDATE files 
   SET details = hstore('new_users', p_new_user_count::text)
where id = v_file_id;

Edit after the question was changed:

To do this for multiple variables you can either concatenate two hstore values:

details = hstore('new_users', p_new_user_count::text)||hstore('post_count', p_post_count::text)

or use arrays:

details = hstore(array['new_users','post_count'], array[p_user_count, p_post_count]::text[]);

This is all documented in the manual: http://www.postgresql.org/docs/current/static/hstore.html

like image 82
a_horse_with_no_name Avatar answered Sep 19 '22 17:09

a_horse_with_no_name