JSONB modification functions let you change parts of JSON data stored in a database easily.
JSONB modification functions in PostgreSQL
jsonb_set(target jsonb, path text[], new_value jsonb, create_missing boolean DEFAULT true) RETURNS jsonb jsonb_insert(target jsonb, path text[], new_value jsonb, insert_after boolean DEFAULT false) RETURNS jsonb jsonb_strip_nulls(jsonb) RETURNS jsonb jsonb_delete_path(target jsonb, path text[]) RETURNS jsonb
jsonb_set updates or adds a value at the specified path.
path is an array of keys or indexes to locate where to change inside the JSON.
age to 31.SELECT jsonb_set('{"name": "John", "age": 30}'::jsonb, '{age}', '31'::jsonb);
city with value New York.SELECT jsonb_set('{"name": "John"}'::jsonb, '{city}', '"New York"'::jsonb, true);
green before index 1 in the colors array.SELECT jsonb_insert('{"colors": ["red", "blue"]}'::jsonb, '{colors,1}', '"green"'::jsonb, false);
SELECT jsonb_strip_nulls('{"a":1, "b":null}'::jsonb);
This query shows three JSONB modifications: updating age, adding a new key country, and removing null values.
WITH data AS ( SELECT '{"user": {"name": "Alice", "age": 25, "city": "Boston"}}'::jsonb AS info ) SELECT jsonb_set(info, '{user,age}', '26'::jsonb) AS updated_age, jsonb_set(info, '{user,country}', '"USA"'::jsonb, true) AS added_country, jsonb_strip_nulls('{"a":1, "b":null}'::jsonb) AS no_nulls FROM data;
Paths in jsonb_set use curly braces and commas, like {user,age}.
Use jsonb_strip_nulls to clean JSON objects by removing keys with null values.
Remember that JSONB functions return new JSONB values; they do not change data in place unless used in an UPDATE statement.
JSONB modification functions help update, add, or remove parts of JSON data inside PostgreSQL.
They use paths to locate where to make changes inside nested JSON objects or arrays.
These functions return new JSONB values, so use them in SELECT or UPDATE queries to see changes.
Practice
jsonb_set do when used on a JSONB column?Solution
Step 1: Understand the purpose of jsonb_set
The function jsonb_set is designed to update or add a value at a specific location inside JSONB data using a path.Step 2: Compare with other options
The other options describe actions unrelated to jsonb_set's purpose, such as creating or deleting columns or converting data types.Final Answer:
It updates or adds a value at a specified path inside the JSONB data. -> Option DQuick Check:
jsonb_set updates JSONB data [OK]
- Thinking jsonb_set deletes data
- Confusing jsonb_set with data type conversion
- Assuming jsonb_set creates new columns
"age" from a JSONB column data in PostgreSQL?Solution
Step 1: Identify the correct operator for key removal
In PostgreSQL, the minus operator (-) removes a key from JSONB data, sodata - 'age'removes the key "age".Step 2: Check other options for correctness
UPDATE table SET data = jsonb_set(data, '{age}', NULL); tries to set the key to NULL but does not remove it. UPDATE table SET data = data + 'age'; adds a key, which is incorrect. UPDATE table SET data = jsonb_remove(data, 'age'); uses a non-existent function jsonb_remove.Final Answer:
UPDATE table SET data = data - 'age'; -> Option AQuick Check:
Minus operator removes JSONB key [OK]
- Using jsonb_set with NULL to remove keys
- Trying to add keys to remove them
- Using non-existent functions like jsonb_remove
data with value '{"name": "Alice", "details": {"age": 30}}', what will be the result of this query?SELECT jsonb_set(data, '{details,age}', '31', false) FROM table;Solution
Step 1: Understand jsonb_set parameters
The function jsonb_set updates the value at path '{details,age}' to '31' (a JSON string) because the new value is given as text, not as a number.Step 2: Check the effect of the 'create_missing' flag
The last parameter is false, so it updates existing key without creating new ones. The age key is updated to the string '31', not the number 31.Final Answer:
{"name": "Alice", "details": {"age": "31"}} -> Option BQuick Check:
jsonb_set updates value as text unless cast [OK]
- Assuming '31' is numeric without casting
- Expecting no change when create_missing is false
- Confusing JSON string and number types
UPDATE table SET data = jsonb_set(data, '{info,score}', 100);throws an error. What is the likely cause?
Solution
Step 1: Check the new value type in jsonb_set
The third argument must be JSONB type. Passing 100 as an integer without casting causes a type error.Step 2: Verify other options
The path '{info,score}' is invalid syntax and must be a string. is incorrect because the path syntax is valid. jsonb_set cannot update nested keys, only top-level keys. is false; jsonb_set supports nested keys. The data column is not JSONB type. might cause error but question implies the error is from the query syntax.Final Answer:
The new value 100 is not cast to JSONB, causing a type error. -> Option AQuick Check:
jsonb_set value must be JSONB type [OK]
- Passing plain integers without casting
- Misunderstanding path syntax
- Assuming jsonb_set can't update nested keys
data storing user info. You want to increment the "visits" count inside "stats" by 1, but visits might be missing. Which query correctly updates data to add or increment visits?Solution
Step 1: Understand the need to increment or add visits
The query must get the current visits count, convert it to integer, handle missing key with COALESCE to 0, add 1, then convert back to JSONB.Step 2: Analyze each option
UPDATE table SET data = jsonb_set(data, '{stats,visits}', to_jsonb((COALESCE((data->'stats'->>'visits')::int, 0) + 1))); correctly uses COALESCE and to_jsonb to update visits inside stats. UPDATE table SET data = jsonb_set(data, '{stats,visits}', '1'); sets visits to string '1' always. UPDATE table SET data = data || '{"stats":{"visits":1}}'; overwrites stats with visits=1, losing other keys. UPDATE table SET data = jsonb_set(data, '{visits}', to_jsonb(1)); updates visits at top level, not inside stats.Final Answer:
UPDATE table SET data = jsonb_set(data, '{stats,visits}', to_jsonb((COALESCE((data->'stats'->>'visits')::int, 0) + 1))); -> Option CQuick Check:
Use COALESCE and to_jsonb for safe increment [OK]
- Overwriting nested objects accidentally
- Not casting string to int before increment
- Updating wrong JSONB path
Ready to prove it?
Pass the test and this pattern moves unknown
