DB 스키마 설계 원칙
AI 모델에 실용적인 관계형 데이터베이스(RDB) 스키마 설계 규칙과 모범 사례를 주입합니다.
- 추천 툴
- ClaudeAI 분류
- 쓰인 기법
- 역할 부여 · 제약 조건 명시 · 출력 표준화
프롬프트 원문
# 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`을 작성합니다.
- 활용Cursor나 Claude System Prompt에 커스텀 지침으로 등록해 두면 고품질의 DB 마이그레이션 코드를 작성해 줍니다.
- 활용새 프로젝트 설계 시 데이터 모델 검수용 체크리스트로도 유용하게 활용할 수 있습니다.
출처 · 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가지를 모두 확인했습니다. 요구사항 준수 준비가 완료되었습니다.
핵심 설계 적용 방식 요약:
- 기본키/외래키 구조: 모든 테이블에
bigintidentity 또는UUIDv7인공키 적용, 외래키 명시적 제약조건 설정 및<referenced_table_singular>_id명명 규칙 준수. - 데이터 무결성 & 타입:
NOT NULL기본 적용, UTC 기준timestamptz사용, 통화 데이터는 정수/numeric처리, 상태값 및 범위 검증을 위한CHECK제약조건 활용. - 정규화 & 인덱스: 3정규형(3NF) 기반 설계 후 필요시 역정규화 문서화,
EXPLAIN기반 인덱싱 및 Partial Index 활용. - 안전성 & 확장성: 다형성 외래키 금지, 변경 이력(Audit) 단방향 전용 테이블 관리, Row-Level Security(RLS)를 통한 다중 테넌트(
tenant_id) 격리 지원.
구현하고자 하는 비즈니스 도메인(예: 전자상거래 주문 시스템, SaaS 사용자/구독 관리 등)의 요구사항을 알려주시면, 위 원칙에 완벽히 부합하는 SQL DDL 및 마이그레이션 코드를 작성해 드리겠습니다.
mopick 개선안
원문을 더 잘 동작하게 고쳐 쓴 프롬프트
원문을 그대로 넣으면 AI 가 매번 다르게 답하거나 중요한 부분을 빠뜨릴 수 있습니다. 개선안은 원문의 뜻과 언어는 그대로 두고 역할 · 바꿔 넣을 입력 칸 · 결과 형식 · 지킬 조건을 보완해 다시 쓴 버전입니다. 원문과 같은 곳(ChatGPT · Claude 등)에 그대로 붙여 넣어 쓰면 됩니다.
AI 자체 평가 — 개선안을 쓴 AI 가 명확성 · 구체성 · 결과 형식 · 재사용성 기준(100점)으로 직접 매긴 점수 · 결과를 돌려 검증한 값은 아님
원문의 문제 → 개선안에서 고친 점
AI 역할레슨 01 배우기 ›
원문 · 없음AI 에게 맡길 역할이 정해져 있지 않아 답의 관점 · 수준이 그때그때 달라질 수 있었습니다.
개선 · 역할을 정함Role: Pragmatic Relational Database Architect
입력 칸레슨 05 배우기 ›
원문 · 없음바꿔 넣을 자리가 표시돼 있지 않아 쓸 때마다 원문을 직접 고쳐야 했습니다.
개선 · 1개[Insert Target Domain/Feature]
작업 순서레슨 07 배우기 ›
원문 · 없음작업 순서가 정해져 있지 않아 AI 가 순서를 스스로 정해야 했습니다.
개선 · 3단계
고친 이유 (개선안을 만든 AI 의 설명)
- 1역할 및 실행 과업을 선언하여 단순 규칙 모음을 지시형 프롬프트로 전환.
- 2노이즈(Confidence 점수) 제거 및 주제별 카테고리화로 가독성과 집중도 향상.
- 3출력 형식(DDL, 설계 근거, 자가 검토)을 명확히 정의하여 재사용성 증대.
이 개선안에 쓰인 기법 — 프롬프트 클래스에서 배우기
01역할 정하기03결과 모양 정하기05입력 칸으로 템플릿 만들기07작업을 단계로 나누기08스스로 검토하게 하기09구역을 나눠 쓰기
원문
# 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
개선안 · 색칠한 [칸]에 내 내용을 넣어 쓰세요
# 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.
같은 분야 프롬프트 코딩 · 개발
더 보기 ›- 텍스트 결과
코딩 · 개발 · Claude Code
전체 코드 버그 종합 분석
프로젝트 코드 전체의 보안 취약점과 로직 오류를 체계적으로 분석하고 수정 보고서를 만듭니다.
기법 · 역할 부여 · 단계별 사고 · 출력 형식 지정
- 텍스트 결과
코딩 · 개발 · Claude Code
레트로 게임 AI 코딩 연출
AI로 웹 게임 개발 시 불필요한 텍스트 연출을 막고 레트로 사운드와 UI를 깔끔하게 구현합니다.
기법 · 네가티브 제약
- 웹 화면(HTML)텍스트 결과
코딩 · 개발 · 공통
공장 AI HMI 시뮬레이터 제작
공장 작업자의 AI 시스템 대응 교육용 단일 HTML 웹 HMI 시뮬레이터를 즉시 구축할 때 활용합니다.
기법 · 역할 부여 · 단계별 지시 · 출력 형식 지정

