본문으로 건너뛰기
Skillpedia
데이터베이스41k · #6673

postgresql-table-design

하는 일

이 에이전트는 PostgreSQL 데이터베이스의 테이블 구조를 설계하고 검토하도록 돕습니다. 데이터 타입, 인덱스, 규칙에 대한 모범 사례를 제안해 데이터베이스가 잘 작동하도록 합니다.

사용하는 경우

  • ✓새 데이터베이스를 만들 때.
  • ✓열에 맞는 데이터 타입을 고를 때.
  • ✓최고의 성능을 위해 데이터를 어떻게 정리할지 결정하는 경우.

스킬 링크

https://github.com/wshobson/agents/blob/main/plugins/database-design/skills/postgresql-table-design/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/wshobson/agents/blob/main/plugins/database-design/skills/postgresql-table-design/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“고객 정보를 저장하는 테이블을 어떻게 만들면 좋을까요? 이메일이 고유하도록 해 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

필요를 분석하고, 성능과 모범 사례를 고려해 가장 좋은 열 옵션, 인덱스, PostgreSQL 전용 규칙을 제안합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

PostgreSQL Table Design

When to Use

  • Designing a new PostgreSQL schema, or reviewing one before it ships.
  • Choosing column types, keys, constraints, or indexes for PostgreSQL specifically.
  • Deciding whether and how to partition a large table, or how to store semi-structured data.
  • Planning a schema change on a live database without downtime.

The rules and decision points for a PostgreSQL schema. The full data-type catalog, workload patterns (update-heavy, insert-heavy, upsert, schema evolution), extensions, JSONB indexing, and worked DDL examples are in references/details.md; open it when a section below points there.

Core Rules

  • Define a PRIMARY KEY for reference tables (users, orders, etc.). Not always needed for time-series/event/log data. When used, prefer BIGINT GENERATED ALWAYS AS IDENTITY; use UUID only when global uniqueness/opacity is needed.
  • Normalize first (to 3NF) to eliminate data redundancy and update anomalies; denormalize only for measured, high-ROI reads where join performance is proven problematic.
  • Add NOT NULL everywhere it is semantically required; use DEFAULTs for common values.
  • Create indexes for access paths you actually query: PK/unique (auto), FK columns (manual!), frequent filters/sorts, and join keys.
  • Prefer TIMESTAMPTZ for event time; NUMERIC for money; TEXT for strings; BIGINT for integers; DOUBLE PRECISION for floats (or NUMERIC for exact decimal arithmetic).

PostgreSQL Gotchas

  • Identifiers: unquoted → lowercased. Avoid quoted/mixed-case names; use snake_case.
  • Unique + NULLs: UNIQUE allows multiple NULLs. Use UNIQUE NULLS NOT DISTINCT (...) (PG15+) to restrict to one NULL.
  • FK indexes: PostgreSQL does not auto-index FK columns. Add them.
  • No silent coercions: length/precision overflows error out (no truncation). Inserting 999 into NUMERIC(2,0) fails, unlike databases that silently truncate or round.
  • Sequences/identity have gaps (normal; don't "fix"). Rollbacks, crashes, and concurrent transactions leave gaps (1, 2, 5, 6...).
  • Heap storage: no clustered PK by default; CLUSTER is a one-off reorganization, not maintained on later inserts.
  • MVCC: updates/deletes leave dead tuples; vacuum handles them—design to avoid hot wide-row churn.

Data Types

  • IDs: BIGINT GENERATED ALWAYS AS IDENTITY; UUID for distributed or opaque IDs, generated with uuidv7() (PG18+) or gen_random_uuid().
  • Numbers: BIGINT unless storage is critical; DOUBLE PRECISION over REAL; NUMERIC(p,s) for money and exact decimals.
  • Strings: TEXT, with CHECK (LENGTH(col) <= n) when a limit is needed; BYTEA for binary. Case-insensitive lookups: expression index on LOWER(col), or CITEXT when a constraint must be case-insensitive.
  • Time: TIMESTAMPTZ, DATE, INTERVAL. now() is transaction start; clock_timestamp() is wall clock.
  • Booleans: BOOLEAN NOT NULL unless tri-state is required.
  • Enums: CREATE TYPE ... AS ENUM only for small, stable sets; evolving business values get TEXT + CHECK or a lookup table.
  • JSONB over JSON, indexed with GIN, for optional/semi-structured attributes only.
  • Arrays, ranges, network, geometric, full-text, domain, composite, and vector types, plus TOAST storage and collation control: see references/details.md.

Types to avoid

Avoid Use instead
timestamp (without time zone) timestamptz
char(n), varchar(n) text (+ CHECK on length if needed)
money numeric
timetz timestamptz
timestamptz(0) or any precision timestamptz
serial generated always as identity

Constraints

  • PK: implicit UNIQUE + NOT NULL; creates a B-tree index.
  • FK: specify ON DELETE/UPDATE (CASCADE, RESTRICT, SET NULL, SET DEFAULT). Index the referencing column. Use DEFERRABLE INITIALLY DEFERRED for circular dependencies checked at commit.
  • UNIQUE: creates a B-tree index; allows multiple NULLs unless NULLS NOT DISTINCT (PG15+). Prefer NULLS NOT DISTINCT unless duplicate NULLs are wanted.
  • CHECK: row-local; NULL passes (three-valued logic). Combine with NOT NULL: price NUMERIC NOT NULL CHECK (price > 0).
  • EXCLUDE: prevents overlaps with operators, e.g. EXCLUDE USING gist (room_id WITH =, booking_period WITH &&) stops double-booking. Needs a GiST-capable type.

Indexing

…

자주 묻는 질문

'varchar(n)'을 쓰면 안 되는 이유는 무엇인가요?

PostgreSQL에서는 일반적으로 'text'가 선호됩니다. 크기 제한이 없고 성능도 비슷하기 때문입니다. 길이를 제한해야 하면 CHECK 제약 조건을 추가할 수 있습니다.

PostgreSQL은 외래 키에 인덱스를 자동으로 만드나요?

아니요. PostgreSQL은 외래 키 열에 인덱스를 자동으로 만들지 않습니다. 좋은 조회 성능을 위해서는 직접 추가해야 합니다.

PostgreSQL의 '함정(gotchas)'은 무엇인가요?

PostgreSQL에서 모르면 문제가 될 수 있는 특이한 동작입니다. 예를 들어 식별자가 처리되는 방식이나 외래 키에 인덱스가 자동으로 생기지 않는 점 등이 있습니다.

상세 정보

작성자의 원본 설명

Use this skill when designing or reviewing a PostgreSQL-specific schema. Covers best-practices, data types, indexing, constraints, performance patterns, and advanced features

repo: wshobson/agents

인기도

GitHub 스타
41k
순위
#6673
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