Back to all posts

PostgreSQL JSONB: Operators, GIN Indexes, and Query Examples

For SQL users with a JSONB column in front of them, who need to read a field out of it, filter on it and index it.

On this page

A jsonb column holds a JSON document in each row of a PostgreSQL table, and PostgreSQL's JSON operators read values out of the document. For example, you can keep each country's cities in one JSON array and list every city as a row of its own.

The operators go where a column name would go:

SELECT jsonb_column -> 'key',
       jsonb_column ->> 'key',
       jsonb_column #>> '{key,position}'
FROM table_name
WHERE jsonb_column @> 'json_fragment';

key is a field name, position is a place in an array, counted from 0, and json_fragment is a piece of JSON in quotes.

PostgreSQL 18 has these jsonb operators:

OperatorReturnsWhat it does
->jsonbobject field, or array element by position
->>textthe same, as text
#>jsonbvalue at a path
#>>textvalue at a path, as text
@>booleanleft contains right
<@booleanleft is contained by right
?booleankey or array element exists
?|booleanany of the listed keys exist
?&booleanall of the listed keys exist
||jsonbconcatenate arrays, or merge objects
-jsonbremove a key, a matching string element, or a position

Create a sample table of two countries, each with its cities in one jsonb array:

CREATE TABLE countries (
    id     SERIAL PRIMARY KEY,
    name   TEXT NOT NULL,
    cities JSONB
);

INSERT INTO countries (name, cities) VALUES
('France', '[
  {"name": "Paris",     "population": 2148000},
  {"name": "Lyon",      "population": 513000},
  {"name": "Marseille", "population": 861000, "port": true}
]'),
('Germany', '[
  {"name": "Berlin",  "population": 3769000},
  {"name": "Munich",  "population": 1472000},
  {"name": "Hamburg", "population": 1841000, "port": true}
]');

PostgreSQL parses each string into jsonb as it inserts it, so a malformed document fails the INSERT. Only the two port cities have a port key.

Every statement in this article was run on PostgreSQL 18.6. Run the statements in the order shown. The updates further down change the France row, and the queries after them read the changed row.

The -> and ->> operators

-> returns an object's field, or an array's element, as jsonb. ->> returns the same value as text. For example, you can read the name of each country's first city.

SELECT name,
       cities -> 0 -> 'name'  AS with_arrow,
       cities -> 0 ->> 'name' AS with_double_arrow
FROM countries
ORDER BY name;
namewith_arrowwith_double_arrow
France"Paris"Paris
Germany"Berlin"Berlin

cities -> 0 is the first element of the array, and -> 'name' then reads the name field of that element. With ->, Paris keeps its JSON quotes, because the value is still jsonb. With ->>, Paris is plain text, the form that a comparison or your application needs.

Array positions start at 0. A negative position counts from the end, so cities -> -1 is a country's last city.

The #> and #>> operators

#>> follows a path of keys and array positions, and returns the value at the end of the path as text. #> returns the same value as jsonb. For example, you can read the name of each country's second city.

SELECT name, cities #>> '{1,name}' AS second_city
FROM countries
ORDER BY name;
namesecond_city
FranceLyon
GermanyMunich

The path {1,name} means the element at position 1, then its name key. Position 1 is the second city: Lyon for France, Munich for Germany. One path replaces a chain of arrows, which helps once a document is several levels deep.

Here is what each expression reads from the France row:

The cities array of the France row as three objects at positions 0 to 2, only Marseille with a port key, and what cities -> 0, cities -> 0 ->> 'name', cities #>> '{1,name}' and cities -> -1 each return

jsonb_array_elements

jsonb_array_elements returns one row for each element of a JSON array. For example, you can list every city of every country as a row of its own.

SELECT c.name AS country,
       city ->> 'name'       AS city,
       city ->> 'population' AS population
FROM countries c,
     jsonb_array_elements(c.cities) AS city;
countrycitypopulation
FranceParis2148000
FranceLyon513000
FranceMarseille861000
GermanyBerlin3769000
GermanyMunich1472000
GermanyHamburg1841000

France's three cities became three rows, and Germany's became three more.

The comma before the function joins each country to its own cities: the function runs once for each country and reads that country's cities. PostgreSQL calls this a lateral join. For a function in FROM, the LATERAL keyword is optional, as the documentation says.

jsonb_array_elements turns the France row, whose cities array holds three objects, into three result rows, one per city, with France repeated as the country
The jsonb_array_elements query in the DbSchema SQL Editor, with the six city rows of France and Germany in the result grid

The ? operator

? checks whether a JSON object has a given key. For example, you can find the cities that have a port key.

SELECT c.name AS country,
       city ->> 'name' AS city
FROM countries c,
     jsonb_array_elements(c.cities) AS city
WHERE city ? 'port';
countrycity
FranceMarseille
GermanyHamburg

Only Marseille and Hamburg have the key, so only their rows pass. ? ignores the key's value. ?| and ?& take an array of keys, and check whether any or all of them exist.

The @> containment operator

@> checks whether a document contains a JSON fragment. For example, you can find the country whose cities include Paris.

