JSON in SQL: Storing, Querying and Building JSON
How to work with JSON in SQL databases: json versus jsonb, extracting values with -> and ->>, containment and existence tests, turning arrays into rows, JSON_TABLE and the SQL/JSON path functions, building JSON from rows, updating documents, indexing, and when JSON is the wrong choice.
kvi5hnuCode Sprout team member11 min readOn this page
Relational tables have a fixed set of columns. Some data doesn't fit that shape well: product specifications that differ for tents, torches and backpacks, settings that change with every release, payloads received from other systems. Every major database can now store JSON in a column, query inside it, and produce JSON from ordinary rows.
This article uses PostgreSQL, which has the richest JSON support, and gives the equivalents for MySQL, SQL Server, Oracle and SQLite. The examples store product specifications in a jsonb column next to the shop's products table:
CREATE TABLE product_specs (product_id INTEGER PRIMARY KEY, specs JSONB NOT NULL);
-- 1 {"season": 3, "waterproof": true, "colours": ["green", "orange"],
-- "packed": {"length_cm": 45, "diameter_cm": 15}}
-- 2 {"season": 4, "waterproof": true, "colours": ["green"], "packed": {...}}
-- 3 {"lumens": 350, "battery": "AAA", "waterproof": false, "colours": ["black", "red"]}
-- 5 {"litres": 30, "colours": ["blue", "grey", "black"], "rain_cover": true}
json and jsonb
-- json keeps the text exactly; jsonb parses it into a binary form
SELECT '{"b": 1, "a": 2, "a": 3}'::json AS as_json,
'{"b": 1, "a": 2, "a": 3}'::jsonb AS as_jsonb;
-- JSON values have types of their own
SELECT v, jsonb_typeof(v) AS json_type
FROM (VALUES ('"text"'::jsonb), ('42'), ('3.5'), ('true'), ('null'),
('[1, 2]'), ('{"k": "v"}')) AS t(v);
-- Invalid JSON is rejected; test text first with pg_input_is_valid (PostgreSQL 16+)
SELECT pg_input_is_valid('{"season": 3}', 'jsonb') AS valid,
pg_input_is_valid('{season: 3}', 'jsonb') AS keys_need_quotes,
pg_input_is_valid('{"a": 1,}', 'jsonb') AS no_trailing_comma;
as_json | as_jsonb
--------------------------+------------------
{"b": 1, "a": 2, "a": 3} | {"a": 3, "b": 1}
(1 row)
v | json_type
------------+-----------
"text" | string
42 | number
3.5 | number
true | boolean
null | null
[1, 2] | array
{"k": "v"} | object
(7 rows)
valid | keys_need_quotes | no_trailing_comma
-------+------------------+-------------------
t | f | f
(1 row)
PostgreSQL has two JSON types:
jsonstores the text exactly as given, including spacing, key order and duplicate keys, and parses it again every time it's queried.jsonbparses the text once and stores a binary form. Duplicate keys are removed, keeping the last value, keys are reordered, and whitespace is dropped. It's faster to query and supports indexes and containment operators.
Use jsonb unless you must preserve the exact original text.
JSON has its own small type system: string, number, boolean, null, array and object. jsonb_typeof reports which one a value is. JSON's null is a value inside the document, which is different from SQL's NULL, meaning the whole column has no value.
Both types reject invalid JSON: keys must be in double quotes, strings use double quotes, and trailing commas aren't allowed. pg_input_is_valid (PostgreSQL 16+) tests text without raising an error, which is useful when loading data from outside.
In other databases: MySQL has a JSON type, stored in a binary form like jsonb, which also keeps the last duplicate key. SQL Server 2025 added a native json type, and earlier versions store JSON in nvarchar(max) with an ISJSON check. Oracle 21c added a JSON type. SQLite stores JSON as text, or since 3.45 as binary jsonb blobs, and its json_valid checks the text.
Getting values out
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
CREATE TABLE product_specs (
product_id INTEGER PRIMARY KEY,
specs JSONB NOT NULL
);
INSERT INTO product_specs VALUES
(1, '{"season": 3, "waterproof": true, "colours": ["green", "orange"],
"packed": {"length_cm": 45, "diameter_cm": 15}}'),
(2, '{"season": 4, "waterproof": true, "colours": ["green"],
"packed": {"length_cm": 60, "diameter_cm": 22}}'),
(3, '{"lumens": 350, "battery": "AAA", "waterproof": false, "colours": ["black", "red"]}'),
(5, '{"litres": 30, "colours": ["blue", "grey", "black"], "rain_cover": true}');
\pset null '(null)'
-- -> returns JSON, ->> returns text; #>> follows a path
SELECT product_id,
specs -> 'season' AS season_json,
specs ->> 'season' AS season_text,
specs -> 'colours' ->> 0 AS first_colour,
specs #>> '{packed,length_cm}' AS packed_length,
jsonb_array_length(specs -> 'colours') AS colour_count
FROM product_specs
ORDER BY product_id;
-- Filtering: cast extracted text before comparing numbers
SELECT p.name, (s.specs ->> 'season')::int AS season
FROM products p
JOIN product_specs s ON s.product_id = p.product_id
WHERE (s.specs ->> 'season')::int >= 3
ORDER BY p.name;
-- Containment @> and key existence ?
SELECT p.name,
s.specs @> '{"waterproof": true}' AS waterproof,
s.specs @> '{"colours": ["black"]}' AS comes_in_black,
s.specs ? 'rain_cover' AS has_rain_cover_key
FROM products p
JOIN product_specs s ON s.product_id = p.product_id
ORDER BY p.product_id;
product_id | season_json | season_text | first_colour | packed_length | colour_count
------------+-------------+-------------+--------------+---------------+--------------
1 | 3 | 3 | green | 45 | 2
2 | 4 | 4 | green | 60 | 1
3 | (null) | (null) | black | (null) | 2
5 | (null) | (null) | blue | (null) | 3
(4 rows)
name | season
---------------+--------
Ridge 2 tent | 3
Summit 4 tent | 4
(2 rows)
name | waterproof | comes_in_black | has_rain_cover_key
-------------------+------------+----------------+--------------------
Ridge 2 tent | t | f | f
Summit 4 tent | t | f | f
Glow head torch | f | t | f
Trail 30 backpack | f | t | t
(4 rows)
The extraction operators:
| Operator | Returns | Example |
|---|---|---|
-> key or index | JSON | specs -> 'colours' is ["green", "orange"] |
->> key or index | text | specs ->> 'season' is '3' |
#> path | JSON | specs #> '{packed,length_cm}' |
#>> path | text | specs #>> '{packed,length_cm}' is '45' |
They chain: specs -> 'colours' ->> 0 takes the array and then its first element as text. Array indexes start at 0. A missing key gives NULL, as the torch and the backpack show for season. ->> also returns SQL NULL for a JSON null value; use the ? operator or jsonb_typeof to tell the two apart.
The difference between -> and ->> matters when comparing: ->> returns text, so to compare numbers, cast the result: (specs ->> 'season')::int >= 3. Comparing the text '10' >= '3' would be false, because text compares character by character.
Two operators test whole structures without extracting anything:
@>(contains):specs @> '{"waterproof": true}'is true when the document contains that key with that value. For arrays,'{"colours": ["black"]}'checks thatcoloursincludes"black", wherever it appears in the array.?(key exists):specs ? 'rain_cover'is true when the key is present at the top level.?|and?&test for any or all of a list of keys.
Containment tests are also the ones a GIN index speeds up (see below).
Equivalents: MySQL has col->'$.season' (JSON) and col->>'$.colours[0]' (text), using JSON path strings, and JSON_EXTRACT and JSON_CONTAINS. SQLite 3.38+ has -> and ->> with paths like '$.colours[0]', and json_extract. SQL Server and Oracle use the standard JSON_VALUE(col, '$.season') for scalars and JSON_QUERY(col, '$.colours') for objects and arrays.
From JSON to rows

To join, group or count the contents of a document, turn it into rows, often called shredding:
CREATE TABLE product_specs (
product_id INTEGER PRIMARY KEY,
specs JSONB NOT NULL
);
INSERT INTO product_specs VALUES
(1, '{"season": 3, "waterproof": true, "colours": ["green", "orange"],
"packed": {"length_cm": 45, "diameter_cm": 15}}'),
(2, '{"season": 4, "waterproof": true, "colours": ["green"],
"packed": {"length_cm": 60, "diameter_cm": 22}}'),
(3, '{"lumens": 350, "battery": "AAA", "waterproof": false, "colours": ["black", "red"]}'),
(5, '{"litres": 30, "colours": ["blue", "grey", "black"], "rain_cover": true}');
-- One row per array element
SELECT s.product_id, c.colour
FROM product_specs s,
jsonb_array_elements_text(s.specs -> 'colours') AS c(colour)
ORDER BY c.colour, s.product_id;
-- One row per key
SELECT key, value, jsonb_typeof(value) AS type
FROM product_specs, jsonb_each(specs)
WHERE product_id = 3
ORDER BY key;
-- JSON_TABLE (PostgreSQL 17): turn JSON into typed columns, with nested arrays as rows
SELECT s.product_id, jt.*
FROM product_specs s,
JSON_TABLE(s.specs, '$'
COLUMNS (season int PATH '$.season',
waterproof boolean PATH '$.waterproof' DEFAULT false ON EMPTY,
NESTED PATH '$.colours[*]' COLUMNS (colour text PATH '$'))) AS jt
WHERE s.product_id IN (1, 2)
ORDER BY s.product_id, jt.colour;
product_id | colour
------------+--------
3 | black
5 | black
5 | blue
1 | green
2 | green
5 | grey
1 | orange
3 | red
(8 rows)
key | value | type
------------+------------------+---------
battery | "AAA" | string
colours | ["black", "red"] | array
lumens | 350 | number
waterproof | false | boolean
(4 rows)
product_id | season | waterproof | colour
------------+--------+------------+--------
1 | 3 | t | green
1 | 3 | t | orange
2 | 4 | t | green
(3 rows)
jsonb_array_elements_textreturns one row per array element, as text (jsonb_array_elementskeeps them as JSON). Used in theFROMclause after the table, it's a lateral join (article 23): it runs for each product and repeats the product's columns. The colours can now be counted, filtered and grouped like any column.jsonb_eachreturns one row per key, with the value as JSON.jsonb_object_keysreturns just the keys.JSON_TABLE(SQL standard, PostgreSQL 17) is the most complete tool. It describes the columns to produce, each with a type and a path, andNESTED PATHturns an inner array into extra rows. Values are converted to the column types, andDEFAULT ... ON EMPTYsupplies a value when the path finds nothing.
JSON_TABLE is also available in MySQL 8 and Oracle, with the same overall shape. SQL Server uses OPENJSON for the same job, and SQLite has the json_each and json_tree table-valued functions.
SQL/JSON path
The strings like '$.packed.length_cm' are SQL/JSON path expressions, standardised in SQL. $ is the whole document, .key steps into an object, [0] and [*] select array elements, and ? (...) filters, with @ meaning the current item.
CREATE TABLE product_specs (
product_id INTEGER PRIMARY KEY,
specs JSONB NOT NULL
);
INSERT INTO product_specs VALUES
(1, '{"season": 3, "waterproof": true, "colours": ["green", "orange"],
"packed": {"length_cm": 45, "diameter_cm": 15}}'),
(2, '{"season": 4, "waterproof": true, "colours": ["green"],
"packed": {"length_cm": 60, "diameter_cm": 22}}'),
(3, '{"lumens": 350, "battery": "AAA", "waterproof": false, "colours": ["black", "red"]}'),
(5, '{"litres": 30, "colours": ["blue", "grey", "black"], "rain_cover": true}');
\pset null '(null)'
-- SQL/JSON path functions (PostgreSQL 17): JSON_VALUE, JSON_QUERY, JSON_EXISTS
SELECT product_id,
JSON_VALUE(specs, '$.packed.length_cm' RETURNING int) AS length_cm,
JSON_QUERY(specs, '$.colours') AS colours,
JSON_EXISTS(specs, '$.colours[*] ? (@ == "black")') AS has_black,
JSON_VALUE(specs, '$.lumens' RETURNING int DEFAULT 0 ON EMPTY) AS lumens
FROM product_specs
ORDER BY product_id;
-- A path with a filter, and the @? operator that can use a GIN index
SELECT product_id
FROM product_specs
WHERE specs @? '$ ? (@.season >= 4 || @.litres > 20)'
ORDER BY product_id;
product_id | length_cm | colours | has_black | lumens
------------+-----------+---------------------------+-----------+--------
1 | 45 | ["green", "orange"] | f | 0
2 | 60 | ["green"] | f | 0
3 | (null) | ["black", "red"] | t | 350
5 | (null) | ["blue", "grey", "black"] | t | 0
(4 rows)
product_id
------------
2
5
(2 rows)
The standard functions, all in PostgreSQL 17:
JSON_VALUE(doc, path RETURNING type)extracts a single scalar and converts it to the given type.DEFAULT ... ON EMPTYreplaces a missing value, andON ERRORcontrols what happens when the value can't be converted.JSON_QUERY(doc, path)extracts an object or array, as JSON.JSON_EXISTS(doc, path)tests whether the path finds anything: here, whether any colour equals"black".
The @? operator tests whether a path returns any item, and @@ evaluates a path predicate. The last query finds four-season tents or packs larger than 20 litres in one path with || meaning "or" inside the filter. Both can use a GIN index. jsonb_path_query returns every item a path finds, as rows.
These functions are standard, but support varies. Oracle has all three. SQL Server has JSON_VALUE and JSON_QUERY, and JSON_PATH_EXISTS (2022+) in place of JSON_EXISTS, without path filters. MySQL has JSON_VALUE (8.0.21+) and uses JSON_EXTRACT and JSON_CONTAINS_PATH for the other two.
Building JSON from rows
Applications and APIs often want JSON, with an order and its items in one document. The database can build it:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Build JSON from rows: one document per order, with its items as an array
\pset format unaligned
\pset tuples_only on
SELECT jsonb_pretty(
jsonb_build_object(
'order_id', o.order_id,
'customer', c.name,
'placed_on', o.placed_on,
'items', jsonb_agg(jsonb_build_object('product', p.name, 'qty', oi.qty,
'unit_price', oi.unit_price)
ORDER BY p.name),
'total', SUM(oi.qty * oi.unit_price))) AS order_document
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE o.order_id = 103
GROUP BY o.order_id, c.name, o.placed_on;
\pset format aligned
\pset tuples_only off
-- The standard constructors (PostgreSQL 16+), and NULL handling
SELECT JSON_OBJECT('id': product_id, 'brand': brand) AS with_null,
JSON_OBJECT('id': product_id, 'brand': brand ABSENT ON NULL) AS absent_on_null
FROM products
WHERE product_id IN (3, 4)
ORDER BY product_id;
SELECT JSON_ARRAYAGG(name ORDER BY name) AS lighting
FROM products
WHERE category = 'lighting';
{
"items": [
{
"qty": 1,
"product": "Glow head torch",
"unit_price": 34.50
},
{
"qty": 2,
"product": "Merino socks",
"unit_price": 15.00
},
{
"qty": 1,
"product": "Trail 30 backpack",
"unit_price": 89.95
}
],
"total": 154.45,
"customer": "Asha Rao",
"order_id": 103,
"placed_on": "2026-03-09"
}
with_null | absent_on_null
-------------------------------+-------------------------------
{"id" : 3, "brand" : "Lumen"} | {"id" : 3, "brand" : "Lumen"}
{"id" : 4, "brand" : null} | {"id" : 4}
(2 rows)
lighting
-----------------------------------------
["Basecamp lantern", "Glow head torch"]
(1 row)
jsonb_build_object(key, value, ...)builds an object from alternating keys and values. SQL types are converted: numbers stay numbers, and dates become strings.jsonb_agg(expr ORDER BY ...)is an aggregate that collects the group's values into an array. Here, each item is an object, so the order gets anitemsarray.jsonb_object_agg(key, value)collects key/value pairs into an object.jsonb_prettyformats the result over several lines. Notice thatjsonbsorted the top-level keys by length and then alphabetically, so don't rely on key order injsonb.- The standard constructors, PostgreSQL 16+, are
JSON_OBJECT('key': value),JSON_ARRAY,JSON_OBJECTAGGandJSON_ARRAYAGG.ABSENT ON NULLleaves out keys whose value is NULL, instead of writingnull.
MySQL has JSON_OBJECT('k', v), JSON_ARRAYAGG and JSON_OBJECTAGG. SQL Server has FOR JSON PATH, which turns a whole query result into JSON, and SQL Server 2025 added JSON_OBJECTAGG and JSON_ARRAYAGG. SQLite has json_object, json_array and json_group_array.
Building JSON in one query is efficient, because it replaces one query per order with one query for everything. But keep it for the edges of the system: inside the database, ordinary rows are easier to filter, join and aggregate.
Changing documents
CREATE TABLE product_specs (
product_id INTEGER PRIMARY KEY,
specs JSONB NOT NULL
);
INSERT INTO product_specs VALUES
(1, '{"season": 3, "waterproof": true, "colours": ["green", "orange"],
"packed": {"length_cm": 45, "diameter_cm": 15}}'),
(2, '{"season": 4, "waterproof": true, "colours": ["green"],
"packed": {"length_cm": 60, "diameter_cm": 22}}'),
(3, '{"lumens": 350, "battery": "AAA", "waterproof": false, "colours": ["black", "red"]}'),
(5, '{"litres": 30, "colours": ["blue", "grey", "black"], "rain_cover": true}');
-- Change parts of a document: jsonb_set, || to merge, - to remove a key
UPDATE product_specs
SET specs = jsonb_set(specs, '{packed,length_cm}', '48')
WHERE product_id = 1;
UPDATE product_specs
SET specs = specs || '{"warranty_years": 2}'
WHERE product_id IN (1, 2);
UPDATE product_specs
SET specs = specs - 'battery'
WHERE product_id = 3;
SELECT product_id, specs
FROM product_specs
WHERE product_id IN (1, 3)
ORDER BY product_id;
product_id | specs
------------+----------------------------------------------------------------------------------------------------------------------------------------
1 | {"packed": {"length_cm": 48, "diameter_cm": 15}, "season": 3, "colours": ["green", "orange"], "waterproof": true, "warranty_years": 2}
3 | {"lumens": 350, "colours": ["black", "red"], "waterproof": false}
(2 rows)
jsonb values are replaced as a whole, but these operators compute the new document from the old one:
jsonb_set(doc, path, new_value)replaces the value at a path, here the tent's packed length. The new value must be JSON, so a string needs quotes inside the literal:'"AA"'.jsonb_insertadds a value into an array.||merges two objects: keys from the right side are added or replace existing ones. It adds a warranty to both tents.-removes a key, and#-removes the value at a path.
In MySQL, use JSON_SET, JSON_INSERT, JSON_REPLACE and JSON_REMOVE. SQL Server uses JSON_MODIFY, and Oracle uses JSON_TRANSFORM.
Indexing JSON
Querying inside JSON can be fast, with the right index:
-- One index for containment, existence and path operators on the whole document
CREATE INDEX product_specs_gin ON product_specs USING GIN (specs);
-- An ordinary B-tree index on one extracted value
CREATE INDEX product_specs_season ON product_specs (((specs ->> 'season')::int));
- A GIN index on a
jsonbcolumn supports@>,?,?|,?&,@?and@@. With thejsonb_path_opsoperator class it's smaller and faster, but supports only@>,@?and@@. - An expression index on one extracted value supports ordinary comparisons and sorting, if the query uses exactly the same expression.
MySQL indexes JSON through generated columns or functional indexes, and multi-valued indexes for arrays. SQL Server indexes computed columns that use JSON_VALUE, and SQL Server 2025 added JSON indexes. Article 55 covers indexes in general.
When to use JSON, and when not
JSON columns are good for:
- attributes that genuinely vary between rows, like the specifications here
- data received from or sent to other systems, kept as delivered
- optional settings and metadata that queries rarely filter on
They're a poor replacement for proper columns and tables:
- The database can't enforce types, NOT NULL, foreign keys or uniqueness inside a document without extra work. A typo like
"seasn"is accepted silently. - Values that are queried, joined or aggregated all the time are simpler and faster as columns.
- Arrays of related things, such as an order's items, usually belong in their own table (article 51), where each can be referenced and changed on its own.
A common, effective design is a hybrid: ordinary columns for the core fields every row has, and one jsonb column for the rest. When a JSON field turns out to matter, promote it to a column. CHECK constraints can add some guarantees, such as CHECK (jsonb_typeof(specs -> 'colours') = 'array').
What's current
- PostgreSQL 17 added
JSON_TABLEand the standard query functionsJSON_VALUE,JSON_QUERYandJSON_EXISTS. PostgreSQL 16 added the standard constructorsJSON_OBJECT,JSON_ARRAY,JSON_OBJECTAGGandJSON_ARRAYAGG, and theIS JSONpredicate. - SQL Server 2025 added a native
jsontype,JSON_OBJECTAGG,JSON_ARRAYAGGand JSON indexes. - SQLite 3.45 added
jsonb, a binary JSON format stored in blobs, alongside its text JSON functions. - SQL added a JSON data type to the standard, along with simplified accessors such as
doc.season.
Common questions
Should I use json or jsonb?
jsonb, unless you need the exact original text, including key order and duplicate keys.
What's the difference between -> and ->>?
-> returns JSON, and ->> returns text. Use ->>, with a cast if needed, when comparing values with ordinary SQL values.
Why does my numeric comparison on a JSON value give wrong results?
->> returns text, and text compares character by character. Cast it: (doc ->> 'n')::int > 5, or use JSON_VALUE(doc, '$.n' RETURNING int).
How do I turn a JSON array into rows?
jsonb_array_elements or JSON_TABLE in PostgreSQL, JSON_TABLE in MySQL and Oracle, OPENJSON in SQL Server, json_each in SQLite.
Can I index JSON? Yes. In PostgreSQL, a GIN index covers containment and path queries on the whole document, and an expression index covers one extracted value.
Is JSON a replacement for normalised tables? No. Use it for data that varies or is exchanged as a whole, and ordinary columns and tables for everything with a fixed structure.
Summary
- Store JSON in
jsonbin PostgreSQL. Other databases haveJSONtypes or text with JSON functions. ->and->>extract JSON and text,#>and#>>follow paths. Cast text before comparing numbers.@>tests containment, and?tests for keys.jsonb_array_elements,jsonb_eachandJSON_TABLEturn documents into rows.- SQL/JSON path, with
JSON_VALUE,JSON_QUERYandJSON_EXISTS, is the standard, portable way to query documents. jsonb_build_object,jsonb_aggand the standardJSON_OBJECTandJSON_ARRAYAGGbuild JSON from rows.jsonb_set,||and-change documents.- GIN and expression indexes make JSON queries fast.
- Keep JSON for genuinely variable data, and use columns for the fields you query and constrain.
Practice questions
What does '{"a": 1, "a": 2}'::jsonb ->> 'a' return, and what type is it?
Answer
'2', as text. jsonb keeps only the last value of a duplicate key, and ->> returns text.
Write a query that lists the names of products whose specs say they are waterproof, using containment.
Answer
SELECT p.name
FROM products p
JOIN product_specs s ON s.product_id = p.product_id
WHERE s.specs @> '{"waterproof": true}'
ORDER BY p.name;
It returns Ridge 2 tent and Summit 4 tent. The torch has "waterproof": false, and the backpack has no waterproof key.
Write a query that counts how many products come in each colour.
Answer
SELECT c.colour, COUNT(*) AS products
FROM product_specs s,
jsonb_array_elements_text(s.specs -> 'colours') AS c(colour)
GROUP BY c.colour
ORDER BY products DESC, c.colour;
black 2, green 2, then blue, grey, orange and red with 1 each.
A query uses WHERE specs ->> 'season' > '3'. What's wrong with it, and how do you fix it?
Answer
It compares text, so a value of '10' would be less than '3'. Cast before comparing: WHERE (specs ->> 'season')::int > 3, or use JSON_VALUE(specs, '$.season' RETURNING int) > 3.
Write a query that returns a single JSON array of the names of all products in the packs category, sorted by name.
Answer
SELECT jsonb_agg(name ORDER BY name)
FROM products
WHERE category = 'packs';
It returns ["Day 18 backpack", "Trail 30 backpack"]. JSON_ARRAYAGG(name ORDER BY name) does the same in standard syntax.
Previous: Regular Expressions in SQL

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.