Home > Database > Mysql Tutorial > How to Query JSON and JSONB Data in PostgreSQL?

How to Query JSON and JSONB Data in PostgreSQL?

Mary-Kate Olsen
Release: 2025-01-18 19:32:02
Original
258 people have browsed it

How to Query JSON and JSONB Data in PostgreSQL?

Quering JSON Datatype Fields in PostgreSQL

PostgreSQL 9.2 introduced the JSON datatype, but advanced querying of fields within JSON records required custom functions. PostgreSQL 9.3 expanded these capabilities with operators and functions.

Specifically, for a table with a JSON column named "data":

Postgres 9.3:

  • To find a record by name:
SELECT object
FROM   json_tbl
     , json_array_elements(data) AS object
WHERE  object->>'name' = 'Toby';
Copy after login

Postgres 9.4:

  • Introduced the jsonb datatype, which stores JSON data in native Postgres types.
  • Indexes using GIN or other types can improve performance.

Postgres 9.5:

  • Complete jsonb functions and operators.
  • More functions for manipulating and displaying jsonb data.

Postgres 12:

  • SQL/JSON path language support
  • To find a record by name using JSON path:
SELECT jsonb_path_query_first(data, '$[*] ? (@.name == "Toby")') AS object
FROM   jsonb_tbl
WHERE  data @> '[{ "name": "Toby"}]';  -- optional for indexing
Copy after login
  • Or equivalent:

    ...
    WHERE  data @@ '$[*].name == "Toby"';
    Copy after login

Additional resources:

  • [Postgres 9.3 JSON Functionality](https://www.postgresql.org/docs/9.3/static/)
  • [Postgres JSONB Datatype](https://www.postgresql.org/docs/current/static/datatype-json.html)
  • [Postgres 12 JSON Path Support](https://www.postgresql.org/docs/12/static/functions-json.html)
  • [Github PostSQL Functions](https://github.com/daviddias/postsด้วย)

The above is the detailed content of How to Query JSON and JSONB Data in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template