Scrivio Interview library
CodingFoundations8 min read · updated 12 November 2026

Table events(id, payload jsonb). Write PostgreSQL queries to find events where payload->'user'->>'country' = 'DE', and to extract the items array into rows. What index supports the first query?

To filter, we write WHERE payload->'user'->>'country' = 'DE', or the containment form WHERE payload @> '{"user":{"country":"DE"}}'. A GIN index on payload serves the containment form and an expression B-tree index on (payload->'user'->>'country') serves the equality form. To turn the items array into rows, we CROSS JOIN LATERAL jsonb_array_elements(e.payload->'items').

Why this question is asked

Many Spring Boot services keep event payloads, webhook bodies or flexible attributes in a jsonb column, and sooner or later someone has to query them. Interviewers ask this question because it checks three things at once: whether we know the difference between the -> and ->> operators, whether we can turn nested JSON into ordinary rows, and whether we know that an index only helps when it matches the exact shape of the query. In this answer, we will recap how jsonb works, write both filter forms, pick the index that serves each one, unpack the items array into rows, and look at the SQL/JSON functions that PostgreSQL 17 added.

1A Quick Recap of jsonb and Its Operators

PostgreSQL has two JSON types. The json type stores the text exactly as we sent it, with its spaces, key order and even duplicate keys, and it parses that text again every time we query it. The jsonb type parses the document once, on insert, and stores a binary form. It drops insignificant whitespace, does not keep key order, and keeps only the last value when a key appears twice. So jsonb is slightly slower to write but much faster to query, and it is the only one of the two that supports GIN indexes. For almost every application column, jsonb is the right choice.

Two operators do most of the work. The -> operator takes a key and returns the value as jsonb, so we can keep walking down the document. The ->> operator takes a key and returns the value as text, which is what we need when we compare with a string such as 'DE'. Notice the difference in the result: payload->'user'->'country' is the jsonb value "DE" with its quotes, while payload->'user'->>'country' is the plain text DE.

Java
SELECT '{"user":{"country":"DE"}}'::jsonb -> 'user' -> 'country'; -- "DE" (jsonb)
SELECT '{"user":{"country":"DE"}}'::jsonb -> 'user' ->> 'country'; -- DE (text)
SELECT '{"a":1,"a":2}'::json; -- {"a":1,"a":2} json keeps the text as written
SELECT '{"a":1,"a":2}'::jsonb; -- {"a": 2} jsonb keeps the last key only

2Writing the Filter Two Ways

The question gives us the first form directly. We walk to the user object with ->, take country as text with ->>, and compare it with a string.

Java
-- Form 1: extract a value and compare it
SELECT id FROM events
WHERE payload->'user'->>'country' = 'DE';
-- Form 2: ask whether the document contains this smaller document
SELECT id FROM events
WHERE payload @> '{"user":{"country":"DE"}}';

The second form uses the containment operator @>. It reads as "does payload contain this JSON fragment?" and it is true when every key and value in the fragment also appears, at the same place, in the payload. Both queries return the same rows for this filter. The reason we care about having two forms is that each one can use a different kind of index, and the index we create decides which form becomes fast.

3Choosing the Index That Serves Each Form

A GIN index (Generalized Inverted Index) works like the index at the back of a book: for each key and value inside the documents, it lists the rows that contain it. That is exactly what @> needs. PostgreSQL offers two operator classes for it. The default, jsonb_ops, indexes every key and every value separately and also supports the key-exists operators ?, ?| and ?&. The jsonb_path_ops class stores one hash per path-and-value, so the index is usually smaller and faster for @>, but it cannot answer the key-exists operators.

An expression B-tree index stores the result of one expression for every row, sorted. If we index exactly payload->'user'->>'country', PostgreSQL can use it for the equality form, and also for range conditions and ORDER BY on that value. But there is a catch: the planner only uses it when the query repeats the same expression. A GIN index will not help form 1, and the B-tree index will not help form 2.

Java
-- Serves form 2 (payload @> ...), for any key, not just country
CREATE INDEX events_payload_gin ON events USING gin (payload jsonb_path_ops);
-- Serves form 1 (payload->'user'->>'country' = 'DE'), and only that expression
CREATE INDEX events_country_idx ON events ((payload->'user'->>'country'));
EXPLAIN SELECT id FROM events WHERE payload->'user'->>'country' = 'DE';
-- Index Scan using events_country_idx on events
Which index helps which filter
FilterGIN jsonb_opsGIN jsonb_path_opsB-tree on expression
payload @> '{...}'yesyes, smaller indexno
payload ? 'coupon'yesnono
payload->'user'->>'country' = 'DE'nonoyes
ORDER BY payload->'user'->>'country'nonoyes
An index helps only the query shape it was built for.

So which one should we pick? If country is a filter the application uses all the time, the expression index is small, precise and also gives the planner statistics on that expression after ANALYZE. If users can filter on many different keys, one GIN index covers all of them through @>. Note the double parentheses in the expression index: PostgreSQL requires them around any expression that is not a plain column.

4Turning the items Array Into Rows

