Primary Key
Primary Key
A column or combination of columns that uniquely identifies each row in a table. It implicitly has NOT NULL and UNIQUE constraints, and an index is created automatically to support fast lookups.
Primary Key
A column or combination of columns that uniquely identifies each row in a table. It implicitly has NOT NULL and UNIQUE constraints, and an index is created automatically to support fast lookups.
Primary Key is the most important constraint in a relational database for uniquely identifying each record in a table. A PK has two core properties: uniqueness (UNIQUE) and no NULLs (NOT NULL). As a result, no two rows in a table can have the same PK value, and every row must have a PK value.
Natural Key vs Surrogate Key is the key choice in PK design. A natural key uses a value that has meaning in the business (email, resident registration number, etc.), while a surrogate key uses a system-generated value with no meaning (AUTO_INCREMENT, UUID). In most cases a surrogate key is recommended, because a natural key can become a problem when business rules change.
Auto Increment is a common way to implement a surrogate key. MySQL uses AUTO_INCREMENT, PostgreSQL uses SERIAL or IDENTITY, and SQL Server uses IDENTITY. The numbers increase sequentially, so the insertion order can be known, and index efficiency is also good. However, in distributed environments, UUID may be more suitable.
Composite Primary Key (Composite PK) consists of two or more columns as the PK. It is mainly used in junction tables of many-to-many relationships. For example, in a student-enrollment table, (student_id, course_id) can be set as a composite PK.
A Clustered Index is automatically created on the PK. It determines the physical sort order of the table, and PK-based lookups are very fast. It becomes the target referenced by a Foreign Key, serving as the reference point for relationships between tables.
-- Primary Key 예제 - SQL DDL
-- ============================================
-- 1. 단일 컬럼 Primary Key
-- ============================================
-- PostgreSQL - SERIAL 사용
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
name VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- MySQL - AUTO_INCREMENT 사용
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
name VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- PostgreSQL 15+ - IDENTITY 사용 (표준 SQL)
CREATE TABLE users (
id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
name VARCHAR(100) NOT NULL
);
-- ============================================
-- 2. 복합 Primary Key (Composite PK)
-- ============================================
-- 다대다 관계 중간 테이블
CREATE TABLE student_courses (
student_id INTEGER NOT NULL,
course_id INTEGER NOT NULL,
enrolled_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
grade CHAR(2),
-- 복합 PK 정의
PRIMARY KEY (student_id, course_id),
-- Foreign Keys
FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,
FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE
);
-- 이력/버전 테이블
CREATE TABLE product_prices (
product_id INTEGER NOT NULL,
valid_from DATE NOT NULL,
price DECIMAL(10, 2) NOT NULL,
valid_to DATE,
PRIMARY KEY (product_id, valid_from),
FOREIGN KEY (product_id) REFERENCES products(id)
);
-- ============================================
-- 3. UUID를 Primary Key로 사용
-- ============================================
-- PostgreSQL
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE TABLE orders (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
customer_id INTEGER NOT NULL,
total_amount DECIMAL(10, 2) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- MySQL 8.0+
CREATE TABLE orders (
id CHAR(36) PRIMARY KEY DEFAULT (UUID()),
customer_id INT NOT NULL,
total_amount DECIMAL(10, 2) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- ============================================
-- 4. 자연 키(Natural Key) 예시
-- ============================================
-- 국가 코드를 PK로 사용 (ISO 3166-1)
CREATE TABLE countries (
code CHAR(2) PRIMARY KEY, -- 'KR', 'US', 'JP'
name VARCHAR(100) NOT NULL,
continent VARCHAR(50)
);
-- 설정 테이블 (키-값 구조)
CREATE TABLE app_settings (
key VARCHAR(100) PRIMARY KEY,
value TEXT NOT NULL,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- ============================================
-- 5. Primary Key 조회 성능
-- ============================================
-- PK를 통한 조회 (가장 빠름)
SELECT * FROM users WHERE id = 12345;
-- 실행 계획 확인
EXPLAIN ANALYZE SELECT * FROM users WHERE id = 12345;
-- Index Scan using users_pkey (PK 인덱스 사용)
-- ============================================
-- 6. Primary Key 관리
-- ============================================
-- 기존 테이블에 PK 추가
ALTER TABLE legacy_table
ADD PRIMARY KEY (id);
-- PK 삭제 (MySQL)
ALTER TABLE users DROP PRIMARY KEY;
-- PK 삭제 (PostgreSQL)
ALTER TABLE users DROP CONSTRAINT users_pkey;
-- 시퀀스 현재값/다음값 확인 (PostgreSQL)
SELECT currval('users_id_seq');
SELECT nextval('users_id_seq');
-- 시퀀스 재설정
ALTER SEQUENCE users_id_seq RESTART WITH 1000;
-- AUTO_INCREMENT 값 설정 (MySQL)
ALTER TABLE users AUTO_INCREMENT = 1000;
# Primary Key 예제 - Python + SQLAlchemy
from sqlalchemy import create_engine, Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.dialects.postgresql import UUID
from datetime import datetime
import uuid
Base = declarative_base()
# ============================================
# 1. 자동 증가 Primary Key
# ============================================
class User(Base):
"""자동 증가 PK 사용"""
__tablename__ = 'users'
# 자동 증가 PK (PostgreSQL SERIAL / MySQL AUTO_INCREMENT)
id = Column(Integer, primary_key=True, autoincrement=True)
email = Column(String(255), unique=True, nullable=False)
name = Column(String(100), nullable=False)
created_at = Column(DateTime, default=datetime.utcnow)
# 관계
orders = relationship('Order', back_populates='user')
def __repr__(self):
return f""
# ============================================
# 2. UUID Primary Key
# ============================================
class Order(Base):
"""UUID PK 사용 - 분산 시스템에 적합"""
__tablename__ = 'orders'
# UUID PK
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
total_amount = Column(Integer, nullable=False)
created_at = Column(DateTime, default=datetime.utcnow)
user = relationship('User', back_populates='orders')
# ============================================
# 3. 복합 Primary Key
# ============================================
class StudentCourse(Base):
"""복합 PK - 다대다 중간 테이블"""
__tablename__ = 'student_courses'
# 복합 PK
student_id = Column(Integer, ForeignKey('students.id'),
primary_key=True)
course_id = Column(Integer, ForeignKey('courses.id'),
primary_key=True)
enrolled_at = Column(DateTime, default=datetime.utcnow)
grade = Column(String(2))
# 관계
student = relationship('Student', back_populates='enrollments')
course = relationship('Course', back_populates='enrollments')
class Student(Base):
__tablename__ = 'students'
id = Column(Integer, primary_key=True)
name = Column(String(100), nullable=False)
enrollments = relationship('StudentCourse', back_populates='student')
class Course(Base):
__tablename__ = 'courses'
id = Column(Integer, primary_key=True)
title = Column(String(200), nullable=False)
enrollments = relationship('StudentCourse', back_populates='course')
# ============================================
# 4. 자연 키(Natural Key)
# ============================================
class Country(Base):
"""자연 키 사용 - ISO 국가 코드"""
__tablename__ = 'countries'
# 자연 키 PK
code = Column(String(2), primary_key=True) # 'KR', 'US'
name = Column(String(100), nullable=False)
continent = Column(String(50))
# ============================================
# 5. PK 사용 예제
# ============================================
def main():
engine = create_engine('postgresql://localhost/mydb', echo=True)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
try:
# 사용자 생성 (PK 자동 할당)
user = User(email='test@example.com', name='홍길동')
session.add(user)
session.flush() # PK 값 확정
print(f"생성된 사용자 ID: {user.id}") # 자동 생성된 ID
# UUID PK 주문 생성
order = Order(user_id=user.id, total_amount=50000)
session.add(order)
session.flush()
print(f"생성된 주문 UUID: {order.id}")
# PK로 조회 (가장 빠름)
found_user = session.query(User).get(user.id) # deprecated in 2.0
# SQLAlchemy 2.0 스타일
found_user = session.get(User, user.id)
# 복합 PK로 조회
enrollment = session.get(StudentCourse, (1, 1)) # (student_id, course_id)
session.commit()
except Exception as e:
session.rollback()
print(f"에러: {e}")
finally:
session.close()
if __name__ == '__main__':
main()
// Primary Key 예제 - Node.js + Prisma
// ============================================
// 1. Prisma 스키마 (schema.prisma)
// ============================================
/*
// 자동 증가 PK
model User {
id Int @id @default(autoincrement())
email String @unique
name String
createdAt DateTime @default(now())
orders Order[]
}
// UUID PK
model Order {
id String @id @default(uuid())
userId Int
totalAmount Decimal @db.Decimal(10, 2)
createdAt DateTime @default(now())
user User @relation(fields: [userId], references: [id])
}
// 복합 PK
model StudentCourse {
studentId Int
courseId Int
enrolledAt DateTime @default(now())
grade String?
student Student @relation(fields: [studentId], references: [id])
course Course @relation(fields: [courseId], references: [id])
@@id([studentId, courseId]) // 복합 PK
}
// 자연 키
model Country {
code String @id @db.Char(2) // 'KR', 'US'
name String
continent String?
}
// CUID (Collision-resistant Unique ID)
model Post {
id String @id @default(cuid())
title String
content String?
createdAt DateTime @default(now())
}
*/
// ============================================
// 2. Prisma Client 사용
// ============================================
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
async function main() {
// 자동 증가 PK - 생성 시 ID 자동 할당
const user = await prisma.user.create({
data: {
email: 'test@example.com',
name: '홍길동'
}
});
console.log('생성된 사용자 ID:', user.id); // 1, 2, 3...
// UUID PK - 생성 시 UUID 자동 할당
const order = await prisma.order.create({
data: {
userId: user.id,
totalAmount: 50000
}
});
console.log('생성된 주문 UUID:', order.id); // 550e8400-e29b-41d4...
// PK로 단일 레코드 조회 (가장 빠름)
const foundUser = await prisma.user.findUnique({
where: { id: user.id }
});
// 복합 PK로 조회
const enrollment = await prisma.studentCourse.findUnique({
where: {
studentId_courseId: { // 복합 PK 이름
studentId: 1,
courseId: 1
}
}
});
// 자연 키 사용
const country = await prisma.country.create({
data: {
code: 'KR',
name: '대한민국',
continent: 'Asia'
}
});
// 자연 키로 조회
const korea = await prisma.country.findUnique({
where: { code: 'KR' }
});
// PK 기반 관계 조회
const userWithOrders = await prisma.user.findUnique({
where: { id: user.id },
include: {
orders: true // FK가 참조하는 관계
}
});
// 대량 삽입 시 PK 반환
const users = await prisma.user.createMany({
data: [
{ email: 'user1@example.com', name: '사용자1' },
{ email: 'user2@example.com', name: '사용자2' }
],
// skipDuplicates: true // 중복 PK 무시
});
console.log('생성된 레코드 수:', users.count);
// PK 존재 여부 확인
const exists = await prisma.user.findUnique({
where: { id: 999 },
select: { id: true } // PK만 조회 (효율적)
});
if (!exists) {
console.log('사용자가 존재하지 않습니다');
}
}
main()
.catch(console.error)
.finally(() => prisma.$disconnect());
"I think the user table's PK should be an auto-increment number rather than the email. Emails can change, which becomes a problem when many tables reference it with an FK. The email can be managed separately with a UNIQUE index."
"In a microservices environment, it's better to use a UUID as the PK. There are no collisions even when multiple services create records at the same time. However, index efficiency is slightly lower, so consider ULID or Snowflake ID as well."
"Looking up by PK uses the clustered index, so it's the fastest. For list queries too, passing an array of PKs in the form WHERE id IN (1, 2, 3) is efficient. Make the most of PK-based lookups whenever possible."
Do not use values that can change, such as email, phone number, or resident registration number, as a PK. When the value changes, every table that references it through an FK must be updated.
Do not reuse the PK value of a deleted record. It can cause confusion in logs and audit records, and can lead to foreign key reference problems.
If a composite PK is made up of three or more columns, JOINs become complex and setting up FKs becomes difficult. Consider adding a surrogate key.
Prefer a surrogate key (auto-increment/UUID); use a consistent id rather than a meaningful name (user_id); consider UUID/ULID in distributed environments; use composite PKs only in junction tables, and only in a limited way.