Skip to content

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)
Questionjsonjsonb
What is storedAn exact copy of the input textA decomposed binary format
White space, key order, duplicate keysKeptNot kept. The last duplicate key wins
Cost of reading a fieldThe text is parsed again on every callNo reparsing. Input is slightly slower
Containment operator and GIN indexesNot availableAvailable

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 coupon key. 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.

TaskPostgreSQL 16BigQuerySnowflakeSQL Server
Column typejsonbJSONVARIANTjson (SQL Server 2025, Azure SQL Database), or text in nvarchar(max)
Field as JSONpayload -> 'customer'payload.customerpayload:customerJSON_QUERY(payload, '$.customer')
Nested field as textpayload #>> '{customer,country}'JSON_VALUE(payload, '$.customer.country')payload:customer.country::stringJSON_VALUE(payload, '$.customer.country')
Field as an integer(payload #>> '{customer,id}')::integerINT64(payload.customer.id)payload:customer.id::numberJSON_VALUE(payload, '$.customer.id' RETURNING int) (json column, SQL Server 2025)
Array to rowsjsonb_array_elements(payload -> 'items')UNNEST(JSON_QUERY_ARRAY(payload.items))LATERAL FLATTEN(input => payload:items)CROSS APPLY OPENJSON(payload, '$.items')
Build JSONjsonb_build_object, jsonb_aggJSON_OBJECT, TO_JSONOBJECT_CONSTRUCT, ARRAY_AGGFOR JSON PATH, JSON_OBJECT
Missing keyNULLNULLNULLNULL 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/A to numeric raises 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

The PostgreSQL output shown is what psql printed on PostgreSQL 16. Vendor pages were read in November 2026.