Thank you, Singapore. See the photos from our Agentic Patterns workshop at GovTech STACK 2026.

Databases & BigQuery · Optimized Analytics Applications, part 4

Querying JSON data in Postgres

Filter rows on values inside a JSONB column with @>, ->> and ILIKE, and unpack nested arrays with jsonb_array_elements. Examples use real IDX company data.

SC
Samuel Chan
Head of Supertype Incubator4 min read

JSON operators in Postgres

Sectors runs on Postgres and keeps semi-structured data such as shareholder lists in jsonb columns, so we query it with SQL and skip a separate document store like MongoDB. These are the operators you'll use most:

OperatorWhat it doesExample
->Gets a key or array element as jsonbmajor_shareholders -> 0
->>Gets a key or array element as textmajor_shareholders -> 0 ->> 'name'
#>>Reads a path as textmajor_shareholders #>> '{0,name}'
@>Tests whether the left value contains the right onemajor_shareholders @> '[{"name": "Public"}]'
?Tests whether a key existsmajor_shareholders -> 0 ? 'name'
@?Runs a jsonpath query and tests for a matchmajor_shareholders @? '$[*].name ? (@ like_regex "persero" flag "i")'

Querying JSON columns in Postgres

Suppose we have a table called idx_company_report with a jsonb column called major_shareholders. Here's an example of what a row might look like:

{
  "symbol": "TLKM.JK",
  "company_name": "PT Telkom Indonesia (Persero) Tbk",
  "major_shareholders": [
    {
      "name": "Republic of Indonesia",
      "share_percentage": "0.5209"
    },
    {
      "name": "Public",
      "share_percentage": "0.4791"
    }
  ]
}

Every query in this note expects jsonb. On a plain json column, @>, ?, @? and jsonb_array_elements fail with errors like operator does not exist: json @> unknown. Convert the column once with ALTER TABLE idx_company_report ALTER COLUMN major_shareholders TYPE jsonb USING major_shareholders::jsonb.

To select rows from the idx_company_report table where the major_shareholders array contains an object with the value 'Republic of Indonesia', you can use the following SQL query:

SELECT
  symbol, company_name, major_shareholders
FROM
  idx_company_report
WHERE
  major_shareholders @> '[{"name": "Republic of Indonesia"}]';

This query uses the @> operator to check if the major_shareholders array contains an object with the specified name. You can adjust the query based on your specific requirements and the structure of your JSON data.

Matching part of a name with OR and @?

Sectors is the only place, as far as I know, where you can find a list of companies on the Indonesian Stock Exchange (IDX) with state ownership whether directly or indirectly, i.e. through another entity with state ownership. The state-owned companies in Indonesia are often referred to as '(persero)' which is short for "Badan Usaha Milik Negara yang berbentuk Perusahaan Perseroan". Based on BUMN and PERSERO on IDX by Sectors there are 44 such companies that are either directly or indirectly owned by the Republic of Indonesia.

To gather this list of companies, we will have to modify the query slightly so that, in addition to 'Republic of Indonesia' any shareholder whose name contains "persero", in any case and at any position, should also match.

Here is our new query:

SELECT
  symbol, company_name, major_shareholders
FROM
  idx_company_report
WHERE
  major_shareholders @> '[{"name": "Republic of Indonesia"}]'
  OR major_shareholders @? '$[*].name ? (@ like_regex "persero" flag "i")';

The first condition is the exact match from before. The second uses @? to run a jsonpath query: $[*].name reads the name of every shareholder in the array, and like_regex with flag "i" matches "persero" anywhere in that name, ignoring case. @> only compares whole values, so it can't match part of a string.

The result of this query converted to JSON would look something like this:

[
  ...
  {
    "symbol": "BBNI.JK",
    "company_name": "PT Bank Negara Indonesia (Persero) Tbk",
    "major_shareholders": [
      {
        "name": "Republic of Indonesia",
        "share_value": 105849774057500,
        "share_amount": 22378387750,
        "share_percentage": "0.6"
      },
      {
        "name": "Public",
        "share_value": 70419087578070,
        "share_amount": 14887756359,
        "share_percentage": "0.39917"
      },
      {
        "name": "Putrama Wahju Setyawan",
        "share_value": 18350157980,
        "share_amount": 3879526,
        "share_percentage": "0.0001"
      },
      {
        "name": "Royke Tumilaar",
        "share_value": 17297330930,
        "share_amount": 3656941,
        "share_percentage": "0.0001"
      },
     ...
    ]
  },
  {
    "symbol": "BBRI.JK",
    "company_name": "PT Bank Rakyat Indonesia (Persero) Tbk",
    "major_shareholders": [
      {
        "name": "Republic of Indonesia",
        "share_value": 336147773572920,
        "share_amount": 80610976876,
        "share_percentage": "0.53188"
      },
      {
        "name": "Public",
        "share_value": 291831312468900,
        "share_amount": 69983528170,
        "share_percentage": "0.46177"
      },
      {
        "name": "Treasury Stock",
        "share_value": 3794192511000,
        "share_amount": 909878300,
        "share_percentage": "0.006"
      },
      {
        "name": "Handayani",
        "share_value": 23943723000,
        "share_amount": 5741900,
        "share_percentage": "0.00004"
      },
    ...
    ]
  },
    ...
]

