How to store arbitrary PostgreSQL data types in JSONB?

PostgreSQL’s JSONB data type allows you to store arbitrary JSON data in a structured format. This can be useful for storing data that does not fit neatly into a traditional relational database schema, such as nested or unstructured data.

To store arbitrary PostgreSQL data types in JSONB, you can use the to_jsonb function to convert the data to a JSONB object. This function accepts any PostgreSQL data type and converts it to a JSONB value.

For example, let’s say you have a table of customers with a column for their contact information. In traditional relational database design, you might have separate columns for the customer’s name, email address, phone number, and so on. However, if you want to store this information in a JSONB column instead, you can use the following query to insert a new customer record:

INSERT INTO customers (name, contact_info)
VALUES ('John Doe', to_jsonb(
'{"email": "", "phone": "555-1234", "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zip": "12345"}}'

This query creates a new customer record with the name “John Doe” and contact information in JSONB format. The contact information is a nested JSONB object that includes the customer’s email address, phone number, and address information.

To retrieve the contact information for a specific customer, you can use the -> operator to access the individual JSONB fields. For example:

SELECT name, contact_info->>'email' as email, contact_info->>'phone' as phone
FROM customers
WHERE name = 'John Doe';

This query retrieves the name, email address, and phone number for the customer with the name “John Doe”. The ->> operator is used to extract the values of the individual JSONB fields as text.

By storing arbitrary data types in JSONB format, you can take advantage of the flexibility and expressiveness of JSON while still benefiting from PostgreSQL’s powerful querying and indexing capabilities.

About Shiv Iyer 219 Articles
Open Source Database Systems Engineer with a deep understanding of Optimizer Internals, Performance Engineering, Scalability and Data SRE. Shiv currently is the Founder, Investor, Board Member and CEO of multiple Database Systems Infrastructure Operations companies in the Transaction Processing Computing and ColumnStores ecosystem. He is also a frequent speaker in open source software conferences globally.