Foreign Key
Foreign Key
A constraint that defines relationships between tables by referencing another table's Primary Key. It ensures referential integrity and maintains data consistency.
Foreign Key
A constraint that defines relationships between tables by referencing another table's Primary Key. It ensures referential integrity and maintains data consistency.
A Foreign Key is a key constraint that establishes the relationship between two tables in a relational database. A column (or set of columns) in one table references the Primary Key of another table, forming a "parent-child" relationship. For example, if customer_id in the orders table references id in the customers table, an order cannot be created for a customer that does not exist.
Referential Integrity is the core purpose of an FK. When data is inserted into a child table, the corresponding value must exist in the parent table. This prevents "orphan records" from arising and ensures the logical consistency of the entire database.
Referential Actions define the behavior when a parent record is deleted or updated. CASCADE deletes/updates the children as well, SET NULL sets the child's FK to NULL, RESTRICT/NO ACTION rejects the deletion if children exist, and SET DEFAULT sets it to the default value. You must choose the appropriate action according to your business logic.
In terms of indexing and performance, it is recommended to create an index on FK columns. Performance improves significantly for JOIN queries and referential integrity checks. MySQL InnoDB automatically creates an index on FKs, but PostgreSQL requires you to create it explicitly.
FKs are used to model 1:1, 1:N, and N:M relationships. An N:M relationship is implemented with two FKs through a junction table. Proper FK design is the foundation of a normalized schema and efficient queries.
-- Foreign Key 예제 - SQL DDL
-- ============================================
-- 1. 기본 Foreign Key 생성
-- ============================================
-- 부모 테이블 (참조 대상)
CREATE TABLE customers (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 자식 테이블 (FK 보유)
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
customer_id INTEGER NOT NULL,
total_amount DECIMAL(10, 2) NOT NULL,
status VARCHAR(20) DEFAULT 'pending',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
-- Foreign Key 제약조건
CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id)
REFERENCES customers(id)
ON DELETE RESTRICT
ON UPDATE CASCADE
);
-- ============================================
-- 2. 참조 동작(Referential Actions)
-- ============================================
-- CASCADE: 부모 삭제 시 자식도 삭제
CREATE TABLE order_items (
id SERIAL PRIMARY KEY,
order_id INTEGER NOT NULL,
product_name VARCHAR(200) NOT NULL,
quantity INTEGER NOT NULL,
price DECIMAL(10, 2) NOT NULL,
FOREIGN KEY (order_id)
REFERENCES orders(id)
ON DELETE CASCADE -- 주문 삭제 시 아이템도 삭제
);
-- SET NULL: 부모 삭제 시 NULL로 설정
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
author_id INTEGER, -- NULL 허용
title VARCHAR(200) NOT NULL,
content TEXT,
FOREIGN KEY (author_id)
REFERENCES users(id)
ON DELETE SET NULL -- 사용자 삭제 시 author_id = NULL
);
-- ============================================
-- 3. 복합 Foreign Key
-- ============================================
CREATE TABLE enrollments (
student_id INTEGER NOT NULL,
course_id INTEGER NOT NULL,
semester VARCHAR(10) NOT NULL,
grade CHAR(2),
-- 복합 Primary Key
PRIMARY KEY (student_id, course_id, semester),
-- 각각의 FK
FOREIGN KEY (student_id) REFERENCES students(id),
FOREIGN KEY (course_id) REFERENCES courses(id)
);
-- ============================================
-- 4. FK 인덱스 생성 (PostgreSQL)
-- ============================================
-- FK 열에 인덱스 추가 (성능 향상)
CREATE INDEX idx_orders_customer_id ON orders(customer_id);
CREATE INDEX idx_order_items_order_id ON order_items(order_id);
-- ============================================
-- 5. FK 활용 JOIN 쿼리
-- ============================================
-- 고객별 주문 조회
SELECT
c.name AS customer_name,
c.email,
COUNT(o.id) AS order_count,
SUM(o.total_amount) AS total_spent
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id
GROUP BY c.id, c.name, c.email
ORDER BY total_spent DESC;
-- ============================================
-- 6. FK 제약조건 관리
-- ============================================
-- 기존 테이블에 FK 추가
ALTER TABLE orders
ADD CONSTRAINT fk_orders_shipping_address
FOREIGN KEY (shipping_address_id)
REFERENCES addresses(id);
-- FK 제약조건 삭제
ALTER TABLE orders
DROP CONSTRAINT fk_orders_shipping_address;
-- FK 일시적으로 비활성화 (MySQL)
SET FOREIGN_KEY_CHECKS = 0;
-- 대량 데이터 작업...
SET FOREIGN_KEY_CHECKS = 1;
-- FK 일시적으로 비활성화 (PostgreSQL)
ALTER TABLE orders DISABLE TRIGGER ALL;
-- 대량 데이터 작업...
ALTER TABLE orders ENABLE TRIGGER ALL;
# Foreign Key 예제 - Python + SQLAlchemy
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Numeric, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from datetime import datetime
Base = declarative_base()
# ============================================
# 1. 1:N 관계 모델 정의
# ============================================
class Customer(Base):
"""고객 모델 (부모)"""
__tablename__ = 'customers'
id = Column(Integer, primary_key=True)
name = Column(String(100), nullable=False)
email = Column(String(255), unique=True, nullable=False)
created_at = Column(DateTime, default=datetime.utcnow)
# 관계 정의 (역참조)
orders = relationship('Order', back_populates='customer',
cascade='all, delete-orphan')
def __repr__(self):
return f""
class Order(Base):
"""주문 모델 (자식)"""
__tablename__ = 'orders'
id = Column(Integer, primary_key=True)
customer_id = Column(Integer, ForeignKey('customers.id',
ondelete='CASCADE',
onupdate='CASCADE'),
nullable=False)
total_amount = Column(Numeric(10, 2), nullable=False)
status = Column(String(20), default='pending')
created_at = Column(DateTime, default=datetime.utcnow)
# 관계 정의
customer = relationship('Customer', back_populates='orders')
items = relationship('OrderItem', back_populates='order',
cascade='all, delete-orphan')
class OrderItem(Base):
"""주문 아이템 모델"""
__tablename__ = 'order_items'
id = Column(Integer, primary_key=True)
order_id = Column(Integer, ForeignKey('orders.id', ondelete='CASCADE'),
nullable=False)
product_name = Column(String(200), nullable=False)
quantity = Column(Integer, nullable=False)
price = Column(Numeric(10, 2), nullable=False)
order = relationship('Order', back_populates='items')
# ============================================
# 2. N:M 관계 (다대다)
# ============================================
from sqlalchemy import Table
# 중간 테이블 (Association Table)
student_course = Table(
'student_courses',
Base.metadata,
Column('student_id', Integer, ForeignKey('students.id', ondelete='CASCADE'),
primary_key=True),
Column('course_id', Integer, ForeignKey('courses.id', ondelete='CASCADE'),
primary_key=True)
)
class Student(Base):
__tablename__ = 'students'
id = Column(Integer, primary_key=True)
name = Column(String(100), nullable=False)
# 다대다 관계
courses = relationship('Course', secondary=student_course,
back_populates='students')
class Course(Base):
__tablename__ = 'courses'
id = Column(Integer, primary_key=True)
title = Column(String(200), nullable=False)
students = relationship('Student', secondary=student_course,
back_populates='courses')
# ============================================
# 3. FK 사용 예제
# ============================================
def main():
# 데이터베이스 연결
engine = create_engine('postgresql://localhost/mydb')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
try:
# 고객 생성
customer = Customer(name='홍길동', email='hong@example.com')
session.add(customer)
session.flush() # ID 할당
# 주문 생성 (FK 자동 검증)
order = Order(
customer_id=customer.id,
total_amount=50000
)
session.add(order)
# relationship을 통한 접근
order.items.append(OrderItem(
product_name='노트북',
quantity=1,
price=50000
))
session.commit()
# FK를 통한 JOIN 쿼리
result = session.query(Customer, Order)\
.join(Order, Customer.id == Order.customer_id)\
.filter(Customer.name == '홍길동')\
.all()
for customer, order in result:
print(f"{customer.name}: 주문금액 {order.total_amount}")
# 존재하지 않는 FK 삽입 시도 - 에러 발생
# invalid_order = Order(customer_id=99999, total_amount=10000)
# session.add(invalid_order)
# session.commit() # IntegrityError 발생!
except Exception as e:
session.rollback()
print(f"에러: {e}")
finally:
session.close()
if __name__ == '__main__':
main()
// Foreign Key 예제 - Node.js + Prisma
// ============================================
// 1. Prisma 스키마 (schema.prisma)
// ============================================
/*
model Customer {
id Int @id @default(autoincrement())
name String
email String @unique
createdAt DateTime @default(now())
// 1:N 관계 (한 고객이 여러 주문)
orders Order[]
}
model Order {
id Int @id @default(autoincrement())
customerId Int // Foreign Key
totalAmount Decimal @db.Decimal(10, 2)
status String @default("pending")
createdAt DateTime @default(now())
// FK 관계 정의
customer Customer @relation(fields: [customerId], references: [id],
onDelete: Cascade, onUpdate: Cascade)
items OrderItem[]
@@index([customerId]) // FK에 인덱스 추가
}
model OrderItem {
id Int @id @default(autoincrement())
orderId Int // Foreign Key
productName String
quantity Int
price Decimal @db.Decimal(10, 2)
order Order @relation(fields: [orderId], references: [id],
onDelete: Cascade)
@@index([orderId])
}
// N:M 관계 (다대다)
model Student {
id Int @id @default(autoincrement())
name String
courses Course[] // 암묵적 다대다
}
model Course {
id Int @id @default(autoincrement())
title String
students Student[]
}
*/
// ============================================
// 2. Prisma Client 사용
// ============================================
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
async function main() {
// 고객과 주문을 함께 생성 (Nested Write)
const customer = await prisma.customer.create({
data: {
name: '홍길동',
email: 'hong@example.com',
orders: {
create: [
{
totalAmount: 50000,
status: 'completed',
items: {
create: [
{ productName: '노트북', quantity: 1, price: 50000 }
]
}
}
]
}
},
include: {
orders: {
include: { items: true }
}
}
});
console.log('생성된 고객:', customer);
// FK를 통한 관계 조회
const ordersWithCustomer = await prisma.order.findMany({
where: {
customer: {
name: '홍길동'
}
},
include: {
customer: true,
items: true
}
});
console.log('주문 목록:', ordersWithCustomer);
// FK 무결성 테스트 - 존재하지 않는 고객 ID
try {
await prisma.order.create({
data: {
customerId: 99999, // 존재하지 않는 ID
totalAmount: 10000
}
});
} catch (error) {
console.error('FK 위반 에러:', error.message);
// Foreign key constraint failed on the field: `Order_customerId_fkey`
}
// CASCADE 삭제 테스트
// 고객 삭제 시 주문과 주문아이템도 함께 삭제
await prisma.customer.delete({
where: { id: customer.id }
});
console.log('고객 삭제 완료 (CASCADE로 주문도 삭제됨)');
// N:M 관계 예제
const student = await prisma.student.create({
data: {
name: '김학생',
courses: {
create: [
{ title: '데이터베이스' },
{ title: '알고리즘' }
]
}
},
include: { courses: true }
});
// 기존 코스에 학생 연결
await prisma.student.update({
where: { id: student.id },
data: {
courses: {
connect: [{ id: 1 }, { id: 2 }] // 기존 코스 연결
}
}
});
}
main()
.catch(console.error)
.finally(() => prisma.$disconnect());
"We need to put a Foreign Key on customer_id in the orders table. That way we can prevent orders from being created for customers that don't exist. If we set ON DELETE to RESTRICT, customers who have orders can't be deleted, so data integrity is guaranteed."
"I think the JOIN is slow because there's no index on the FK column. PostgreSQL doesn't automatically create an index on FKs. If you add an index on customer_id in the orders table, query speed should improve dramatically."
"When migrating a large amount of data, it's better to temporarily turn off FK checks. In MySQL, you disable them with SET FOREIGN_KEY_CHECKS = 0 and turn them back on when the work is done. Otherwise, it validates references on every INSERT, which is extremely slow."
ON DELETE CASCADE is convenient, but it can cause unintended mass deletions. Use RESTRICT for important data, and handle deletions explicitly in the application.
PostgreSQL does not automatically create an index on FKs. Always add an index to FK columns. Without one, JOIN and DELETE performance degrades significantly.
If table A references B and B references A again, it becomes a circular reference. This causes insertion/deletion order problems, so it should be avoided in design.
Standardize FK column names in the referenced_table_id format (customer_id), add an index to every FK, choose referential actions to fit the business logic, and implement N:M with a junction table.