PostgreSQL – hstore Data Type
The ‘hstore’ module in PostgreSQL is designed to implement a data type for storing key-value pairs within a single value. This feature is particularly useful for handling semi-structured data or cases where attributes are rarely queried individually. The ‘hstore’ data type excels in scenarios involving multiple rows with numerous attributes that might not be frequently accessed.
Syntax
variable_name hstore;
To use the hstore data type, you first need to enable the hstore extension. It’s pretty simple to enable the ‘hstore‘ extension for using the hstore data type using the below command:
CREATE EXTENSION hstore;
PostgreSQL hstore Data Type Examples
Now let’s look into a few examples for better understanding.
Example 1: Creating and Populating a Table
First we create a ‘books'
table with ‘id'
as the primary key that identifies the book, the ‘title'
as the title of the products and ‘attr'
that stores attributes of the book such as ISBN, weight, and paperback. The data type of the attr column is the hstore using the below command:
CREATE TABLE books (
id serial PRIMARY KEY,
title VARCHAR(255),
attr hstore
);
INSERT INTO books (title, attr)
VALUES
(
'Winds Of Winter',
'"paperback" => "2403",
"publisher" => "Bantam Spectra/US & Voyager Books/UK",
"language" => "English",
"ISBN-13" => "978-1449370000",
"weight" => "13.2 ounces"'
),
(
'A Dance with Dragons',
'"paperback" => "2553",
"publisher" => "Bantam Spectra/US & Voyager Books/UK",
"language" => "English",
"ISBN-13" => "978-1449370001",
"weight" => "14.2 ounces"'
),
(
'A Dream of Spring',
'"paperback" => "2683",
"publisher" => "Bantam Spectra/US & Voyager Books/UK",
"language" => "English",
"ISBN-13" => "978-1449370002",
"weight" => "15.7 ounces"'
);
SELECT
attr
FROM
books;
Output:

Example 2: Querying Specific Key-Value Pairs
PostgreSQL’s ‘hstore’ module also supports the -> operator, which allows you to extract the value associated with a specific key from an ‘hstore’ column. For instance, to get the ISBN-13 values for all books, use the following query:
SELECT attr -> 'ISBN-13' AS isbn
FROM books;
Output:

Important Points About PostgreSQL hstore Data Type
- Ideal for scenarios where the schema may change frequently or where attributes are not uniformly applicable to all rows.
- Useful for storing and querying semi-structured data without the need for extensive schema changes.
- You can query specific key-value pairs using operators like ‘->’ to extract values and ‘@>’ to check for the presence of specific key-value pairs.
- The hstore type is best for relatively small sets of key-value pairs. For more complex hierarchical data or large-scale use, consider JSONB or other types.