SELECT name
FROM countries
WHERE cities @> '[{"name": "Paris"}]';
name
France

The fragment is an array with one object, {"name": "Paris"}. France's array holds an object with that name, so France matches. The other keys of Paris, and the other cities, don't affect the match.

jsonb_path_query

jsonb_path_query returns each value in a document that a JSON path matches, one row per value. For example, you can list each country's cities of more than a million people.

SELECT c.name AS country,
       jsonb_path_query(c.cities, '$[*] ? (@.population > 1000000).name') AS big_city
FROM countries c;
countrybig_city
France"Paris"
Germany"Berlin"
Germany"Munich"
Germany"Hamburg"

The path has four parts:

  • $ is the whole array.
  • [*] takes each element of the array.
  • ? (@.population > 1000000) keeps the elements whose population is over a million. @ is the element under test.
  • .name reads the name of each element that was kept.

The names come back as jsonb, so they keep their quotes.

jsonb_set

jsonb_set replaces the value at a path inside a document. For example, you can change the population of France's first city.

UPDATE countries
SET cities = jsonb_set(cities, '{0,population}', '2161000')
WHERE name = 'France'
RETURNING name, cities -> 0 AS first_city;
namefirst_city
France{"name": "Paris", "population": 2161000}

Paris now has a population of 2161000, and the other cities kept theirs. To set a string, write it with its JSON quotes inside the SQL quotes, such as '"Paris"'. The new value is jsonb, and a JSON string has quotes.

The - removal operator

- removes an array element by its position, or an object's key by its name. For example, you can remove Marseille, at position 2, from France's cities.

UPDATE countries
SET cities = cities - 2
WHERE name = 'France'
RETURNING name, cities -> -1 AS last_city;
namelast_city
France{"name": "Lyon", "population": 513000}

France now has two cities, and Lyon is the last one.

The || concatenation operator

|| joins two arrays into one array. For example, you can add Nice to the end of France's cities.

UPDATE countries
SET cities = cities || '[{"name": "Nice", "population": 342000}]'
WHERE name = 'France'
RETURNING name, cities -> -1 AS last_city;
namelast_city
France{"name": "Nice", "population": 342000}

France's cities are now Paris, Lyon and Nice. On two objects, || merges them into one object, and the right-hand value wins a key that both have.

GIN index

A GIN index on a jsonb column finds the rows that match @> or ? without reading the whole table. For example, you can index cities for the Paris filter.

On a two-row table, PostgreSQL reads the table directly, because that costs less than an index lookup. Turn sequential scans, which read every row, off for the session to see the plan that a large table gets:

CREATE INDEX countries_cities_idx ON countries USING GIN (cities);

SET enable_seqscan = off;

EXPLAIN (COSTS OFF)
SELECT name FROM countries WHERE cities @> '[{"name": "Paris"}]';
 Bitmap Heap Scan on countries
   Recheck Cond: (cities @> '[{"name": "Paris"}]'::jsonb)
   ->  Bitmap Index Scan on countries_cities_idx
         Index Cond: (cities @> '[{"name": "Paris"}]'::jsonb)

The Bitmap Index Scan line names countries_cities_idx, so PostgreSQL used the index. Run RESET enable_seqscan afterwards.

Each GIN index has an operator class, the set of operators that the index serves. The default class, jsonb_ops, serves @>, ?, ?| and ?&. jsonb_path_ops, written USING GIN (cities jsonb_path_ops), serves @> but not the ? operators, and the documentation says it is "usually much smaller":

FilterGIN jsonb_ops, the defaultGIN jsonb_path_opsB-tree on an expression
@>yesyesno
?, ?|, ?&yesnono
(cities -> 0 ->> 'population')::int > 3000000nonoyes, on that expression

A filter on one field needs a B-tree index on the same expression, written exactly as the query writes it: CREATE INDEX ON countries (((cities -> 0 ->> 'population')::int)).

JOIN LATERAL for nested arrays

With JOIN LATERAL, a function in FROM can read the values of the tables and functions to its left. For example, you can expand an array that sits inside another array, with one join for each level.

Create a second table, products, where each color variant of a laptop has its own list of options:

CREATE TABLE products (
    id    SERIAL PRIMARY KEY,
    name  TEXT,
    specs JSONB
);

INSERT INTO products (name, specs) VALUES
('Laptop', '{
  "variants": [
    {"color": "Silver", "options": [
      {"ram": "16GB", "storage": "512GB SSD"},
      {"ram": "32GB", "storage": "1TB SSD"}
    ]},
    {"color": "Black", "options": [
      {"ram": "8GB", "storage": "256GB SSD"},
      {"ram": "16GB", "storage": "512GB SSD"}
    ]}
  ]
}');

SELECT p.name,
       variant ->> 'color'  AS color,
       option ->> 'ram'     AS ram,
       option ->> 'storage' AS storage
FROM products p
JOIN LATERAL jsonb_array_elements(p.specs -> 'variants') AS variant ON true
JOIN LATERAL jsonb_array_elements(variant -> 'options')  AS option  ON true;
namecolorramstorage
LaptopSilver16GB512GB SSD
LaptopSilver32GB1TB SSD
LaptopBlack8GB256GB SSD
LaptopBlack16GB512GB SSD

