Community코딩 & 개발github.com

PostgreSQL 테이블 설계

PostgreSQL 전용 스키마를 설계하거나 리뷰할 때 사용합니다. 모범 사례, 데이터 타입, 인덱싱, 제약 조건, 성능 패턴 및 고급 기능을 다룹니다.

PostgreSQL 테이블 설계란 무엇인가요?

이 스킬은 PostgreSQL 스키마를 설계하거나 기존 스키마를 리뷰할 때 따라야 할 모범 사례와 의사 결정 규칙을 제공합니다. 기본 키 선택(BIGINT IDENTITY vs UUID), 정규화(3NF까지) 후 필요한 경우만 역정규화, 모든 열에 적절한 NOT NULL 및 DEFAULT 사용, 실제 쿼리 패턴에 맞는 인덱스 생성(B-tree, GIN, GiST, BRIN 등) 등 핵심 규칙을 포함합니다. 또한 PostgreSQL 고유의 주의사항(식별자 소문자화, UNIQUE와 NULL 처리, FK 인덱스 자동 생성 안 함, 데이터 변환 오류, 시퀀스 갭, 힙 저장 방식, MVCC)을 설명하며, 데이터 타입별 권장 사항(TIMESTAMPTZ, NUMERIC, TEXT, BIGINT, JSONB 등), 제약 조건(PK, FK, UNIQUE, CHECK, EXCLUDE), 인덱싱 전략(복합, 커버링, 부분, 표현식 인덱스), 그리고 파티셔닝(RANGE, LIST, HASH)에 대한 구체적인 지침을 제공합니다. 실제 DDL 예제와 함께 references/details.md 파일로 더 자세한 내용을 연결합니다. 여러 플랫폼(Claude Code, Cursor 등)에서 사용할 수 있습니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/mianhtsys/landingMod3/tree/HEAD/MODULO_3_DESARROLLO_AL_LADO_DEL_CLIENTE_Y_SERVIDOR_WEB/architecture-skills-framework/.agents/skills/postgresql-table-design

Installed? Explore more 코딩 & 개발 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

PostgreSQL 테이블 설계은(는) 무엇을 하나요?

사용 시기

  • 새로운 PostgreSQL 스키마를 설계하거나, 배포 전에 기존 스키마를 리뷰할 때.
  • PostgreSQL에 특화된 컬럼 타입, 키, 제약 조건, 또는 인덱스를 선택할 때.
  • 대형 테이블을 파티셔닝할지 여부와 방법, 또는 반정형 데이터를 저장할 방법을 결정할 때.
  • 다운타임 없이 운영 중인 데이터베이스의 스키마 변경을 계획할 때.

PostgreSQL 스키마에 대한 규칙과 의사 결정 지점입니다. 전체 데이터 타입 카탈로그, 워크로드 패턴(업데이트 위주, 삽입 위주, 업서트, 스키마 진화), 확장 기능, JSONB 인덱싱, 및 실제 DDL 예제는 references/details.md에 있습니다; 아래 섹션에서 해당 파일을 가리키면 열어보세요.

핵심 규칙

  • 참조 테이블(사용자, 주문 등)에는 PRIMARY KEY를 정의하세요. 시계열/이벤트/로그 데이터에는 항상 필요하지 않습니다. 사용할 경우 BIGINT GENERATED ALWAYS AS IDENTITY를 선호하고, 전역 고유성/불투명성이 필요한 경우에만 UUID를 사용하세요.
  • 데이터 중복과 업데이트 이상을 없애기 위해 먼저 정규화(3NF까지) 하세요; 측정된, ROI가 높은 읽기에서 조인 성능이 문제가 된다고 입증된 경우에만 역정규화하세요.
  • 의미상 필요한 모든 곳에 NOT NULL을 추가하고, 공통 값에는 DEFAULT를 사용하세요.
  • 실제로 쿼리하는 액세스 경로에 대한 인덱스를 생성하세요: PK/유니크(자동), FK 컬럼(수동!), 자주 필터/정렬하는 컬럼, 조인 키.
  • 이벤트 시간에는 TIMESTAMPTZ, 금액에는 NUMERIC, 문자열에는 TEXT, 정수에는 BIGINT, 부동 소수점에는 DOUBLE PRECISION(또는 정확한 십진 연산을 위해 NUMERIC)을 선호하세요.

