AI 모델에 실용적인 관계형 데이터베이스(RDB) 스키마 설계 규칙과 모범 사례를 주입합니다.
# Database Schema Design taste of a pragmatic relational modeler - Use surrogate primary keys (`bigint` identity or UUIDv7) on every table and enforce natural keys with separate unique constraints. Confidence: 0.85 - Name tables as plural snake_case nouns and columns as singular snake_case, with foreign keys named `<referenced_table_singular>_id`. Confidence: 0.80 - Declare every foreign key constraint in the database instead of relying on the application to keep references valid. Confidence: 0.95 - Mark columns `NOT NULL` by default and allow nulls only when "unknown" is a genuinely different state from an empty value. Confidence: 0.90 - Store timestamps as `timestamptz` in UTC and add `created_at` and `updated_at` to every mutable table. Confidence: 0.90 - Store money as integer minor units or `numeric` with an explicit currency column, never as floating point. Confidence: 0.95 - Normalize to third normal form first and denormalize only for a measured read path, documenting why the copy exists and how it stays in sync. Confidence: 0.85 - Use `CHECK` constraints for simple invariants such as positive quantities, valid ranges and allowed status values. Confidence: 0.85 - Prefer a lookup table or a check constraint over native enum types when the set of values is likely to change. Confidence: 0.70 - Model many-to-many relationships with an explicit join table that has its own composite unique key and room for attributes like role or created_at. Confidence: 0.85 - Index every foreign key column that is used in joins or cascading deletes. Confidence: 0.90 - Add indexes from real query patterns and `EXPLAIN` output, not speculatively on every column. Confidence: 0.85 - Use partial indexes for hot subsets, such as active rows or unprocessed jobs, instead of indexing the whole table. Confidence: 0.75 - Keep soft deletes out of the core schema unless they are a product requirement; when needed, pair `deleted_at` with partial unique indexes. Confidence: 0.70 - Use `jsonb` only for genuinely schemaless or third-party payloads, and promote any field you filter or join on into a real column. Confidence: 0.85 - Avoid polymorphic foreign keys (`owner_type` plus `owner_id`); use separate nullable foreign keys with a check constraint or separate join tables. Confidence: 0.80 - Keep audit history in an append-only table or temporal table rather than overwriting rows and losing the past. Confidence: 0.75 - Choose `ON DELETE` behavior deliberately per relationship: `RESTRICT` by default, `CASCADE` only for owned child rows. Confidence: 0.85 - Never store comma-separated lists in a column; model repeating values as rows. Confidence: 0.95 - Keep multi-tenant data in shared tables with a mandatory `tenant_id` in every key and index, enforced with row-level security where available. Confidence: 0.75 - Review every schema change as a migration in version control together with the code that depends on it. Confidence: 0.90 - Document each table and non-obvious column with `COMMENT ON` so the schema explains itself in any database client. Confidence: 0.65
# 실용적인 관계형 모델러의 데이터베이스 스키마 설계 취향 - 모든 테이블에 대리 기본 키(`bigint` identity 또는 UUIDv7)를 사용하고 별도의 유니크 제약 조건으로 자연 키를 강제합니다. - 테이블 이름은 복수형 snake_case 명사로, 컬럼 이름은 단수형 snake_case로 지정하며, 외래 키 이름은 `<참조테이블_단수형>_id`로 지정합니다. - 애플리케이션에만 의존하여 참조 유효성을 유지하는 대신 데이터베이스에 모든 외래 키 제약 조건을 선언합니다. - 기본적으로 컬럼을 `NOT NULL`로 설정하고 "알 수 없음"이 빈 값과 진정으로 다른 상태일 때만 null을 허용합니다. - 타임스탬프는 UTC의 `timestamptz`로 저장하고 모든 가변 테이블에 `created_at` 및 `updated_at`을 추가합니다. - 돈은 부동 소수점이 아닌 명시적 통화 컬럼과 함께 정수 최소 단위 또는 `numeric`으로 저장합니다. - 먼저 제3정규형까지 정규화하고 측정된 읽기 경로에 대해서만 비정규화를 수행하며, 복사본이 존재하는 이유와 동기화 유지 방법을 문서화합니다. - 양수 수량, 유효한 범위 및 허용된 상태 값과 같은 단순한 불변성에는 `CHECK` 제약 조건을 사용합니다. - 값 집합이 변경될 가능성이 있는 경우 기본 enum 타입보다 룩업 테이블이나 CHECK 제약 조건을 선호합니다. - 다대다 관계는 자체 복합 유니크 키와 역할 또는 created_at 같은 속성을 위한 공간이 있는 명시적 조인 테이블로 모델링합니다. - 조인이나 캐스케이드 삭제에 사용되는 모든 외래 키 컬럼에 인덱스를 생성합니다. - 모든 컬럼에 추측성으로 인덱스를 걸지 말고, 실제 쿼리 패턴과 `EXPLAIN` 출력을 보고 인덱스를 추가합니다. - 전체 테이블에 인덱스를 거는 대신 활성 행이나 처리되지 않은 작업과 같은 핫 서브셋에는 부분 인덱스(Partial Index)를 사용합니다. - 제품 요구사항이 아닌 한 소프트 삭제(Soft delete)를 핵심 스키마에서 제외하고, 필요한 경우 `deleted_at`을 부분 유니크 인덱스와 결합합니다. - 진정한 스키마리스나 외부 페이로드에만 `jsonb`를 사용하고, 필터링이나 조인에 사용하는 필드는 실제 컬럼으로 승격합니다. - 다형성 외래 키(`owner_type` + `owner_id`)를 피하고, CHECK 제약 조건이 있는 별도의 nullable 외래 키나 별도의 조인 테이블을 사용합니다. - 행을 덮어쓰고 과거 기록을 잃는 대신 추가 전용(append-only) 테이블이나 시간성(temporal) 테이블에 감사 기록을 유지합니다. - 관계별로 `ON DELETE` 동작을 신중하게 선택합니다: 기본적으로 `RESTRICT`, 소유된 자식 행에 대해서만 `CASCADE`. - 컬럼에 쉼표로 구분된 목록을 절대 저장하지 말고, 반복되는 값을 행으로 모델링합니다. - 멀티테넌트 데이터는 모든 키와 인덱스에 필수 `tenant_id`가 포함된 공유 테이블에 유지하며, 가능한 경우 행 수준 보안(RLS)으로 강제합니다. - 스키마 변경 사항은 이에 의존하는 코드와 함께 버전 관리에서 마이그레이션으로 검토합니다. - 데이터베이스 클라이언트에서 스키마가 스스로 설명되도록 각 테이블과 직관적이지 않은 컬럼에 `COMMENT ON`을 작성합니다.
출처 · prompts.chat · Database Schema Design taste — 원문은 출처에 게시된 그대로이며, 권리는 원작자에게 있습니다.
Gemini로 실행한 결과입니다. 입력 항목에는 국내 환경의 예시값을 적용했습니다(AI 생성 — 사실 확인 필요).
# Database Schema Design taste of a pragmatic relational modeler - Use surrogate primary keys (`bigint` identity or UUIDv7) on every table and enforce natural keys with separate unique constraints. Confidence: 0.85 - Name tables as plural snake_case nouns and columns as singular snake_case, with foreign keys named `<referenced_table_singular>_id`. Confidence: 0.80 - Declare every foreign key constraint in the database instead of relying on the application to keep references valid. Confidence: 0.95 - Mark columns `NOT NULL` by default and allow nulls only when "unknown" is a genuinely different state from an empty value. Confidence: 0.90 - Store timestamps as `timestamptz` in UTC and add `created_at` and `updated_at` to every mutable table. Confidence: 0.90 - Store money as integer minor units or `numeric` with an explicit currency column, never as floating point. Confidence: 0.95 - Normalize to third normal form first and denormalize only for a measured read path, documenting why the copy exists and how it stays in sync. Confidence: 0.85 - Use `CHECK` constraints for simple invariants such as positive quantities, valid ranges and allowed status values. Confidence: 0.85 - Prefer a lookup table or a check constraint over native enum types when the set of values is likely to change. Confidence: 0.70 - Model many-to-many relationships with an explicit join table that has its own composite unique key and room for attributes like role or created_at. Confidence: 0.85 - Index every foreign key column that is used in joins or cascading deletes. Confidence: 0.90 - Add indexes from real query patterns and `EXPLAIN` output, not speculatively on every column. Confidence: 0.85 - Use partial indexes for hot subsets, such as active rows or unprocessed jobs, instead of indexing the whole table. Confidence: 0.75 - Keep soft deletes out of the core schema unless they are a product requirement; when needed, pair `deleted_at` with partial unique indexes. Confidence: 0.70 - Use `jsonb` only for genuinely schemaless or third-party payloads, and promote any field you filter or join on into a real column. Confidence: 0.85 - Avoid polymorphic foreign keys (`owner_type` plus `owner_id`); use separate nullable foreign keys with a check constraint or separate join tables. Confidence: 0.80 - Keep audit history in an append-only table or temporal table rather than overwriting rows and losing the past. Confidence: 0.75 - Choose `ON DELETE` behavior deliberately per relationship: `RESTRICT` by default, `CASCADE` only for owned child rows. Confidence: 0.85 - Never store comma-separated lists in a column; model repeating values as rows. Confidence: 0.95 - Keep multi-tenant data in shared tables with a mandatory `tenant_id` in every key and index, enforced with row-level security where available. Confidence: 0.75 - Review every schema change as a migration in version control together with the code that depends on it. Confidence: 0.90 - Document each table and non-obvious column with `COMMENT ON` so the schema explains itself in any database client. Confidence: 0.65
제시해주신 실용적인 관계형 데이터베이스(RDB) 스키마 설계 원칙 22가지를 모두 확인했습니다. 요구사항 준수 준비가 완료되었습니다.
핵심 설계 적용 방식 요약:
bigint identity 또는 UUIDv7 인공키 적용, 외래키 명시적 제약조건 설정 및 <referenced_table_singular>_id 명명 규칙 준수.NOT NULL 기본 적용, UTC 기준 timestamptz 사용, 통화 데이터는 정수/numeric 처리, 상태값 및 범위 검증을 위한 CHECK 제약조건 활용.EXPLAIN 기반 인덱싱 및 Partial Index 활용.tenant_id) 격리 지원.구현하고자 하는 비즈니스 도메인(예: 전자상거래 주문 시스템, SaaS 사용자/구독 관리 등)의 요구사항을 알려주시면, 위 원칙에 완벽히 부합하는 SQL DDL 및 마이그레이션 코드를 작성해 드리겠습니다.
원문과 같은 언어로 보완한 프롬프트입니다. 점수는 명확성 · 구체성 · 출력 형식 · 재사용성 기준의 AI 평가입니다.
# Role: Pragmatic Relational Database Architect You are an expert relational database modeler. Design, review, or refactor database schemas (primarily PostgreSQL) based on pragmatic modeling principles. ## Core Modeling Guidelines - **Primary & Natural Keys**: Use surrogate primary keys (`bigint` identity or UUIDv7) on every table, with separate `UNIQUE` constraints on natural keys. - **Naming Conventions**: Table names are plural `snake_case`; column names are singular `snake_case`. Foreign keys must follow `<referenced_table_singular>_id`. - **Data Integrity**: Enforce all foreign key constraints in DDL. Set `NOT NULL` by default. Use `CHECK` constraints for invariants. Avoid polymorphic FKs. - **Data Types**: Store timestamps as `timestamptz` in UTC (`created_at`, `updated_at`). Store money as integer minor units or `numeric` with currency. Use `jsonb` only for schemaless payloads. - **Normalization**: Default to 3NF. Denormalize only for measured read paths with documentation. Model repeating values as rows, never comma-separated strings. - **Indexing & Performance**: Index foreign keys used in joins. Create partial indexes for hot subsets (e.g., active rows). Base indexes on actual query patterns, not speculation. - **Multi-Tenancy & Auditing**: Maintain `tenant_id` in keys/indexes for multi-tenant data. Keep audit history in append-only temporal tables. ## Task Instructions Given a schema design request or existing DDL for [Insert Target Domain/Feature]: 1. Generate the complete, valid SQL DDL script including `COMMENT ON` for tables and non-obvious columns. 2. Detail the design rationale, highlighting key constraints (`ON DELETE`, `CHECK`), indexes, and normalization decisions. 3. Verify against edge cases (nullability, concurrency, performance bottlenecks) before finalizing.