PostgreSQL은 json 및 jsonb 데이터 타입을 통해 JSON 데이터의 저장과 쿼리를 강력하게 지원해요. 특히 jsonb 타입은 데이터를 바이너리 형식으로 저장하기 때문에, 텍스트 기반인 json 타입보다 인덱싱과 쿼리를 더 효율적으로 할 수 있어 유용해요.
이 튜토리얼에서는 PostgreSQL에서 가장 많이 쓰이는 JSON 작업을 애플리케이션에 바로 활용할 수 있는 실용적인 예제와 함께 살펴볼게요.
계속 읽기 전에 저희의 현대적이고 빠른 PostgreSQL 데이터베이스 관리 도구인 Beekeeper Studio를 소개할게요. SQL 에디터가 입력하는 대로 자동 완성해 주니 이 JSON 연산자들을 빠르게 시험해 볼 수 있고, PostgreSQL에서는 무료로 사용할 수 있어요. 여기서 다운로드하세요.
JSON 데이터 만들기
먼저 jsonb 컬럼이 있는 테이블을 만들고 샘플 데이터를 넣어 볼게요:
CREATE TABLE customers (
id SERIAL PRIMARY KEY,
info JSONB
);
-- Insert a customer with basic information
INSERT INTO customers (info) VALUES (
'{"name": "Alice Smith", "email": "alice@example.com", "age": 32, "addresses": [
{"type": "home", "city": "San Francisco", "state": "CA"},
{"type": "work", "city": "Oakland", "state": "CA"}
]}'
);
-- Insert another customer
INSERT INTO customers (info) VALUES (
'{"name": "Bob Johnson", "email": "bob@example.com", "age": 45, "addresses": [
{"type": "home", "city": "Seattle", "state": "WA"}
], "orders": [101, 102, 103]}'
);
기본 JSON 작업
JSON 문서 전체 조회하기
SELECT info FROM customers WHERE id = 1;
결과:
{
"age": 32,
"name": "Alice Smith",
"email": "alice@example.com",
"addresses": [
{"city": "San Francisco", "type": "home", "state": "CA"},
{"city": "Oakland", "type": "work", "state": "CA"}
]
}
JSON에서 값 추출하기
PostgreSQL은 JSON에서 값을 추출하는 여러 연산자를 제공해요:
-> 연산자로 특정 필드 추출하기 (JSON 반환)
-- Get the name field as JSON
SELECT info -> 'name' FROM customers;
결과:
"Alice Smith"
"Bob Johnson"
-» 연산자로 특정 필드 추출하기 (텍스트 반환)
-- Get the name field as text
SELECT info ->> 'name' AS customer_name FROM customers;
결과:
customer_name
----------------
Alice Smith
Bob Johnson
중첩 객체에 접근하기
-- Getting the first address (array element 0) city
SELECT info -> 'addresses' -> 0 ->> 'city' AS home_city FROM customers;
결과:
home_city
------------
San Francisco
Seattle
#> 연산자로 경로 접근하기
-- Using the path syntax to get the same value
SELECT info #> '{addresses,0,city}' FROM customers;
결과:
"San Francisco"
"Seattle"
#» 연산자로 텍스트 경로 접근하기
-- Using the path syntax to get the same value as text
SELECT info #>> '{addresses,0,city}' AS home_city FROM customers;
결과:
home_city
------------
San Francisco
Seattle
JSON 데이터 수정하기
PostgreSQL은 JSON 데이터를 수정하는 여러 함수를 제공해요:
jsonb_set으로 필드 추가하기
-- Add a new field 'premium_customer' to a customer
UPDATE customers
SET info = jsonb_set(info, '{premium_customer}', 'true')
WHERE id = 1;
- 연산자로 필드 제거하기
-- Remove the premium_customer field
UPDATE customers
SET info = info - 'premium_customer'
WHERE id = 1;
||로 JSON 객체 병합하기
-- Add multiple fields by merging objects
UPDATE customers
SET info = info || '{"status": "active", "last_login": "2025-03-23"}'::jsonb
WHERE id = 1;
중첩 필드 업데이트하기
-- Update a nested field (home address state)
UPDATE customers
SET info = jsonb_set(
info,
'{addresses,0,state}',
'"NY"'::jsonb
)
WHERE id = 1;
JSON 배열 쿼리하기
JSON 배열은 자주 다루게 되는 작업이에요:
배열 길이 구하기
-- Get the number of addresses for each customer
SELECT
info ->> 'name' AS customer_name,
jsonb_array_length(info -> 'addresses') AS address_count
FROM customers;
결과:
customer_name | address_count
---------------+--------------
Alice Smith | 2
Bob Johnson | 1
특정 배열 요소 추출하기
-- Get the second address (index 1) for Alice
SELECT info -> 'addresses' -> 1 FROM customers WHERE id = 1;
결과:
{"city": "Oakland", "type": "work", "state": "CA"}
배열을 펼쳐 개별 요소 쿼리하기
-- Unnest the addresses array to query individual addresses
SELECT
c.id,
c.info ->> 'name' AS customer_name,
jsonb_array_elements(c.info -> 'addresses') AS address
FROM customers c;
결과:
id | customer_name | address
---+---------------+------------------------------------------------------
1 | Alice Smith | {"city": "San Francisco", "type": "home", "state": "NY"}
1 | Alice Smith | {"city": "Oakland", "type": "work", "state": "CA"}
2 | Bob Johnson | {"city": "Seattle", "type": "home", "state": "WA"}
펼친 배열로 필터링하기
-- Find customers with addresses in CA
SELECT DISTINCT
c.id,
c.info ->> 'name' AS customer_name
FROM customers c,
jsonb_array_elements(c.info -> 'addresses') AS addr
WHERE addr ->> 'state' = 'CA';
결과:
id | customer_name
---+--------------
1 | Alice Smith
키와 값 확인하기
키 존재 여부 확인하기
-- Find customers who have the 'orders' key
SELECT id, info ->> 'name' AS customer_name
FROM customers
WHERE info ? 'orders';
결과:
id | customer_name
---+--------------
2 | Bob Johnson
배열 안의 값 확인하기
-- Find customers with a specific order number
SELECT id, info ->> 'name' AS customer_name
FROM customers
WHERE info -> 'orders' ? '101';
결과:
id | customer_name
---+--------------
2 | Bob Johnson
배열 요소 중 하나라도 일치하는지 확인하기
-- Find customers who have an address in Oakland (using path operators)
SELECT id, info ->> 'name' AS customer_name
FROM customers
WHERE info @> '{"addresses": [{"city": "Oakland"}]}';
결과:
id | customer_name
---+--------------
1 | Alice Smith
JSON 데이터 인덱싱
대용량 JSON 데이터를 다루는 프로덕션 데이터베이스에서는 적절한 인덱싱이 필수예요:
포함 쿼리를 위한 GIN 인덱스 만들기
-- Create a GIN index for faster containment operations
CREATE INDEX idx_customers_info ON customers USING GIN (info);
JSON 필드 전용 인덱스 만들기
-- Create an index on the 'email' field for fast lookups
CREATE INDEX idx_customers_email ON customers ((info ->> 'email'));
쿼리에서 인덱스된 필드 사용하기
-- This query can use the index we created above
SELECT id, info ->> 'name' AS customer_name
FROM customers
WHERE info ->> 'email' = 'alice@example.com';
JSON과 테이블 간 변환
JSON을 행으로 변환하기 (jsonb_to_record)
-- Extract JSON fields into a tabular structure
SELECT
id,
rec.name,
rec.email,
rec.age
FROM
customers,
jsonb_to_record(info) AS rec(
name text,
email text,
age int
);
결과:
id | name | email | age
---+--------------+-------------------+-----
1 | Alice Smith | alice@example.com | 32
2 | Bob Johnson | bob@example.com | 45
중첩 배열을 테이블로 변환하기 (jsonb_to_recordset)
-- Extract addresses from all customers into a table
SELECT
c.id,
c.info ->> 'name' AS customer_name,
addr.type AS address_type,
addr.city,
addr.state
FROM
customers c,
jsonb_to_recordset(c.info -> 'addresses') AS addr(
type text,
city text,
state text
);
결과:
id | customer_name | address_type | city | state
---+---------------+--------------+---------------+------
1 | Alice Smith | home | San Francisco | NY
1 | Alice Smith | work | Oakland | CA
2 | Bob Johnson | home | Seattle | WA
쿼리 결과를 JSON으로 변환하기
-- Aggregate customer orders into a JSON array
SELECT
c.id,
c.info ->> 'name' AS customer_name,
json_agg(o.order_id) AS orders
FROM
customers c
CROSS JOIN LATERAL (
SELECT jsonb_array_elements_text(c.info -> 'orders') AS order_id
) o
GROUP BY c.id, c.info ->> 'name';
결과:
id | customer_name | orders
---+---------------+----------
2 | Bob Johnson | ["101", "102", "103"]
성능 고려 사항
PostgreSQL에서 JSON을 다룰 때는 다음 성능 고려 사항을 염두에 두세요:
-
json대신jsonb사용하기: 대부분의 작업에서jsonb타입이 더 나은 성능을 보여요. -
전략적으로 인덱싱하기: 포함 쿼리에는 GIN 인덱스를 쓰고, 자주 쿼리하는 필드에는 전용 인덱스를 만드세요.
-
비정규화는 신중하게: JSON으로 데이터 모델을 비정규화할 수 있지만, 지나친 중첩은 쿼리 성능에 영향을 줄 수 있어요.
-
쿼리 패턴 살펴보기: 복잡한 JSON 경로 표현식이나 큰 배열을 자주 펼치는 작업은 비용이 클 수 있어요.
-
배열 크기 제한하기: 매우 큰 JSON 배열은 펼칠 때 성능 문제를 일으킬 수 있어요.
-
필요한 필드만 추출하기: JSON 문서 전체를 반환하지 말고 필요한 필드만 추출하세요.
결론
PostgreSQL의 JSON 기능은 반정형 데이터를 저장하고 쿼리해야 하는 애플리케이션에 훌륭한 선택이에요. 이 튜토리얼에서 다룬 연산자와 함수를 활용하면, 성숙한 관계형 데이터베이스의 강력함과 안정성을 그대로 누리면서 JSON 데이터를 효과적으로 다룰 수 있어요.
복잡한 데이터 모델이라면 하이브리드 방식을 고려해 보세요. 고정된 스키마와 자주 쿼리하는 데이터에는 정형 테이블을 쓰고, 유연한 스키마리스 데이터나 관계형으로 모델링하기 까다로운 중첩 구조에는 JSON을 쓰는 거예요.
이 예제들을 직접 실행해 보고 싶으신가요? 지금 Beekeeper Studio를 열고 PostgreSQL의 JSON 기능을 살펴보세요.
Beekeeper Studio는 무료 오픈 소스 PostgreSQL GUI예요
제가 찾던 바로 그 PostgreSQL 클라이언트예요! UI가 차별점이에요. 깔끔하고 직관적이며 강력해요. 투박한 PGAdmin은 이제 안녕. - David Cyprian
Beekeeper Studio는 빠르고 직관적이며 사용하기 쉬운 PostgreSQL 클라이언트예요. 다른 데이터베이스도 많이 지원하고, Windows, Mac, Linux에서 모두 잘 작동해요.
PostgreSQL 사용자들의 Beekeeper Studio 후기
pgAdmin과 달리 Beekeeper는 놀라울 만큼 사용하기 쉬우면서도 기능이 부족하지 않아요. 가격도 적당하고요! 특히 데이터베이스 백업 기능이 유용해요. 정말 훌륭한 소프트웨어예요.
멋진 도구예요. 지금까지 써 본 Postgres와 MySql DB 관리용 IDE 중 가장 실용적이에요. 번거로움 없이 그냥 잘 돌아가요 :-)