Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgreSQL hstore if contains value

Tags:

sql

postgresql

Is there a way to check if a value already exists in the hstore in the query itself.

I have to store various values per row ( each row is an "item"). I need to be able to check if the id already exists in database in one of the hstore rows without selecting everything first and doing loops etc in php. hstore seems to be the only data type that offers something like that and also allows you to select the column for that row into an array.

Hstore may not be the best data type to store data like that but there isn't anything else better available.

The whole project uses 9.2 and i cannot change that - json is in 9.3.

like image 767
Mauro Tamm Avatar asked Nov 27 '14 15:11

Mauro Tamm


People also ask

Is Hstore deprecated?

hstore is deprecated. Use jsonb . @danger89 Actually, it's not formally deprecated, though I don't think there's any reason to use it in favour of jsonb anymore.

What is PG Hstore?

pg-hstore is a node package for serializing and deserializing JSON data to hstore format.

Should I use JSON in Postgres?

The comprehensive JSON support in PostgreSQL is one of its best-loved features. Many people – particularly those with a stronger background in Javascript programming than in relational databases – use it extensively.


1 Answers

The exist() function tests for the existence of a key. To determine whether the key '42' exists anywhere in the hstore . . .

select *
from (select test_id, exist(test_hs, '42') key_exists
      from test) x
where key_exists = true;
test_id  key_exists
--
2        t

The svals() function returns values as a set. You can query the result to determine whether a particular value exists.

select *
from (select test_id, svals(test_hs) vals
      from test) x
where vals = 'Wibble';

hstore Operators and Functions


create table test (
  test_id serial primary key,
  test_hs hstore not null
);

insert into test (test_hs) values (hstore('a', 'b'));
insert into test (test_hs) values (hstore('42', 'Wibble'));
like image 135
Mike Sherrill 'Cat Recall' Avatar answered Nov 09 '22 15:11

Mike Sherrill 'Cat Recall'