JSON in SQL

Updated · 12 min read
mediumPostgreSQL 18sqljsonjsonbjson-tablegin-indexinterview

JSON in SQL means storing JSON documents in a table column and querying inside them with SQL. It is used for data whose shape varies from row to row, such as payment receipts: a card receipt has a card brand and last four digits, a check receipt has a check number, and either can list several items. Forcing every possible field into its own column would leave most of them empty. In this lesson, we will store receipts as jsonb, read values out of them, turn JSON arrays into rows with JSON_TABLE, filter and index JSON, and learn when a plain column is the better choice.

In One Minute

  • jsonb stores JSON in a parsed binary form: faster to query and indexable. Prefer it to json.
  • -> returns JSON; ->> returns text: body ->> 'method' gives card.
  • JSON_VALUE(body, '$.card.brand') is the SQL-standard way to read one value.
  • JSON_TABLE turns a JSON array into rows and columns you can join and total.
  • @> asks "does this document contain...?", and a GIN index makes it fast.

The Receipts Table

Every example uses this table: one JSON receipt for five of the Fee Tracker's payments.

SQL
CREATE TABLE receipts (
  receipt_id INTEGER PRIMARY KEY,
  payment_id INTEGER NOT NULL REFERENCES payments (payment_id),
  body       JSONB NOT NULL
);
 
INSERT INTO receipts VALUES
  (1, 1, '{"method": "card", "card": {"brand": "Visa", "last4": "4242"},
           "lines": [{"item": "Java Basics", "usd": 450.00}], "total_usd": 450.00}'),
  (2, 2, '{"method": "card", "card": {"brand": "Mastercard", "last4": "5454"},
           "lines": [{"item": "Java OOP, installment 1", "usd": 250.00}], "total_usd": 250.00}'),
  (3, 3, '{"method": "check", "check_no": "1043",
           "lines": [{"item": "Java OOP, installment 2", "usd": 250.00}], "total_usd": 250.00}'),
  (4, 6, '{"method": "card", "card": {"brand": "Visa", "last4": "1881"},
           "lines": [{"item": "JavaScript Basics, installment 1", "usd": 200.00},
                     {"item": "Workbook", "usd": 25.00}], "total_usd": 225.00}'),
  (5, 7, '{"method": "check", "check_no": "2210",
           "lines": [{"item": "JavaScript Basics, installment 2", "usd": 225.00}], "total_usd": 225.00}');
Receipt 4: keys, a nested card object and a lines array, with the path to each value

Two JSON Types

PostgreSQL has two JSON types. json keeps the exact text you stored; jsonb parses it into a binary form:

SQL▶ Try it
SELECT '{"b": 1, "a": 2, "a": 3}'::json  AS as_json,
       '{"b": 1, "a": 2, "a": 3}'::jsonb AS as_jsonb;
Output
         as_json          |     as_jsonb
--------------------------+------------------
 {"b": 1, "a": 2, "a": 3} | {"a": 3, "b": 1}
(1 row)

Explanation: json keeps the text as typed, duplicate key and all. jsonb rewrites the spacing in a standard form, keeps only the last value of a duplicate key, and stores keys in its own order. It costs a little more to write, but it's much faster to query and it supports indexes, so jsonb is the usual choice.

jsonjsonb
StoresThe exact textA parsed binary form
Duplicate keysKeptLast one wins
QueryingRe-parses every timeFast
GIN indexes, @>NoYes

Reading Values

-> returns a JSON value; ->> returns it as text. Chain them to walk into nested objects:

SQL▶ Try it
CREATE TABLE receipts (receipt_id INTEGER PRIMARY KEY, payment_id INTEGER NOT NULL REFERENCES payments (payment_id), body JSONB NOT NULL);
INSERT INTO receipts VALUES
  (1, 1, '{"method": "card", "card": {"brand": "Visa", "last4": "4242"}, "lines": [{"item": "Java Basics", "usd": 450.00}], "total_usd": 450.00}'),
  (2, 2, '{"method": "card", "card": {"brand": "Mastercard", "last4": "5454"}, "lines": [{"item": "Java OOP, installment 1", "usd": 250.00}], "total_usd": 250.00}'),
  (3, 3, '{"method": "check", "check_no": "1043", "lines": [{"item": "Java OOP, installment 2", "usd": 250.00}], "total_usd": 250.00}'),
  (4, 6, '{"method": "card", "card": {"brand": "Visa", "last4": "1881"}, "lines": [{"item": "JavaScript Basics, installment 1", "usd": 200.00}, {"item": "Workbook", "usd": 25.00}], "total_usd": 225.00}'),
  (5, 7, '{"method": "check", "check_no": "2210", "lines": [{"item": "JavaScript Basics, installment 2", "usd": 225.00}], "total_usd": 225.00}');
 
