0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【PostgreSQL】json型の値でプロパティを追加や削除する

Posted at

概要

PostgreSQLのテーブルにてjson型の列の値へ、プロパティ追加や削除の操作をする際のメモ書きです。

対応方針

  • プロパティの追加や更新を行う方法はPostgresql update json data propertyのstackoverflowの記事でいくつか紹介されています。PostgreSQLのバージョン9.5以上であれば、||演算子を使う方法がわかりやすい気がします。
  • プロパティの削除を行う方法はPostgreSQL: Remove attribute from JSON columnのstackoverflowの記事でいくつか紹介されています。PostgreSQLのバージョン9.5以上であれば、-演算子を使う方法がわかりやすい気がします。

実装サンプル

テスト用に以下のテーブルを用意します。今回はjsonの列はjson型にしていますが、jsonb型でも構いません。

CREATE TABLE public.sample_table (
	id int8 NOT NULL,
	json_value json NOT null,
	CONSTRAINT samle_table_pk PRIMARY KEY (id)
);

追加や更新を行う際は以下のようなSQLで実現できます、該当行の値にproperty2のプロパティを追加もしくは更新する操作となります。なお、テーブルの列がjsonb型の場合はjsonbへのキャストは不要です。

update sample_table set json_value = json_value::jsonb || '{"property2":"value2"}' where id=1

削除を行う際は以下のようなSQLで実現できます、該当行からproperty2のプロパティを削除する操作となります。なお、テーブルの列がjsonb型の場合はjsonbへのキャストは不要です。

update sample_table set json_value = json_value::jsonb - 'property2' where id=1
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?