EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

hstore in PostgreSQL

By Sohel SayyadSohel Sayyad

Home » Data Science » Data Science Tutorials » PostgreSQL Tutorial » hstore in PostgreSQL

hstore in PostgreSQL

Introduction to hstore in PostgreSQL

In order to consider the key-value pair as a single entity, the PostgreSQL hstore module implements the hstore data type, which can be used in various cases like data that is semi-structured or a row which is having multiple attributes that we cannot try to fetch very often. 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.

Syntax

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

column_name hstore

Explanation: The name of the column whose data type will be store.

How hstore data type works in PostgreSQL?

We need to enable the hstore extension in order to use the hstore data type. We can load the contrib module to the PostgreSQL instance with the help of the hstore extension. Syntax to create the extension for hstore is as follows:

CREATE EXTENSION hstore;

Hstore store the key and value pair where we have to add double quote around both key and value fields as follows:

“<key>”:”<value>”

The PostgreSQL hstore data type is used if the column’s value does not fit into the relational column. The PostgreSQL hstore column works dynamically, which means you do not need to specify the key prior to the table creation; you can just create a table with the hstore column and insert values with different keys later.

Examples to Implement hstore data type in PostgreSQL

In order to understand the examples of the hstore data type, we will create a table named ’employee’ containing the hstore data type.

Create a table ’employee’ with hstore data type using CREATE TABLE statement as follows:

CREATE TABLE employee (
id serial primary key,
name VARCHAR (255),
data hstore
);

the data column will have the properties of the employee like job type, salary, and contact number. The data column of the employee table is of the hstore data type.

Now, we will insert rows into the employee table with the help of the following INSERT INTO statement as follows:

INSERT INTO employee (name, data)
VALUES
(
'Oliver Jake',
'"contact_number" => "9912002430",
"salary" => "30000",'
);

Here you can see the list of comma-separated key-value pairs data is inserted into the hstore column. Illustrate the content of the employee table using the following SELECT statement and snapshot:

SELECT * FROM employee;

hstore in PostgreSQL1

Now we will insert another row using the INSERT INTO statement as follows.

INSERT INTO employee (name, data)
VALUES
(
'Jacob John',
'"contact_number" => "9912002440",
"salary" => "40000",'
);

Illustrate the content of the employee table using the following SELECT statement and snapshot:

SELECT * FROM employee;

hstore in PostgreSQL2

Example #1 – Retrieve the data from hstore column

We can fetch the data from the hstore column by using the following statement.

Code:

SELECT
data
FROM
employee;

Output:

hstore in PostgreSQL3

Example #2 – Retrieve the data for the specific key of hstore

In order to fetch the particular key of the data column of the hstore type, we can use the arrow (->) operator as follows:

Code:

SELECT
data -> 'salary' AS salary
FROM
employee;

Output:

hstore in PostgreSQL4

Example #3 – Where clause with key-value

We can add a condition in where clause in order to filter the rows with the help of the arrow (->) operator:

Code:

SELECT
name,
data -> 'contact_number' AS Contact
FROM
employee
WHERE
data -> 'salary' = '30000';

Output:

hstore in PostgreSQL5

Example #4 – INSERT a key-value pair

We can add a key-value pair by using the hstore column. Here we will add the job type in the data column of the Employee table by using the following statement:

Code:

SELECT
name,
data -> 'job_type' AS JobType
FROM
Employee;

Output:

hstore in PostgreSQL6

Example #5 – Update the key-value pair

We can modify the key-value pair of the hstore column. Use the following statement to update the value of the “job_type” key to “Part”.

Code:

UPDATE employee
SET data = data || '"job_type"=>"Part"' :: hstore;

Output:

Update the key-value pair

Example #6 – Delete the key-value pair

We can delete the key-value pair from the data column, which is of type store, by using the following statement.

Here we will delete the key-value pair  “job_type”=>”Part” in the data column:

Code:

UPDATE employee
SET data = delete(data, 'job_type');

Output:

Delete the key-value pair

Example #7 – Fetch all keys stored in hstore column

In order to fetch all keys stored in hstore type column, we have to use the keys() function or skey() function as follows:

Code:

SELECT
akeys (data)
FROM
employee;

Output:

keys stored

The skey() function provided by the PostgreSQL is used to fetch the result as a set:

Code:

SELECT
skeys (data)
FROM
employee;

Output:

hstore in PostgreSQL10

Example #8 – Fetch all values from the data column

Similar to the keys, we can fetch all values from the data column, which is of hstore type, by using the  avals() function or svals() function provided by PostgreSQL:

Code:

SELECT
avals (data)
FROM
employee;

Output:

data column

The svals() function provided by the PostgreSQL is used to fetch the result as a set:

Code:

SELECT
svals (data)
FROM
employee;

Output:

hstore in PostgreSQL12

Example #9 – Convert hstore data to JSON data

We can use the PostgreSQL’s hstore_to_json() function for converting the hstore data to JSON:

Code:

SELECT
name,
hstore_to_json (data) json_data
FROM
employee;

Output:

JSON data

Example #10 – Convert hstore data to sets

We can use PostgreSQL’s each() function for converting the hstore data to sets.

Code:

SELECT
name,
(EACH(data) ).*
FROM
employee;

Output:

sets

Conclusion

We hope from the above article you have understood how to use the PostgreSQL hstore data type and how the PostgreSQL hstore data type works to store the data in key-value pair. Also, we have added some examples of the PostgreSQL hstore to understand it in detail.

Recommended Articles

This is a guide to the hstore in PostgreSQL. Here we discuss an introduction to hstore in PostgreSQL, syntax, how it works, and examples for better understanding. You can also go through our other related articles to learn more –

  1. PostgreSQL IF Statement
  2. PostgreSQL For Loop
  3. PostgreSQL Primary Key
  4. PostgreSQL List Tables

All in One Data Science Bundle (360+ Courses, 50+ projects)

360+ Online Courses

50+ projects

1500+ Hours

Verifiable Certificates

Lifetime Access

Learn More

2 Shares
Share
Tweet
Share
Primary Sidebar
PostgreSQL Tutorial
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
    • PostgreSQL List Databases
    • PostgreSQL Rename Database
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL repository
    • PostgreSQL shared_buffer
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL Incremental Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Special Offer - All in One Data Science Bundle (360+ Courses, 50+ projects) Learn More