SELECT receipt_id,
       body ->> 'method'            AS method,
       body -> 'card' ->> 'brand'   AS card_brand,
       body #>> '{card, last4}'     AS last4,
       JSON_VALUE(body, '$.check_no') AS check_no,
       (body ->> 'total_usd')::NUMERIC AS total_usd
FROM receipts
ORDER BY receipt_id;
Output
CREATE TABLE
 
INSERT 0 5
 
 receipt_id | method | card_brand | last4 | check_no | total_usd
------------+--------+------------+-------+----------+-----------
          1 | card   | Visa       | 4242  | NULL     |    450.00
          2 | card   | Mastercard | 5454  | NULL     |    250.00
          3 | check  | NULL       | NULL  | 1043     |    250.00
          4 | card   | Visa       | 1881  | NULL     |    225.00
          5 | check  | NULL       | NULL  | 2210     |    225.00
(5 rows)

Explanation: body -> 'card' returns the nested card object, and ->> 'brand' reads text from it. #>> follows a path in one step. JSON_VALUE is the SQL-standard function (PostgreSQL 17+), using a JSON path where $ means the whole document. A key that's missing gives NULL, not an error, so card receipts have no check number. ->> always returns text, so cast it (::NUMERIC) before doing math.

Filtering on JSON

@> tests whether a document contains another, and ? whether a key exists:

SQL▶ Try it
CREATE TABLE receipts (receipt_id INTEGER PRIMARY KEY, payment_id INTEGER NOT NULL REFERENCES payments (payment_id), body JSONB NOT NULL);
INSERT INTO receipts VALUES
  (1, 1, '{"method": "card", "card": {"brand": "Visa", "last4": "4242"}, "lines": [{"item": "Java Basics", "usd": 450.00}], "total_usd": 450.00}'),
  (2, 2, '{"method": "card", "card": {"brand": "Mastercard", "last4": "5454"}, "lines": [{"item": "Java OOP, installment 1", "usd": 250.00}], "total_usd": 250.00}'),
  (3, 3, '{"method": "check", "check_no": "1043", "lines": [{"item": "Java OOP, installment 2", "usd": 250.00}], "total_usd": 250.00}'),
  (4, 6, '{"method": "card", "card": {"brand": "Visa", "last4": "1881"}, "lines": [{"item": "JavaScript Basics, installment 1", "usd": 200.00}, {"item": "Workbook", "usd": 25.00}], "total_usd": 225.00}'),
  (5, 7, '{"method": "check", "check_no": "2210", "lines": [{"item": "JavaScript Basics, installment 2", "usd": 225.00}], "total_usd": 225.00}');
 
SELECT receipt_id FROM receipts
WHERE body @> '{"card": {"brand": "Visa"}}'
ORDER BY receipt_id;
 
SELECT receipt_id FROM receipts
WHERE body ? 'check_no'
ORDER BY receipt_id;
Output
CREATE TABLE
 
INSERT 0 5
 
 receipt_id
------------
          1
          4
(2 rows)
 
 receipt_id
------------
          3
          5
(2 rows)

Explanation: body @> '{"card": {"brand": "Visa"}}' keeps receipts whose JSON includes that nested pair, whatever else they hold: receipts 1 and 4. body ? 'check_no' keeps receipts that have a check_no key at the top level.

Arrays to Rows with JSON_TABLE

JSON_TABLE turns JSON into a table: one row per array element, with the columns you describe:

SQL▶ Try it
CREATE TABLE receipts (receipt_id INTEGER PRIMARY KEY, payment_id INTEGER NOT NULL REFERENCES payments (payment_id), body JSONB NOT NULL);
INSERT INTO receipts VALUES
  (1, 1, '{"method": "card", "card": {"brand": "Visa", "last4": "4242"}, "lines": [{"item": "Java Basics", "usd": 450.00}], "total_usd": 450.00}'),
  (2, 2, '{"method": "card", "card": {"brand": "Mastercard", "last4": "5454"}, "lines": [{"item": "Java OOP, installment 1", "usd": 250.00}], "total_usd": 250.00}'),
  (3, 3, '{"method": "check", "check_no": "1043", "lines": [{"item": "Java OOP, installment 2", "usd": 250.00}], "total_usd": 250.00}'),
  (4, 6, '{"method": "card", "card": {"brand": "Visa", "last4": "1881"}, "lines": [{"item": "JavaScript Basics, installment 1", "usd": 200.00}, {"item": "Workbook", "usd": 25.00}], "total_usd": 225.00}'),
  (5, 7, '{"method": "check", "check_no": "2210", "lines": [{"item": "JavaScript Basics, installment 2", "usd": 225.00}], "total_usd": 225.00}');
 
