Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Table orders(id bigint, data jsonb). Write queries to (a) find orders whose data contains {"status": "PAID"}, (b) get the customer email at data -> 'customer' -> 'email' as text, and (c) create an index that makes (a) fast.

Containment does (a): WHERE data @> '{"status": "PAID"}'. For (b), data -> 'customer' ->> 'email' or data #>> '{customer,email}' return the email as text, because -> returns jsonb and ->> returns text. For (c), CREATE INDEX ON orders USING gin (data jsonb_path_ops) supports @> and is smaller than the default jsonb_ops; for a filter on one known key, an expression B-tree index on (data ->> 'status') is often even better.

Why this question is asked

jsonb columns appear in most modern PostgreSQL schemas, for event payloads, settings or data from other systems. Querying them looks easy until a query returns quoted strings instead of text, or a filter that was instant on a test database scans millions of rows in production. Interviewers ask this coding question to check that we know the operators, the difference between jsonb and text results, and how to index json data. In this answer, we will recap what jsonb is, write each query with its result, build the index and prove it is used, and compare it with an expression index.

1A Quick Recap of jsonb

PostgreSQL has two JSON types. json stores the text exactly as given and re-parses it on every access. jsonb parses the text once on insert and stores a binary form. That makes it a little slower to write but much faster to query, and it supports indexing. The binary form also normalises the document: duplicate keys are removed (the last one wins), key order is not kept, and insignificant whitespace disappears.

SQL
SELECT '{"b": 1, "a": 2, "a": 3}'::json; -- {"b": 1, "a": 2, "a": 3}
SELECT '{"b": 1, "a": 2, "a": 3}'::jsonb; -- {"a": 3, "b": 1}

For our examples, the orders table holds documents like this one.

2Setting Up Sample Data

We create the table and a few orders so every query has a visible result.

SQL
CREATE TABLE orders (id bigint PRIMARY KEY, data jsonb NOT NULL);
INSERT INTO orders VALUES
(1, '{"status": "PAID", "customer": {"email": "ana@example.com"}, "total": 59.9}'),
(2, '{"status": "NEW", "customer": {"email": "raj@example.com"}, "total": 12.0}'),
(3, '{"status": "PAID", "customer": {"email": "li@example.com"}, "tags": ["gift"]}');

3Query (a): Orders Whose Data Contains a Status

The containment operator @> asks whether the left document contains the right one: every key and value on the right must appear on the left, at the same place in the structure. Extra keys on the left do not matter.

SQL
SELECT id FROM orders WHERE data @> '{"status": "PAID"}';
-- 1
-- 3
SELECT id FROM orders WHERE data @> '{"customer": {"email": "raj@example.com"}}';
-- 2 (containment works on nested objects too)

Notice that we pass a JSON document, not a path. That shape is what lets a GIN index answer the query, as we will see in a moment. The alternative, WHERE data ->> 'status' = 'PAID', gives the same rows but needs a different index.

4Query (b): Extracting the Customer Email as Text

PostgreSQL has two families of field operators. -> returns the field as jsonb, which is right when we want to keep navigating. ->> returns it as text, which is what we need for comparisons, joins and display. For a path in one step, #> returns jsonb and #>> returns text.

Java
SELECT data -> 'customer' -> 'email' FROM orders WHERE id = 1; -- "ana@example.com" (jsonb, with quotes)
SELECT data -> 'customer' ->> 'email' FROM orders WHERE id = 1; -- ana@example.com (text)
SELECT data #>> '{customer,email}' FROM orders WHERE id = 1; -- ana@example.com (text)
SELECT data ->> 'missing' FROM orders WHERE id = 1; -- NULL

The first line is a common bug: the result is a jsonb string, so comparing it with a text value or writing it into a text column keeps the quotation marks. Using ->> on the last step fixes it. Missing keys simply return NULL rather than raising an error.

5Query (c): Indexing the Containment Query

Without an index, query (a) must read and check every document. A GIN index (generalized inverted index) works like the index at the back of a book: for each item it stores the list of rows that contain it. PostgreSQL offers two operator classes for jsonb. The default, jsonb_ops, indexes every key and every value separately and supports @>, the key-exists operators ?, ?| and ?&, and the jsonpath operators. jsonb_path_ops indexes a hash of each path-and-value pair, so it supports only containment and jsonpath matching, but the index is usually much smaller and faster for @>.

