According to the postgres documentation, you add a key to an hstore column as follows:
UPDATE tab SET h = h || (\'c\' => \'3\');
But it seem
To avoid this you need to ensure the hstore is created as empty and not null. You can add an empty hstore to an existing table:
ALTER TABLE htest ADD h HSTORE NOT NULL DEFAULT '';
Or you can alter your existing hstore to empty:
ALTER TABLE htest ALTER COLUMN h SET NOT NULL;
ALTER TABLE htest ALTER COLUMN h SET DEFAULT '';
Please note that exiting values cannot be null when you set the column to 'NOT NULL'.
For Postgres version > 9.1:
UPDATE htest SET h = COALESCE(h, hstore('')) || hstore('foo', 'bar') WHERE t='key';
I think the problem here is that the hstore you have is null, and null OR some hstore is null.
The best solution I have, which is probably not the best solution, is to make the table with a default empty hstore rather than allowing null. Then your examples work as you would like:
postgres=# create table htest (t text, h hstore default hstore(array[]::varchar[]));
CREATE TABLE
postgres=# insert into htest (t) values ('key');
INSERT 0 1
postgres=# update htest set h = h || ('foo'=>'bar') where t='key';
UPDATE 1
postgres=# select * from htest;
t | h
-----+--------------
key | "foo"=>"bar"
(1 row)
I unfortunately do not see a cleaner way to create an empty hstore than hstore(array[]::varchar[])
but that doesn't mean there isn't a better way. You could incorporate this into your hstore update from before like so:
update htest set h = coalesce(h, hstore(array[]::varchar[])) || ('foo'=>'bar') where t='key';
This way you don't need to recreate the table. I find that fairly gross though. Hope this helps.
how about:
UPDATE htest SET h = COALESCE(h, '') || ('foo'=>'bar') WHERE t='key';