These two queries cover most of the JSON filtering you'll do in Postgres. You can combine @> and @? with conditions on regular columns, such as ILIKE on company_name, in the same WHERE clause.

Speeding up JSON filters with a GIN index

On a large table, @> and @? read every row unless the column has a GIN index:

CREATE INDEX ON idx_company_report USING gin (major_shareholders jsonb_path_ops);

The jsonb_path_ops operator class builds a smaller index than the default one and supports @>, @? and @@. It doesn't support the key-exists operator ?, so use the default jsonb_ops class if you filter on keys. With this index in place, Postgres answers both queries above with a bitmap index scan.

Incorporating JSONB_ARRAY_ELEMENTS in your JSON queries

In cases where the @> operator does not suffice for your needs, you can use the jsonb_array_elements function along with a WHERE clause to filter based on the condition. Here’s how you can do it:

SELECT
  symbol, company_name, major_shareholders
FROM
  idx_company_report
WHERE
  EXISTS (
    SELECT
      1
    FROM
      JSONB_ARRAY_ELEMENTS(major_shareholders) AS shareholder
    WHERE
      shareholder ->> 'name' = 'Republic of Indonesia'
      OR shareholder ->> 'name' ILIKE '%pemerintah ri%'
  )
OR company_name ILIKE '%persero%';

This query checks if there exists any element in the major_shareholders array (aliased as shareholder) that matches either condition of:

  1. The name field is equal to 'Republic of Indonesia'.
  2. The name field contains the string 'pemerintah ri' (case-insensitive), regardless of its position in the string. "ri" is short for "Republic Indonesia".

In cases where there is a match, the EXISTS clause returns TRUE, and the row is included in the result set. Here, we also use JSONB_ARRAY_ELEMENTS to expand the major_shareholders array into a set of JSON objects, which allows us to filter based on the name field. The ILIKE operator is used for case-insensitive pattern matching.

State-owned and persero companies on IDX returned by the Postgres query

Turning a JSON array into rows with JSON_TABLE

Postgres 17 added JSON_TABLE, which turns a JSON array into rows with typed columns. You can then filter, join and aggregate them like any other table:

SELECT
  r.symbol, s.name, s.share_percentage
FROM
  idx_company_report AS r,
  JSON_TABLE(
    r.major_shareholders, '$[*]'
    COLUMNS (
      name text PATH '$.name',
      share_percentage numeric PATH '$.share_percentage'
    )
  ) AS s
WHERE
  s.name <> 'Public'
ORDER BY
  s.share_percentage DESC;

Each shareholder becomes a row, with name as text and share_percentage as a number you can sort on. On Postgres 16 or older, jsonb_array_elements from the previous section gives you the same rows, and you cast each field yourself.

Conclusion

With just a simple query, you can combine the robustness and predictability of a relational database with the flexibility and expressiveness of JSON data.

In the case of shareholders, a JSON data type feels natural because the number of shareholders varies from company to company, and the shareholding structure can be rather complex and nested. When we opt for a JSON data type, we can store the data in a way that reflects its natural structure, making it easier to work with and query.

I hope this article has given you a good starting point for working with JSON data in Postgres. I write about database optimizations and engineering here on Supertype, so if you'd like to see more content, here are some other articles you might find interesting.

Further reading

Taggedpostgresjson
Share
The Enterprise AI Agentic Stack
From the Supertype shelf

Like this piece? Take home The Enterprise AI Agentic Stack.

The same thinking runs all the way through this 12-chapter guide, written by Samuel Chan and ready to read in an afternoon.

Building agents that build your business
Learn it live with our engineers

Building agents that build your business

A two-evening workshop on designing and shipping AI agents that do real work for your business: from the agentic patterns that keep them reliable, to a working multi-agent system that researches, drafts and reports on your behalf.

December 9, 2026Zoom Conferencing (Online)

Save your seatSeats from Rp490.000 (about $27)

Keep reading

Optimizing queries in Postgres and BigQuery
Databases & BigQuery
Optimized Analytics Applications · Part 1

Optimizing queries in Postgres and BigQuery

BigQuery has no EXPLAIN. Read its execution graph and dry runs, use EXPLAIN ANALYZE in Postgres, and see how much an index speeds up a lookup.

SC
Samuel Chan
14 min read

Databases & BigQuery

Databases & BigQuery

Introduction to NoSQL

A general introduction to NoSQL databases and their use cases.

VC
Vincentius C. Calvin
10 min read

Field notes, straight to your inbox

We publish what we learn building analytics and AI systems for some of the largest enterprises in the region. Subscribe and we will send the next one your way.

The latest in AI and Enterprise Analytics

We do not resell your data. We respect your privacy and trust.