Explain Codes LogoExplain Codes Logo

Postgresql: Remove attribute from JSON column

sql
json-manipulation
postgresql-features
database-performance
Nikita BarsukovbyNikita BarsukovΒ·Nov 12, 2024
⚑TLDR

Need to drop an attribute from a jsonb column in PostgreSQL faster than a hot potato? Use the - operator. If your table, my_table, has a json_data column, and you want to nix 'unwanted_key', run:

-- Darn that unwanted_key, I've had just about enough of it! 😀 UPDATE my_table SET json_data = json_data - 'unwanted_key' WHERE json_data ? 'unwanted_key';

This updates json_data across the board by eliminating 'unwanted_key' from every nook and cranny where it's found.

Handle concurrent updates efficiently

Concurrent environments can get a tad messy. When planning updates in such settings, ensure you consider transaction isolation levels and prevent locking problems.

At times, removing one key may coincide with adding or updating another. In such cases, the || operator can be your hero. Here's how to overwrite key-values in one fell swoop:

-- Remove existing key, add new one. It's like killing two birds with one stone...but less violent! UPDATE my_table SET json_data = (json_data - 'unwanted_key') || '{"new_key": "new_value"}'::jsonb WHERE json_data ? 'unwanted_key';

Dance with both JSON and JSONB types

When you are stuck with the json data type, cast it to jsonb so you can use all the cool JSONB manipulation tricks PostgreSQL offers:

-- It's like adding an accessory to an old dress... makes it brand new! UPDATE my_table SET json_data = json_data::jsonb - 'unwanted_key' WHERE json_data::jsonb ? 'unwanted_key';

Before you start jumping in joy, check your PostgreSQL's version. You need version 9.4 or later to make use of these stellar JSONB features.

Deeply nested JSON often resembles a rabbit hole. Don't panic! The #- operator helps you strip elements from nested keys:

-- Like diving deep into the sea and finding a pearl! 🌊 UPDATE my_table SET json_data = json_data #- '{nested,unwanted_key}'::text[] WHERE json_data @> '{"nested":{"unwanted_key":"value"}}'::jsonb;

Safety first: Testing and more testing

Avoid turning your database into a disaster movie set. Before applying bulk updates, test them on a small dataset, or even a clone of your database. Data backup is your safety net.

For those intricate JSON manipulations that keep coming back for more, create PL/pgSQL functions for standardization and better maintainability.

Demystifying JSON operators

- Operator:

  • Removes a key-value pair from a JSONB object.
  • Finds use in deleting elements from a JSONB array, if you specify an index.

|| Operator:

  • Joins two JSONB objects in harmony.
  • Comes to your aid when adding or updating multiple key-values in one action.

#- Operator:

  • Excavates and eradicates a nested element by following a path.
  • It's your ace in the hole for manipulating complex JSON structures.

Pointers for a smooth operation

  • Immutable column errors: Ensure your JSON column is mutable.
  • nulls and empty objects: Don't let these sneaky ninjas throw your operation off-course. Handle nulls with care.
  • Performance implications: On larger datasets, JSON operators could be resource-greedy. Plan accordingly.
  • Correct data type casting: Always switch party gears from json to jsonb.