SQL

Extract and Query JSON Data in PostgreSQL

Explore how PostgreSQL's JSON functions like `->>`, `jsonb_array_elements`, and `jsonb_each_text` can be used to effectively query and manipulate JSON data stored in columns.

-- Assuming a table 'products' with a JSONB column 'details'
SELECT
    product_id,
    details->>'name' AS product_name,
    details->'dimensions'->>'width' AS width,
    details->'dimensions'->>'height' AS height,
    (
        SELECT string_agg(tag->>0, ', ')
        FROM jsonb_array_elements(details->'tags') AS tag
    ) AS tags_list
FROM
    products
WHERE
    details->>'category' = 'Electronics'
    AND (details->'price')::numeric > 100;
How it works: This snippet demonstrates how to query and extract data from a JSONB column in PostgreSQL. It uses the `->>` operator to extract text values from JSON objects, `->` for JSON object/array access, and `jsonb_array_elements` combined with `string_agg` to flatten a JSON array into a comma-separated string. The `WHERE` clause shows filtering capabilities based on JSON values, illustrating powerful in-database JSON manipulation.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs