Beginner's Guide to JSON in SQL, With PostgreSQL Examples
How to store and query JSON in SQL, run on PostgreSQL 16 with real output: extracting fields, casting them, expanding arrays, the two mistakes that return a wrong number without an error, and when to flatten JSON into typed columns.
On this page · 21 sections
- What JSON is, and the sample table
- json versus jsonb
- Extract a field as JSON or as text
- Nested fields
- Cast a JSON value to a number or date, and filter on it
- Two mistakes that return a wrong result without an error
- Comparing the JSON form of a field with text
- Comparing numbers as text
- A missing key returns NULL, not an error
- Test containment with @>
- Expand a JSON array into rows
- Turn rows back into JSON
- The same tasks in BigQuery, Snowflake, and SQL Server
- When to flatten JSON into typed columns
- Frequently Asked Questions
- What are the benefits of using a JSON data type instead of a text column?
- How can you query and modify JSON data within SQL?
- How do you convert a SQL query result to JSON?
- How do you validate JSON data in SQL?
- How do you format JSON so it is easier to read?
- Primary sources and further reading
- Topic
- SQL for Analytics Engineers
- Category
- SQL
JSON in SQL means storing a JSON document in a table column and reading its fields with SQL operators and functions, so one query can use ordinary columns and semi-structured data (data without a fixed set of columns) together. In PostgreSQL 16 the column type to use is jsonb: -> returns a field as JSON, ->> returns it as text, and a cast turns that text into a number or a date. Every statement below was run on PostgreSQL 16, and a table near the end maps the same tasks to BigQuery, Snowflake, and SQL Server.
What JSON is, and the sample table
JSON (JavaScript Object Notation) is a text format made of objects, which are pairs of keys and values inside curly braces, and arrays, which are lists inside square brackets. A value can be a string, a number, true, false, null, an object, or an array, so documents can nest.
The examples use one table of order events. Each payload holds a nested customer object and an items array. Event 4 has no country and no items, event 3's coupon is JSON null, and events 2 and 4 have no coupon key.
create table events (
event_id integer primary key,
payload jsonb not null
);
insert into events values
(1, '{"status": "paid", "total": 120.50, "ordered_on": "2026-03-02", "coupon": "SPRING10", "customer": {"id": 17, "country": "US"}, "items": [{"sku": "A-100", "qty": 2}, {"sku": "B-200", "qty": 1}]}'),
(2, '{"status": "paid", "total": 89.00, "ordered_on": "2026-03-02", "customer": {"id": 21, "country": "CA"}, "items": [{"sku": "A-100", "qty": 1}]}'),
(3, '{"status": "refunded", "total": 45.00, "ordered_on": "2026-03-05", "coupon": null, "customer": {"id": 17, "country": "US"}, "items": [{"sku": "C-300", "qty": 3}]}'),
(4, '{"status": "paid", "total": 310.00, "ordered_on": "2026-03-09", "customer": {"id": 34}, "items": []}');
json versus jsonb
PostgreSQL has two JSON types. Both reject input that is not valid JSON, which a text column would accept. They differ in what they store:
select
'{"b": 1, "a": 2, "a": 3}'::json as as_json,
'{"b": 1, "a": 2, "a": 3}'::jsonb as as_jsonb;
as_json | as_jsonb
----------------------------+------------------
{"b": 1, "a": 2, "a": 3} | {"a": 3, "b": 1}
(1 row)
| Question | json | jsonb |
|---|---|---|
| What is stored | An exact copy of the input text | A decomposed binary format |
| White space, key order, duplicate keys | Kept | Not kept. The last duplicate key wins |
| Cost of reading a field | The text is parsed again on every call | No reparsing. Input is slightly slower |
| Containment operator and GIN indexes | Not available | Available |
The PostgreSQL documentation advises most applications to use jsonb, as this article does.
Extract a field as JSON or as text
-> returns a field as JSON, and ->> returns it as text:
select
payload -> 'status' as status_json,
pg_typeof(payload -> 'status') as json_type,
payload ->> 'status' as status_text,
pg_typeof(payload ->> 'status') as text_type
from events
where event_id = 1;
status_json | json_type | status_text | text_type
-------------+-----------+-------------+-----------
"paid" | jsonb | paid | text
(1 row)
The jsonb result still carries the string's double quotes. Use -> to step into an object or array, and ->> for a value you compare, group by, or cast. Given an integer in place of a key, both return an array element, counting from zero.
Nested fields
Give #>> the whole path as a list of keys and array positions. #> is the version that returns JSON.
select
event_id,
payload #>> '{customer,country}' as country,
payload #>> '{items,0,sku}' as first_sku
from events
order by event_id;
event_id | country | first_sku
----------+---------+-----------
1 | US | A-100
2 | CA | A-100
3 | US | C-300
4 | |
(4 rows)
Chaining gives the same country values: payload -> 'customer' ->> 'country'. Event 4 has no country and no first item, so its cells are NULL, which psql prints as empty.
Cast a JSON value to a number or date, and filter on it
->> returns text, so cast the result before arithmetic or date logic. This query filters on one JSON field and casts two others:
select
(payload ->> 'ordered_on')::date as ordered_on,
count(*) as paid_orders,
sum((payload ->> 'total')::numeric) as revenue
from events
where payload ->> 'status' = 'paid'
group by ordered_on
order by ordered_on;
ordered_on | paid_orders | revenue
------------+-------------+---------
2026-03-02 | 2 | 209.50
2026-03-09 | 1 | 310.00
(2 rows)
Two mistakes that return a wrong result without an error
Comparing the JSON form of a field with text
select
count(*) filter (where (payload -> 'status')::text = 'paid') as arrow_as_text,
count(*) filter (where payload ->> 'status' = 'paid') as double_arrow
from events;
arrow_as_text | double_arrow
---------------+--------------
0 | 3
(1 row)
When cast to text, -> output keeps its quotes, so the six characters "paid" never equal paid. Without the cast, payload -> 'status' = 'paid' fails with invalid input syntax for type json, because PostgreSQL reads the right-hand side as JSON.
Comparing numbers as text
select
event_id,
payload ->> 'total' as total
from events
where payload ->> 'total' > '100'
order by event_id;
event_id | total
----------+--------
1 | 120.50
2 | 89.00
3 | 45.00
4 | 310.00
(4 rows)
As text, 89.00 and 45.00 sort after 100, so they pass a filter meant for totals over 100. With (payload ->> 'total')::numeric > 100 only events 1 and 4 come back. Likewise max(payload ->> 'total') returns 89.00, not 310.00. Summing text is caught: sum(payload ->> 'total') fails with function sum(text) does not exist.
A missing key returns NULL, not an error
PostgreSQL documents that the extraction operators return NULL when the requested key or array element does not exist.
select
event_id,
payload -> 'coupon' as as_json,
payload ->> 'coupon' as as_text,
payload ? 'coupon' as has_key
from events
order by event_id;
event_id | as_json | as_text | has_key
----------+------------+----------+---------
1 | "SPRING10" | SPRING10 | t
2 | | | f
3 | null | | t
4 | | | f
(4 rows)
- Events 2 and 4 have no
couponkey. Both operators return SQL NULL. - Event 3 has the key with a JSON
null.->returns that JSON value, which is not SQL NULL.->>returns SQL NULL. ?tests whether a top-level key exists, which tells the two cases apart.
A misspelled key behaves the same way: payload ->> 'Status' is NULL in all four rows. So after extracting a field, count its non-null values.
Test containment with @>
@> asks whether the document on the left contains the one on the right, matching its structure as well as its values.
select event_id
from events
where payload @> '{"customer": {"country": "US"}}'
order by event_id;
event_id
----------
1
3
(2 rows)
It also searches arrays: payload @> '{"items": [{"sku": "A-100"}]}' returns events 1 and 2. Types must match: '{"customer": {"id": "17"}}' matches nothing, because the id is stored as a number. A GIN index (create index events_payload_gin on events using gin (payload)) supports @> searches.
Expand a JSON array into rows
jsonb_array_elements returns one row per array element. A lateral join runs it once for each event.
select
e.event_id,
item ->> 'sku' as sku,
(item ->> 'qty')::integer as qty
from events as e
cross join lateral jsonb_array_elements(e.payload -> 'items') as item
order by e.event_id, sku;
event_id | sku | qty
----------+-------+-----
1 | A-100 | 2
1 | B-200 | 1
2 | A-100 | 1
3 | C-300 | 3
(4 rows)
Event 4 is missing because its array is empty. left join lateral ... on true keeps it, with NULL in sku and qty.
Turn rows back into JSON
jsonb_build_object builds an object from alternating keys and values, and the aggregate jsonb_agg collects a group's values into an array.
select
payload #>> '{customer,id}' as customer_id,
jsonb_agg(
jsonb_build_object(
'event_id', event_id,
'total', (payload ->> 'total')::numeric
)
order by event_id
) as orders
from events
group by customer_id
order by customer_id;
customer_id | orders
-------------+---------------------------------------------------------------------
17 | [{"total": 120.50, "event_id": 1}, {"total": 45.00, "event_id": 3}]
21 | [{"total": 89.00, "event_id": 2}]
34 | [{"total": 310.00, "event_id": 4}]
(3 rows)
The keys come out in a different order than they were written, because jsonb does not preserve key order.
The same tasks in BigQuery, Snowflake, and SQL Server
Only the PostgreSQL column was run. The other columns are documented syntax that was not run, checked against the vendor pages listed under Primary sources.
| Task | PostgreSQL 16 | BigQuery | Snowflake | SQL Server |
|---|---|---|---|---|
| Column type | jsonb | JSON | VARIANT | json (SQL Server 2025, Azure SQL Database), or text in nvarchar(max) |
| Field as JSON | payload -> 'customer' | payload.customer | payload:customer | JSON_QUERY(payload, '$.customer') |
| Nested field as text | payload #>> '{customer,country}' | JSON_VALUE(payload, '$.customer.country') | payload:customer.country::string | JSON_VALUE(payload, '$.customer.country') |
| Field as an integer | (payload #>> '{customer,id}')::integer | INT64(payload.customer.id) | payload:customer.id::number | JSON_VALUE(payload, '$.customer.id' RETURNING int) (json column, SQL Server 2025) |
| Array to rows | jsonb_array_elements(payload -> 'items') | UNNEST(JSON_QUERY_ARRAY(payload.items)) | LATERAL FLATTEN(input => payload:items) | CROSS APPLY OPENJSON(payload, '$.items') |
| Build JSON | jsonb_build_object, jsonb_agg | JSON_OBJECT, TO_JSON | OBJECT_CONSTRUCT, ARRAY_AGG | FOR JSON PATH, JSON_OBJECT |
| Missing key | NULL | NULL | NULL | NULL in lax mode (the default), an error in strict mode |
The text trap carries over: BigQuery's JSON_VALUE returns a STRING and SQL Server's returns nvarchar(4000) unless RETURNING is used, so cast before comparing numbers. Containment has no row because a like-for-like function was found only in SQL Server 2025 (JSON_CONTAINS). See also BigQuery SQL best practices, the beginner's guide to Snowflake, and working with XML in SQL Server.
When to flatten JSON into typed columns
Querying JSON in place suits exploration. For fields that reports depend on, extract and cast them once in a staging model, the layer that dbt's project guide uses for renaming and type casting. Flatten a field when:
- More than one model or dashboard reads it. The key name and the cast then live in one place.
- It is used in joins, filters, or GROUP BY. A typed column is compared as its type, not as text.
- You want to check it. A bad value fails the cast in one known place: casting
N/Atonumericraises an error.
create view stg_orders as
select
event_id as order_id,
payload ->> 'status' as status,
(payload ->> 'total')::numeric(10, 2) as total,
(payload ->> 'ordered_on')::date as ordered_on,
(payload #>> '{customer,id}')::integer as customer_id,
payload #>> '{customer,country}' as customer_country
from events;
Selecting from the view returns the four orders with total as numeric, ordered_on as date, and customer_id as integer. Give the items array its own model, one row per item, because its grain (what one row represents) differs. Leave rarely used keys in the payload and keep the raw column, so new keys can be extracted later. dbt project structure best practices covers the staging layer. For more, see the SQL hub and the graded practice exercises.
Frequently Asked Questions
What are the benefits of using a JSON data type instead of a text column?
The type checks that every stored value is valid JSON, and the JSON operators work on it directly. PostgreSQL's jsonb is also stored in a parsed binary form, so queries do not reparse the text, and it supports GIN indexes.
How can you query and modify JSON data within SQL?
In PostgreSQL, read fields with ->, ->>, and #>>, filter with a cast or @>, and expand arrays with jsonb_array_elements. To change a document, jsonb_set(payload, '{status}', '"shipped"') returns a copy with one value replaced, || merges in keys, and - removes a key. The stored row changes only in an UPDATE.
How do you convert a SQL query result to JSON?
In PostgreSQL, to_jsonb turns a row into an object, jsonb_build_object builds an object from listed keys and values, and jsonb_agg collects rows into an array. SQL Server adds a FOR JSON clause to the SELECT statement, and BigQuery has TO_JSON.
How do you validate JSON data in SQL?
A json or jsonb column validates on input: casting the truncated document '{"a": 1' fails with invalid input syntax for type json. For text not yet converted, PostgreSQL 16 has the IS JSON predicate, which returned false for that document. SQL Server's function is ISJSON.
How do you format JSON so it is easier to read?
In PostgreSQL, jsonb_pretty(payload) returns the document as indented text with one key per line, for reading in a SQL client.
Primary sources and further reading
- JSON types, PostgreSQL 16.
jsonversusjsonb, containment, GIN indexes. - JSON functions and operators, PostgreSQL 16. The operators, NULL for a missing key, and the array, construction, and validation functions.
- Aggregate functions and table expressions, PostgreSQL 16.
jsonb_agg, lateral joins. - Work with JSON data in GoogleSQL and JSON functions, Google Cloud. The BigQuery column.
- Querying semi-structured data, FLATTEN, GET, OBJECT_CONSTRUCT, and ARRAY_AGG, Snowflake. The Snowflake column.
- JSON data in SQL Server, JSON data type, JSON_VALUE, JSON path expressions, OPENJSON, JSON_OBJECT, and JSON_CONTAINS, Microsoft. The SQL Server column.
- Staging: Preparing our atomic building blocks, dbt documentation. Renaming and type casting in staging models.
The PostgreSQL output shown is what psql printed on PostgreSQL 16. Vendor pages were read in November 2026.
- SQL
Learn SQL: Introduction to SQL with a No‑Fluff 4‑Week Plan
A practitioner’s 4‑week plan to learn SQL for data analytics. Daily graded practice, concrete milestones, and realistic examples—no fluff, just queries.
- SQL
LAG and LEAD in SQL: Compare Each Row With the One Before or After
A practitioner’s guide to SQL LAG and LEAD for period-over-period analysis, churn flags, and sessionization—plus syntax, pitfalls, and performance tips.
- SQL
SQL QUALIFY Clause: Filter Window Functions Without Subqueries
QUALIFY lets you filter window-function outputs inline, avoiding extra subqueries and CTEs. Learn syntax, patterns, performance tips, and cross-database equivalents.
Drill it in the exercise library.
Portfolio-ready builds on this topic.
- intermediate · open →
SQL Alien Invasion Challenge: Defend Earth
Crisis-response analytics: defend Earth with multi-table joins, aggregation, and CTEs.
- advanced · open →
SQL Mystery Challenge: The Case of the Vanishing Artifacts
Investigative SQL: follow the evidence across museum audit logs to unmask a thief.