SELECT r.receipt_id, line.item, line.usd
FROM receipts AS r,
     JSON_TABLE(r.body, '$.lines[*]'
       COLUMNS (item TEXT    PATH '$.item',
                usd  NUMERIC PATH '$.usd')) AS line
WHERE r.receipt_id IN (3, 4)
ORDER BY r.receipt_id, line.item;
Output
CREATE TABLE
 
INSERT 0 5
 
 receipt_id |               item               |  usd
------------+----------------------------------+--------
          3 | Java OOP, installment 2          | 250.00
          4 | JavaScript Basics, installment 1 | 200.00
          4 | Workbook                         |  25.00
(3 rows)

Explanation: '$.lines[*]' means "each element of the lines array". Receipt 4's two lines become two rows; receipt 3's one line becomes one row. Each COLUMNS entry reads a path inside the element. The result is an ordinary table, so it can be grouped, joined and totaled. Before PostgreSQL 17, jsonb_array_elements(r.body -> 'lines') did the same job.

Receipt 4's lines array becomes two rows with item and usd columns

Indexing JSON

A GIN index on a jsonb column speeds up @> and ? searches. With only five receipts the planner prefers a scan, so this example turns scans off just to show the index being used:

SQL▶ Try it
CREATE TABLE receipts (receipt_id INTEGER PRIMARY KEY, payment_id INTEGER NOT NULL REFERENCES payments (payment_id), body JSONB NOT NULL);
INSERT INTO receipts VALUES
  (1, 1, '{"method": "card", "card": {"brand": "Visa", "last4": "4242"}, "lines": [{"item": "Java Basics", "usd": 450.00}], "total_usd": 450.00}'),
  (3, 3, '{"method": "check", "check_no": "1043", "lines": [{"item": "Java OOP, installment 2", "usd": 250.00}], "total_usd": 250.00}');
 
CREATE INDEX receipts_body_idx ON receipts USING GIN (body);
 
SET enable_seqscan = off;
 
EXPLAIN (COSTS OFF)
SELECT receipt_id FROM receipts WHERE body @> '{"method": "check"}';
Output
CREATE TABLE
 
INSERT 0 2
 
CREATE INDEX
 
SET
 
                         QUERY PLAN
------------------------------------------------------------
 Bitmap Heap Scan on receipts
   Recheck Cond: (body @> '{"method": "check"}'::jsonb)
   ->  Bitmap Index Scan on receipts_body_idx
         Index Cond: (body @> '{"method": "check"}'::jsonb)
(4 rows)

Explanation: The Bitmap Index Scan on receipts_body_idx shows the GIN index answering the containment test. A GIN index lists every key and value inside every document, so it can find documents containing any pair. For a single field you filter on often, an ordinary B-tree index on the expression, such as ((body ->> 'method')), is smaller. enable_seqscan = off is only for demonstrations; don't use it in real code.

Building JSON from Rows

SQL can also produce JSON, which is handy for APIs. jsonb_build_object makes an object and jsonb_agg collects rows into an array:

SQL▶ Try it
SELECT s.first_name,
       jsonb_agg(jsonb_build_object('course_id', p.course_id, 'usd', p.amount_usd)
                 ORDER BY p.payment_id) AS payments
FROM students AS s
JOIN payments AS p ON p.student_id = s.student_id
WHERE s.student_id = 103
GROUP BY s.first_name;
Output
 first_name |                              payments
------------+--------------------------------------------------------------------
 Navika     | [{"usd": 225.00, "course_id": 5}, {"usd": 225.00, "course_id": 5}]
(1 row)

Explanation: jsonb_build_object pairs keys with values for each payment, and jsonb_agg gathers Navika's two payments into one JSON array, in payment_id order. A program can send this straight to a web page. Notice that jsonb printed usd before course_id: it keeps keys in its own order, not yours.

When JSON Is the Wrong Choice