Java
CREATE INDEX orders_data_gin ON orders USING gin (data jsonb_path_ops);
EXPLAIN SELECT id FROM orders WHERE data @> '{"status": "PAID"}';
-- Bitmap Heap Scan on orders
-- Recheck Cond: (data @> '{"status": "PAID"}'::jsonb)
-- -> Bitmap Index Scan on orders_data_gin
-- (on three rows the planner may still choose a sequential scan; plans differ with real data)
Which index for which query
Queryjsonb_ops GINjsonb_path_ops GINB-tree on (data ->> 'status')
data @> '{"status": "PAID"}'yesyes, smaller indexno
data ? 'tags' (key exists)yesnono
data ->> 'status' = 'PAID'nonoyes
ORDER BY data ->> 'status'nonoyes

Notice the Recheck Cond line. Because jsonb_path_ops stores hashes, the index may return a few false matches, and PostgreSQL rechecks each candidate row. This is normal and cheap.

6When an Expression B-tree Index Is Better

If the application always filters on one known key, an index on just that value is smaller still and supports equality, ranges and sorting. The query must use exactly the same expression as the index.

Java
CREATE INDEX orders_status_idx ON orders ((data ->> 'status'));
SELECT id FROM orders WHERE data ->> 'status' = 'PAID'; -- uses orders_status_idx
SELECT id FROM orders WHERE data @> '{"status": "PAID"}'; -- does not: different expression

So the choice depends on how the data is queried. A GIN index on the whole document serves many different containment filters; an expression index serves one hot filter better. If status is filtered on constantly, it may deserve to be a real column, or a generated column, which also gives the planner proper statistics.

7Follow-up questions

When would jsonb_ops be needed instead of jsonb_path_ops?

When queries test whether a key exists, with ?, ?| or ?&, for example WHERE data ? 'tags' to find orders that have tags at all. jsonb_path_ops does not index keys on their own, so it cannot help these. jsonb_ops also helps when we search for a value regardless of its key. The price is a larger index that is slower to update, so we choose jsonb_path_ops when containment is all we need.

How would you query with SQL/JSON path?

With the jsonpath operators @? and @@, or functions such as jsonb_path_query. For example, SELECT id FROM orders WHERE data @@ '$.total > 50'; returns order 1, and data @? '$.tags[*] ? (@ == "gift")' finds order 3. Both GIN operator classes can support @? and @@ for simple equality conditions. PostgreSQL 17 added the SQL standard functions JSON_VALUE, JSON_QUERY and JSON_EXISTS, so JSON_VALUE(data, '$.customer.email') also returns the email as text.

Why does json keep duplicate keys and jsonb not?

json is stored as the original text, so nothing is changed. jsonb is parsed into a structure where each key appears once, keeping the last value, and keys are stored in their own sorted order. If the exact original text matters, for example for a signature, keep json or text.

8Conclusion

In this answer, we wrote the three queries. Containment with data @> '{"status": "PAID"}' finds the paid orders; data -> 'customer' ->> 'email' or data #>> '{customer,email}' return the email as text, because -> and #> return jsonb while ->> and #>> return text; and a GIN index with jsonb_path_ops makes containment fast with a smaller index than the default jsonb_ops. For a single hot key, an expression B-tree index on (data ->> 'status') is often better. We also saw that jsonb stores a parsed binary form without duplicate keys or key order.

What to say in the interviewAbout 80 seconds aloud

Open with

For part a, I would use the containment operator: SELECT * FROM orders WHERE data @> '{"status": "PAID"}'. It checks that the document contains that key and value, and it is the form a GIN index can serve.

Then, if they want more

For part b, the important detail is the operator: the single arrow returns jsonb and the double arrow returns text, so I would write data -> 'customer' ->> 'email', or with a path, data #>> '{customer,email}'. If I used the single arrow at the end, I would get a jsonb string with quotation marks.

For part c, I would create a GIN index with the jsonb_path_ops operator class: CREATE INDEX ON orders USING gin (data jsonb_path_ops). It supports containment and jsonpath matching, and it is smaller and faster than the default jsonb_ops, which I would only need for key-exists queries with the question mark operators.

If the application really only ever filters on status, an expression B-tree index on (data ->> 'status') is often better, because it is small and supports equality and sorting, as long as the query uses the same expression.

I would also mention that jsonb stores a parsed binary form, so it removes duplicate keys and does not keep key order, unlike the json type.

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.
Official documentation
PostgreSQL documentation
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 orders(id bigint, data jsonb). Write queries to (a) find orders whose data...": https://scrivio-interview-library.netlify.app/databases/postgresql/f313e15fa0/