The first join turns the two variants into two rows. The second join reads variant from the first join, and turns each variant's two options into rows: four rows in all. ON true is there because a join needs a condition, and the nesting already pairs the rows.

If a product's variants array is empty, the inner joins drop the product. Write LEFT JOIN LATERAL at both levels to keep it, with NULL in color, ram and storage.

json and jsonb

The json type stores the text exactly as written, and jsonb stores it parsed, in a binary form. For example, you can cast the same text to both types and compare them.

SELECT '{"b": 1, "a": 2, "a": 3}'::json  AS as_json,
       '{"b": 1, "a": 2, "a": 3}'::jsonb AS as_jsonb;
as_jsonas_jsonb
{"b": 1, "a": 2, "a": 3}{"a": 3, "b": 1}

json returns the text as written, with both values of a. jsonb keeps only the last value of a, and orders the keys its own way. The documentation adds that json is parsed again on every use, while jsonb is "significantly faster to process".

json also has no @> operator and no GIN operator class. Use jsonb, unless you have to return the exact text, such as a webhook body whose signature was computed over its exact characters.

What goes wrong

Comparing ->> with a number

->> returns text, and PostgreSQL has no > between text and a number:

SELECT name FROM countries WHERE cities -> 1 ->> 'population' > 1000000;
ERROR:  operator does not exist: text > integer

Quoting the number removes the error, but the answer is wrong:

SELECT name FROM countries WHERE cities -> 1 ->> 'population' > '1000000' ORDER BY name;
name
France
Germany

Text is compared one character at a time, so Lyon's '513000' comes after '1000000'. Cast the value before you compare it: with (cities -> 1 ->> 'population')::int > 1000000, only Germany is returned.

? on an array of objects

? looks at the top level only. The top level of cities is an array of objects, so ? finds no port key there:

SELECT name, cities ? 'port' AS has_port
FROM countries
ORDER BY name;
namehas_port
Francef
Germanyf

On an array, ? matches a string element, as in '["Paris", "Lyon"]' ? 'Paris'. To test a key of each object, expand the array with jsonb_array_elements first.

jsonb_set with a missing parent key

jsonb_set adds a missing key at the end of the path. If a key earlier in the path is missing, jsonb_set returns the document unchanged, without an error:

SELECT jsonb_set('{"a": {"b": 1}}', '{x,b}', '2') AS missing_parent,
       jsonb_set('{"a": {"b": 1}}', '{a,c}', '2') AS missing_last_key;
missing_parentmissing_last_key
{"a": {"b": 1}}{"a": {"b": 1, "c": 2}}

The path {x,b} needs a key x, and the document has none. The path {a,c} ends under the existing key a, so c is added.

When to use a jsonb column

Use jsonb for fields that differ from row to row, such as product attributes that depend on the category. Keep a field in a column of its own when every row has it, when a query joins on it, or when it needs a foreign key. When a field of the document starts to appear in WHERE and GROUP BY across your queries, move it to a column.

PostgreSQL checks nothing inside a document. Add a CHECK constraint for the shape that your queries rely on:

ALTER TABLE countries
ADD CONSTRAINT cities_is_array
CHECK (jsonb_typeof(cities) = 'array');

INSERT INTO countries (name, cities)
VALUES ('Italy', '{"name": "Rome"}');
ERROR:  new row for relation "countries" violates check constraint "cities_is_array"
DETAIL:  Failing row contains (3, Italy, {"name": "Rome"}).

The cities column now refuses an object.

Explore a jsonb column in DbSchema

The DDL of a jsonb column says only jsonb, and nothing about what the documents hold. DbSchema connects to PostgreSQL, reads its tables and columns, and draws them on an interactive diagram. For a JSON column, DbSchema also reads a sample of the stored documents, and lists the fields it finds under the column, nested arrays included:

The products table on a DbSchema diagram, with specs expanded into variants, color, options, ram and storage, above the JOIN LATERAL query and its four rows in the SQL Editor

The fields come from a sample, so they show what those documents contain, not a structure that PostgreSQL enforces.

In the Query Builder, right-click products on the diagram, choose Query Editor, and tick the fields you want. DbSchema writes one jsonb_array_elements for each array level and reads each ticked field with ->>, so the result has one row per option:

The DbSchema Query Builder on products, with specs expanded into variants and options, the ram and storage fields ticked, and four result rows

Type what a document holds in the column's Comment box. DbSchema keeps the comment in its model, and while connected writes it to PostgreSQL as a COMMENT ON COLUMN.

The HTML5 documentation, from File → Export As... → HTML5/PDF Documentation, shows the comment as a mouse-over tooltip on the diagram.

Download DbSchema from https://dbschema.com/download.html, connect it to the database that holds your jsonb column, and run the queries above in the SQL Editor. The free Community Edition connects, reads the schema, draws the diagram and runs the SQL Editor. The Query Builder, the HTML5 documentation and saving the model to a file are in Pro.

DbSchema Database Designer