PostgreSQL 주의사항

  • 식별자: 따옴표 없음 → 소문자로 변환. 따옴표/대소문자 혼용 이름은 피하고 snake_case를 사용하세요.
  • 유니크 + NULL: UNIQUE는 여러 NULL을 허용합니다. 하나의 NULL로 제한하려면 UNIQUE NULLS NOT DISTINCT (...)(PG15+)를 사용하세요.
  • FK 인덱스: PostgreSQL은 FK 컬럼을 자동으로 인덱싱하지 않습니다. 추가하세요.
  • 묵시적 변환 없음: 길이/정밀도 오버플로는 오류를 발생시킵니다(자르기 없음). NUMERIC(2,0)에 999를 삽입하면 실패합니다. 다른 데이터베이스가 자동으로 자르거나 반올림하는 것과 다릅니다.
  • 시퀀스/아이덴티티는 갭이 있습니다(정상입니다; "고치지" 마세요). 롤백, 크래시, 동시 트랜잭션으로 인해 갭이 발생합니다(1, 2, 5, 6...).
  • 힙 저장 방식: 기본적으로 클러스터된 PK가 없습니다. CLUSTER는 일회성 재구성일 뿐 이후 삽입 시 유지되지 않습니다.
  • MVCC: 업데이트/삭제는 데드 튜플을 남깁니다; vacuum이 처리하므로—핫 와이드 로우 변동을 피하도록 설계하세요.

데이터 타입

  • ID: BIGINT GENERATED ALWAYS AS IDENTITY; 분산 또는 불투명 ID에는 UUID, uuidv7()(PG18+) 또는 gen_random_uuid()로 생성.
  • 숫자: 저장 공간이 중요하지 않으면 BIGINT; REAL보다 DOUBLE PRECISION; 금액과 정확한 십진수에는 NUMERIC(p,s).
  • 문자열: TEXT, 제한이 필요할 때 CHECK (LENGTH(col) <= n)와 함께; 바이너리에는 BYTEA. 대소문자 구분 없는 조회: LOWER(col)에 표현식 인덱스, 또는 제약 조건이 대소문자 구분이 없어야 할 때 CITEXT.
  • 시간: TIMESTAMPTZ, DATE, INTERVAL. now()는 트랜잭션 시작 시각이고, clock_timestamp()는 실제 시각입니다.
  • 불리언: 삼상태가 필요하지 않으면 BOOLEAN NOT NULL.
  • Enum: 작고 안정적인 집합에만 CREATE TYPE ... AS ENUM; 진화하는 비즈니스 값은 TEXT + CHECK 또는 조회 테이블을 사용하세요.
  • JSONB: 선택적/반정형 속성에만 JSON보다 JSONB를 사용하고 GIN으로 인덱싱하세요.
  • 배열, 범위, 네트워크, 기하, 전문 검색, 도메인, 복합, 벡터 타입, TOAST 저장소 및 데이터 정렬 제어: references/details.md 참조.

피해야 할 타입

피할 타입대신 사용할 타입
timestamp (시간대 없음)timestamptz
char(n), varchar(n)text (+ 필요시 CHECK로 길이 제한)
moneynumeric
timetztimestamptz
timestamptz(0) 또는 정밀도 지정timestamptz
serialgenerated always as identity

제약 조건

  • PK: 묵시적 UNIQUE + NOT NULL; B-tree 인덱스를 생성합니다.
  • FK: ON DELETE/UPDATE(CASCADE, RESTRICT, SET NULL, SET DEFAULT)를 지정하세요. 참조하는 컬럼에 인덱스를 생성하세요. 커밋 시점에 검사되는 순환 종속성을 위해 DEFERRABLE INITIALLY DEFERRED를 사용하세요.
  • UNIQUE: B-tree 인덱스를 생성합니다; NULLS NOT DISTINCT(PG15+)가 아니면 여러 NULL을 허용합니다. 중복 NULL이 필요하지 않으면 NULLS NOT DISTINCT를 선호하세요.
  • CHECK: 로우 수준; NULL은 통과합니다(삼값 논리). NOT NULL과 결합: price NUMERIC NOT NULL CHECK (price > 0).
  • EXCLUDE: 연산자를 사용하여 겹침을 방지합니다, 예: EXCLUDE USING gist (room_id WITH =, booking_period WITH &&)는 이중 예약을 막습니다. GiST 지원 타입이 필요합니다.