Now the second part. Suppose each payload has an items array such as [{"sku":"A1","qty":2},{"sku":"B7","qty":1}]. The function jsonb_array_elements takes an array and returns one row per element. Because it needs the payload of each event, we call it with LATERAL, which lets a function or subquery in the FROM clause refer to columns of the tables listed before it.

Java
SELECT e.id, i.value
FROM events e
CROSS JOIN LATERAL jsonb_array_elements(e.payload->'items') AS i(value);
-- id | value
-- 1 | {"qty": 2, "sku": "A1"}
-- 1 | {"qty": 1, "sku": "B7"}
SELECT e.id, i.value->>'sku' AS sku, (i.value->>'qty')::int AS qty
FROM events e
LEFT JOIN LATERAL jsonb_array_elements(e.payload->'items') AS i(value) ON true;
-- 1 | A1 | 2
-- 1 | B7 | 1
-- 2 | NULL | NULL event 2 has no items, but LEFT JOIN keeps it

Notice what CROSS JOIN does with an event that has no items key: payload->'items' is NULL, the function returns no rows, and the event disappears from the result. That is fine when we only want items, but when we need every event, LEFT JOIN LATERAL ... ON true keeps it with NULL columns. One more trap: if some payload has items as an object or a string instead of an array, jsonb_array_elements raises an error, so for untrusted data we can guard it with jsonb_typeof(payload->'items') = 'array'.

5The SQL/JSON Way in PostgreSQL 17

PostgreSQL 17 added the SQL standard functions JSON_TABLE, JSON_EXISTS, JSON_QUERY and JSON_VALUE. JSON_TABLE does the unpacking and the typing in one step: we give it a path to the rows and a list of typed columns. On older versions these functions do not exist, so check your version before relying on them.

SQL
SELECT e.id, jt.sku, jt.qty
FROM events e,
JSON_TABLE(e.payload, '$.items[*]'
COLUMNS (sku text PATH '$.sku',
qty int PATH '$.qty')) AS jt;
-- 1 | A1 | 2
-- 1 | B7 | 1
SELECT id FROM events WHERE JSON_VALUE(payload, '$.user.country') = 'DE'; -- same rows as form 1

The result is the same as the LATERAL query, but the column types are declared once and the code is portable to other databases that follow the standard, such as MySQL's JSON_TABLE. The older operators remain fully supported, and most existing code still uses them.

6Follow-up questions

Why not just use json instead of jsonb?

Because json is stored as text and parsed again on every query, cannot have a GIN index and keeps duplicate keys, which makes comparisons surprising. json is only worth it when we must keep the exact original text, for example to verify a signature over a webhook body. Even then, many teams store the raw text for audit and a jsonb copy for querying.

Does the GIN index help a query that uses ->> with LIKE?

No. A GIN index on jsonb serves the containment, key-exists and jsonpath operators, not text comparisons on extracted values. For LIKE on an extracted value we would index that expression, and for substring search a trigram GIN index from pg_trgm on the expression would help.

How would we sum quantities per SKU across all events?

We unpack the array with LATERAL and group the result: SELECT i.value->>'sku' AS sku, SUM((i.value->>'qty')::int) FROM events e CROSS JOIN LATERAL jsonb_array_elements(e.payload->'items') AS i(value) GROUP BY 1. If this report runs often on a big table, it is a sign that items deserve their own table.

7Conclusion

In this answer, we saw that -> returns jsonb and ->> returns text, so the equality filter is payload->'user'->>'country' = 'DE', while the containment filter is payload @> '{"user":{"country":"DE"}}'. A GIN index, with jsonb_ops or the smaller jsonb_path_ops, serves containment, and an expression B-tree index serves the equality form only when the query repeats the same expression. jsonb_array_elements with LATERAL turns the items array into rows, LEFT JOIN keeps events without items, and PostgreSQL 17 adds JSON_TABLE for the same job in standard SQL.

What to say in the interviewAbout 90 seconds aloud

Open with

For the filter I would write payload arrow user, then double arrow country, equals DE. The single arrow returns jsonb so I can keep walking, and the double arrow returns text so I can compare with a string.

Then, if they want more

The other way is containment: payload contains the fragment user country DE. The index depends on which form we use. A GIN index on payload serves containment; jsonb_path_ops is smaller and faster for that, while the default jsonb_ops also supports the key-exists operators.

For the equality form I would create an expression B-tree index on exactly that expression, with the double parentheses, and the query has to repeat the expression for the planner to use it.

If country is a hot filter I prefer the expression index because it is small and gives the planner statistics; if users filter on arbitrary keys, one GIN index covers them all.

To get the items as rows, I would cross join lateral jsonb_array_elements of payload items, which gives one row per element, and then pick fields with double arrow and cast them. If I need events without items, I use a left join lateral on true.

On PostgreSQL 17 I can also use JSON_TABLE, which unpacks and types the columns in one step. And I would mention that jsonb stores a parsed binary form without duplicate keys or whitespace, while json keeps the original text.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 17
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Table events(id, payload jsonb). Write PostgreSQL queries to find events where...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/ece27bc9d6/