🐘 PostgreSQL Intermediate

What is the hstore extension in PostgreSQL?

Answer

hstore is a PostgreSQL extension that stores key-value pairs in a single column. Enable: CREATE EXTENSION hstore;. Store: INSERT INTO products (attrs) VALUES ('color => red, size => XL, material => cotton');. Access a key: attrs->'color' returns 'red'. Check key exists: attrs ? 'color'. All keys: akeys(attrs). All values: avals(attrs). Convert to JSON: hstore_to_json(attrs). Update a key: attrs || 'color => blue'. Delete a key: delete(attrs, 'color'). Index: CREATE INDEX ON products USING GIN(attrs);. In modern PostgreSQL, JSONB is generally preferred over hstore for new applications, as it supports nested structures and has better tooling.