인덱싱

  • B-tree: 동등성/범위(=, <, >, BETWEEN, ORDER BY)의 기본.
  • 복합: 최좌측 접두사 규칙(WHERE a = ? AND b > ?는 (a,b) 사용; WHERE b = ?는 사용하지 못함). 선택도가 가장 높은 컬럼을 먼저.
  • 커버링: 인덱스 전용 스캔을 위해 CREATE INDEX ON tbl (id) INCLUDE (name, email).
  • 부분: 핫 서브셋, CREATE INDEX ON tbl (user_id) WHERE status = 'active'.
  • 표현식: CREATE INDEX ON tbl (LOWER(email)); 쿼리는 동일한 표현식을 사용해야 합니다.
  • GIN: JSONB 포함/존재, 배열, 전문 검색. GiST: 범위, 기하, 제외 제약 조건.
  • BRIN: 대규모, 자연스럽게 정렬된 데이터(시계열)를 최소 저장 비용으로 처리; 디스크 순서가 인덱싱된 컬럼과 상관 관계가 있을 때 효과적입니다.

파티셔닝

  • 파티션 키로 일관되게 필터링하는 대형 테이블(>1억 행)이나 유지 관리(정리, 대량 교체)가 키를 따르는 경우 사용하세요.
  • RANGE는 시계열(PARTITION BY RANGE (created_at); TimescaleDB는 보존 및 압축으로 자동화), LIST는 이산 값, HASH는 자연스러운 키 없이 균등 분포.
  • 제약 조건 배제: 옵티마이저가 CHECK 제약 조건을 통해 파티션을 가지치기합니다; 선언적 파티셔닝(PG10+)이 자동으로 생성합니다.
  • 선언적 파티셔닝 또는 하이퍼테이블을 선호하세요. 테이블 상속을 사용하지 마세요.
  • 제한 사항: 전역 UNIQUE 제약 조건 없음—PK/UNIQUE에 파티션 키를 포함하세요. 파티션된 테이블의 FK는 PG11+ 필요, 파티션된 테이블을 참조하는 FK는 PG12+ 필요; 이전 버전에서는 트리거를 사용하세요.

예제