Use JSON forUse columns for
Fields that vary from row to row (receipt details, settings)Fields every row has (amount, date, student)
Data you store and return whole, such as an API payloadData you filter, join and total all the time
Rarely queried extrasAnything that needs foreign keys, NOT NULL or CHECK

JSON skips the protections of a schema. Nothing stops a receipt from spelling "total_usd" as "total", or storing it as text. Keep the facts you rely on in real columns (here, payments.amount_usd), and use JSON for the extras.

JSON in Other Databases

DatabaseTypeRead a valueArrays to rows
PostgreSQLjsonb (and json)->>, JSON_VALUE (17+)JSON_TABLE (17+), jsonb_array_elements
MySQL 8JSON->>, JSON_EXTRACT, JSON_VALUE (8.0.21+)JSON_TABLE
SQL ServerNVARCHAR text (a native json type in SQL Server 2025)JSON_VALUEOPENJSON
OracleJSON (21c+)JSON_VALUE, dot notationJSON_TABLE

Tabs showing each database's version are coming to this course.

Common Mistakes

Doing math on ->> without a cast. It returns text; '450.00' + 1 fails. Cast first.

Using -> where you meant ->>. body -> 'method' = 'card' compares JSON with text and fails; use ->>.

Choosing json over jsonb by default. jsonb is faster to query and indexable.

Putting core facts only inside JSON. You lose types, constraints and simple queries.

Interview Corner

What's the difference between json and jsonb in PostgreSQL?

json stores the exact input text and re-parses it on each use. jsonb stores a parsed binary form: duplicate keys are dropped and key order isn't kept, but it's faster to query and supports GIN indexes and operators like @>.

What's the difference between -> and ->>?

-> returns the value as JSON, so you can keep navigating. ->> returns it as text, for comparing or casting.

When should you store JSON in a relational database?

For data whose shape varies or that's stored and returned whole. Data you filter, join, constrain or total regularly belongs in typed columns.

Practice

Challenge (module checkpoint): Using the receipts, report the total collected by payment method, read from the JSON, largest first.

Show solution
SQL▶ Try it
CREATE TABLE receipts (receipt_id INTEGER PRIMARY KEY, payment_id INTEGER NOT NULL REFERENCES payments (payment_id), body JSONB NOT NULL);
INSERT INTO receipts VALUES
  (1, 1, '{"method": "card", "card": {"brand": "Visa", "last4": "4242"}, "lines": [{"item": "Java Basics", "usd": 450.00}], "total_usd": 450.00}'),
  (2, 2, '{"method": "card", "card": {"brand": "Mastercard", "last4": "5454"}, "lines": [{"item": "Java OOP, installment 1", "usd": 250.00}], "total_usd": 250.00}'),
  (3, 3, '{"method": "check", "check_no": "1043", "lines": [{"item": "Java OOP, installment 2", "usd": 250.00}], "total_usd": 250.00}'),
  (4, 6, '{"method": "card", "card": {"brand": "Visa", "last4": "1881"}, "lines": [{"item": "JavaScript Basics, installment 1", "usd": 200.00}, {"item": "Workbook", "usd": 25.00}], "total_usd": 225.00}'),
  (5, 7, '{"method": "check", "check_no": "2210", "lines": [{"item": "JavaScript Basics, installment 2", "usd": 225.00}], "total_usd": 225.00}');
 
SELECT body ->> 'method' AS method,
       count(*) AS receipts,
       sum((body ->> 'total_usd')::NUMERIC) AS total_usd
FROM receipts
GROUP BY body ->> 'method'
ORDER BY total_usd DESC;
Output
CREATE TABLE
 
INSERT 0 5
 
 method | receipts | total_usd
--------+----------+-----------
 card   |        3 |    925.00
 check  |        2 |    475.00
(2 rows)

Three card receipts total 925.00 and two check receipts 475.00. The ->> reads the method as text for grouping, and the cast turns each total into a number before sum adds them.

Card receipts total 925.00 and check receipts 475.00, read from the JSON documents

Quick check: JSON in SQL

3 questions
1Which returns the method as text?
2What does body @> '{"method": "check"}' test?
3What does JSON_TABLE do?

Key Takeaways

You want toWrite
Read textbody ->> 'method'
Read nested textbody -> 'card' ->> 'brand' or body #>> '{card, brand}'
Filter by contentWHERE body @> '{"method": "card"}'
Array to rowsJSON_TABLE(body, '$.lines[*]' COLUMNS (...))
Index documentsCREATE INDEX ... USING GIN (body)

Was this tutorial helpful?

Lesson 88 of 115