PostgreSql에서는 컬럼 타입을 json 타입으로 지정하여 사용할 수 있다.
json, json[], jsonb, jsonb[] 4가지 타입이 있다.
저장 이후 조회가 많지 않다면 json 타입으로 저장
저장 이후 조회가 많다면 jsonb 타입으로 저장
-> 와 ->> 연산자를 사용하여 조회 가능
create table test_table
(
id serial primary key,
jsonb_col jsonb
)
;
insert into test_table (jsonb_col) values ('{"age": "21", "name": "홍길동", "weapon": ["몽둥이", "칼"]}');
insert into test_table (jsonb_col) values ('{"age": "22", "name": "홍길금", "weapon": ["권총", "장총"]}');
insert into test_table (jsonb_col) values ('{"age": "15", "name": "홍길은", "weapon": ["새총"], "hasItem": "True"}');
-- hasItem 필드가 있는 데이터만 조회
select *
from test_table
where jsonb_col -> 'hasItem' is not null;
-- 해당 필드의 값을 뽑아낼 때
select jsonb_col -> 'hasItem'as hasItem
from test_table
where jsonb_col -> 'hasItem' is not null;
-> 연산자로 조회한 값은 타입이 jsonb 타입이다
-- hasItem 필드가 있는 데이터만 조회
select *
from test_table
where jsonb_col ->> 'hasItem' is not null;
-- 해당 필드의 값을 뽑아낼 때
select jsonb_col ->> 'hasItem'as hasItem
from test_table
where jsonb_col ->> 'hasItem' is not null;
->> 연산자로 조회한 값은 타입이 text 타입이다
-- weapon 필드가 있고 그 필드의 첫 번째 값이 권총인 데이터 조회
select *
from test_table
where jsonb_col -> 'weapon' ->> 0 = '권총';
-- weapon 필드의 값을 jsonb 로 꺼냈기 때문에 조회할 수 없다
select *
from test_table
where jsonb_col -> 'weapon' -> 0 = '권총'