CREATE TABLE users (
  user_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  name TEXT NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX ON users (LOWER(email));
CREATE INDEX ON users (created_at);
CREATE TABLE orders (
  order_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  user_id BIGINT NOT NULL REFERENCES users(user_id),
  status TEXT NOT NULL DEFAULT 'PENDING' CHECK (status IN ('PENDING','PAID','CANCELED')),
  total NUMERIC(10,2) NOT NULL CHECK (total > 0),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX ON orders (user_id);
CREATE INDEX ON orders (created_at);
-- 생성된 인덱싱 가능한 스칼라를 가진 JSONB 속성
CREATE TABLE profiles (
  user_id BIGINT PRIMARY KEY REFERENCES users(user_id),
  attrs JSONB NOT NULL DEFAULT '{}',
  theme TEXT GENERATED ALWAYS AS (attrs->>'theme') STORED
);
CREATE INDEX profiles_attrs_gin ON profiles USING GIN (attrs);

더 깊이 알아보기

references/details.md에는 이 파일에서 이름만 언급한 내용이 담겨 있습니다:

  • 전체 데이터 타입 카탈로그: TOAST 저장소, 데이터 정렬, 배열, 범위, 네트워크, 기하, 텍스트 검색, 도메인, 복합, 벡터.
  • 테이블 유형(TEMPORARY, UNLOGGED) 및 로우 레벨 보안.
  • 제약 조건 및 인덱스 참고 사항, RANGE, LIST, HASH 파티셔닝 DDL.
  • 워크로드 패턴: 업데이트 위주, 삽입 위주, 업서트 설계, 안전한 스키마 진화.
  • 생성 컬럼 및 확장 기능(pg_trgm, citext, timescaledb, postgis, pgvector 등).
  • jsonb_path_ops 및 추출된 B-tree 컬럼을 포함한 JSONB 인덱싱 전략.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

mianhtsys/landingMod3

Implement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.

mianhtsys/landingMod3

Master REST and GraphQL API design principles to build intuitive, scalable, and maintainable APIs that delight developers. Use when designing new APIs, reviewing API specifications, or establishing API design standards.

mianhtsys/landingMod3

Diseña y compara alternativas arquitectónicas trazables a RF/RNF sin implementar código.

mianhtsys/landingMod3

Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use this skill when designing clean architecture for a new microservice, when refactoring a monolith to use bounded contexts, when implementing hexagonal or onion architecture patterns, or when debugging dependency cycles between application layers.

mianhtsys/landingMod3

Revisión adversarial de la arquitectura contra RF/RNF, detectando contradicciones, cobertura faltante y complejidad innecesaria.

mianhtsys/landingMod3

Master authentication and authorization patterns including JWT, OAuth2, session management, and RBAC to build secure, scalable access control systems. Use when implementing auth systems, securing APIs, or debugging security issues.

mianhtsys/landingMod3

>- Generate grounded-and-verified, engine-agnostic database documentation that reaches 100% parity with the real schema. Introspects the LIVE database as ground truth and cross-validates it against ORM models, migrations, generated types, seeds, and application queries, then proves completeness by diffing the docs back against the database. Produces ER diagrams (mermaid), per-table data dictionaries, and a machine-readable schema.json. Works with PostgreSQL, MySQL, SQL Server, and SQLite across any ORM (Prisma, TypeORM, Drizzle, Sequelize, Knex, Django, Rails) or raw SQL. Use when asked to document a database, produce an ERD or data dictionary, write db/schema docs, audit schema drift, or refresh existing DB docs.

mianhtsys/landingMod3

Compara estrategias de persistencia y motores de datos según consistencia, concurrencia, volumen, recuperación y operación.

mianhtsys/landingMod3

Design robust, scalable database schemas for SQL and NoSQL databases. Provides normalization guidelines, indexing strategies, migration patterns, constraint design, and performance optimization. Ensures data integrity, query performance, and maintainable data models.

mianhtsys/landingMod3

Consolida análisis especializados en una recomendación arquitectónica, matriz de decisión, ADR y plan de validación.

mianhtsys/landingMod3

Master error handling patterns across languages including exceptions, Result types, error propagation, and graceful degradation to build resilient applications. Use when implementing error handling, designing APIs, or improving application reliability.

mianhtsys/landingMod3

Build and maintain web frontends — component architecture, state management, API integration, responsive layout, client-side performance, and frontend testing patterns. Framework agnostic, focused on web frontend implementation. Do not use for backend service implementation, data engineering, or platform infrastructure work.

mianhtsys/landingMod3

Evalúa despliegue, contenedores, escalado, alta disponibilidad, observabilidad, backup, recuperación y CI/CD de forma proporcional.

mianhtsys/landingMod3

Execute read-only SQL queries against multiple Microsoft SQL Server databases. Use when: (1) querying MSSQL/SQL Server databases, (2) exploring database schemas/tables, (3) running SELECT queries for data analysis, (4) checking database contents. Supports multiple database connections with descriptions for intelligent auto-selection. Blocks all write operations (INSERT, UPDATE, DELETE, DROP, etc.) for safety.

mianhtsys/landingMod3

Generate and maintain OpenAPI 3.1 specifications from code, design-first specs, and validation patterns. Use when creating API documentation, generating SDKs, or ensuring API contract compliance.

mianhtsys/landingMod3

PHP 8.0+ development — XAMPP, RESTful APIs, PDO/MySQL/MariaDB, and authentication. Use when building PHP backends, creating API endpoints, configuring XAMPP, or integrating PHP with databases.

mianhtsys/landingMod3

Analiza requisitos funcionales y no funcionales, reglas, restricciones, capacidad y ambigüedades antes de seleccionar tecnologías.

mianhtsys/landingMod3

Implement modern responsive layouts using container queries, fluid typography, CSS Grid, and mobile-first breakpoint strategies. Use when building adaptive interfaces, implementing fluid layouts, or creating component-level responsive behavior.

mianhtsys/landingMod3

>- Use when designing or implementing software securely: define security requirements, threat-model a feature, choose secure defaults, design authentication and authorization, handle untrusted data and secrets, evaluate dependencies, design multi-tenant trust boundaries, or review security-sensitive changes. Use for prevention during requirements, design, implementation, and review; not for post-build security assessments or scanning an existing codebase.

mianhtsys/landingMod3

Revisa seguridad arquitectónica, identidad, autorización, secretos, APIs, auditoría, fraude y resiliencia antes de implementar.

관련 스킬