Query
Query
A command that requests or manipulates information in a database. A collective term for all statements that handle data, from SQL's SELECT, INSERT, UPDATE, and DELETE to NoSQL's find() and aggregate().
Query
A command that requests or manipulates information in a database. A collective term for all statements that handle data, from SQL's SELECT, INSERT, UPDATE, and DELETE to NoSQL's find() and aggregate().
A query is a "question" posed to a database. A request such as "Find all users in their 20s who live in Seoul" expressed in SQL or NoSQL syntax is a query. It includes not only data retrieval but all data manipulation commands, including insert, update, and delete.
A SELECT query is the most frequently used retrieval command. FROM specifies the table, WHERE applies conditions, ORDER BY sorts, and LIMIT restricts the number of rows. JOIN connects multiple tables, and GROUP BY with aggregate functions (COUNT, SUM, AVG) can summarize data.
A subquery is another query contained within a query. It is used when the result of another query serves as a condition, as in "retrieve employees whose salary is higher than the average salary." There are various forms, including scalar subqueries (single value), inline views (FROM clause), and EXISTS/IN subqueries (WHERE clause).
The query execution order differs from the SQL syntax order. Processing proceeds in the order FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY -> LIMIT. Understanding this order is necessary to write correct queries and optimize performance.
Query optimization is the key to performance. You should analyze the execution plan with EXPLAIN, use indexes, prevent the N+1 problem, and avoid retrieving unnecessary columns. It is important to monitor the Slow Query Log to find and improve bottleneck queries.
-- ============================================
-- 1. 기본 SELECT 쿼리
-- ============================================
-- 전체 조회
SELECT * FROM users;
-- 특정 컬럼만 조회 (권장)
SELECT id, name, email FROM users;
-- 조건 필터링
SELECT * FROM users
WHERE status = 'active'
AND created_at >= '2024-01-01';
-- 정렬과 페이지네이션
SELECT * FROM orders
ORDER BY created_at DESC
LIMIT 20 OFFSET 0;
-- ============================================
-- 2. JOIN - 테이블 연결
-- ============================================
-- INNER JOIN: 양쪽 모두 일치하는 데이터
SELECT u.name, o.total_amount, o.created_at
FROM users u
INNER JOIN orders o ON u.id = o.user_id
WHERE o.status = 'completed';
-- LEFT JOIN: 왼쪽 테이블 기준 (주문 없는 사용자도 포함)
SELECT u.name, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id, u.name;
-- 다중 JOIN
SELECT u.name, p.name as product_name, oi.quantity
FROM users u
JOIN orders o ON u.id = o.user_id
JOIN order_items oi ON o.id = oi.order_id
JOIN products p ON oi.product_id = p.id
WHERE o.id = 12345;
-- ============================================
-- 3. 집계 쿼리 (GROUP BY)
-- ============================================
-- 카테고리별 상품 수
SELECT category, COUNT(*) as product_count
FROM products
GROUP BY category
ORDER BY product_count DESC;
-- 월별 매출 통계
SELECT
DATE_TRUNC('month', created_at) as month,
COUNT(*) as order_count,
SUM(total_amount) as revenue,
AVG(total_amount) as avg_order_value
FROM orders
WHERE status = 'completed'
GROUP BY DATE_TRUNC('month', created_at)
HAVING SUM(total_amount) > 1000000
ORDER BY month DESC;
-- ============================================
-- 4. 서브쿼리 (Subquery)
-- ============================================
-- 스칼라 서브쿼리: 평균보다 높은 가격의 상품
SELECT name, price
FROM products
WHERE price > (SELECT AVG(price) FROM products);
-- IN 서브쿼리: 주문한 적 있는 사용자
SELECT * FROM users
WHERE id IN (
SELECT DISTINCT user_id FROM orders
WHERE created_at >= '2024-01-01'
);
-- EXISTS: 리뷰가 있는 상품
SELECT p.name FROM products p
WHERE EXISTS (
SELECT 1 FROM reviews r WHERE r.product_id = p.id
);
-- 인라인 뷰 (FROM절 서브쿼리)
SELECT category, avg_price
FROM (
SELECT category, AVG(price) as avg_price
FROM products
GROUP BY category
) as category_stats
WHERE avg_price > 50000;
-- ============================================
-- 5. 윈도우 함수 (고급)
-- ============================================
-- 순위 매기기
SELECT
name,
category,
price,
RANK() OVER (PARTITION BY category ORDER BY price DESC) as price_rank
FROM products;
-- 누적 합계
SELECT
created_at::date as date,
total_amount,
SUM(total_amount) OVER (ORDER BY created_at) as cumulative_revenue
FROM orders;
-- 이전 행 비교 (전일 대비)
SELECT
date,
revenue,
revenue - LAG(revenue) OVER (ORDER BY date) as diff_from_yesterday
FROM daily_sales;
-- ============================================
-- 6. 데이터 조작 쿼리 (DML)
-- ============================================
-- INSERT
INSERT INTO users (name, email, status)
VALUES ('홍길동', 'hong@example.com', 'active');
-- UPDATE
UPDATE users
SET status = 'inactive', updated_at = NOW()
WHERE last_login_at < NOW() - INTERVAL '6 months';
-- DELETE (주의!)
DELETE FROM sessions
WHERE expires_at < NOW();
-- UPSERT (PostgreSQL)
INSERT INTO user_settings (user_id, theme, language)
VALUES (1, 'dark', 'ko')
ON CONFLICT (user_id)
DO UPDATE SET theme = EXCLUDED.theme, language = EXCLUDED.language;
# 쿼리 예제 - Python + SQLAlchemy
from sqlalchemy import create_engine, text, select, func, and_, or_
from sqlalchemy.orm import Session, declarative_base, relationship
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Numeric
from datetime import datetime, timedelta
Base = declarative_base()
# 모델 정의
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(100))
email = Column(String(255))
status = Column(String(20))
created_at = Column(DateTime, default=datetime.utcnow)
orders = relationship("Order", back_populates="user")
class Order(Base):
__tablename__ = 'orders'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'))
total_amount = Column(Numeric(10, 2))
status = Column(String(20))
created_at = Column(DateTime)
user = relationship("User", back_populates="orders")
class QueryExamples:
def __init__(self, engine):
self.engine = engine
def basic_select(self):
"""기본 SELECT 쿼리"""
with Session(self.engine) as session:
# ORM 스타일
users = session.query(User).filter(
User.status == 'active'
).order_by(User.created_at.desc()).limit(10).all()
# 2.0 스타일 (권장)
stmt = select(User).where(
User.status == 'active'
).order_by(User.created_at.desc()).limit(10)
users = session.scalars(stmt).all()
return users
def complex_filter(self):
"""복잡한 조건 필터"""
with Session(self.engine) as session:
one_month_ago = datetime.utcnow() - timedelta(days=30)
# AND, OR 조건
stmt = select(User).where(
and_(
User.status == 'active',
or_(
User.email.like('%@gmail.com'),
User.created_at >= one_month_ago
)
)
)
return session.scalars(stmt).all()
def join_query(self):
"""JOIN 쿼리"""
with Session(self.engine) as session:
# 사용자와 주문 조인
stmt = (
select(User.name, Order.total_amount, Order.created_at)
.join(Order, User.id == Order.user_id)
.where(Order.status == 'completed')
.order_by(Order.created_at.desc())
)
results = session.execute(stmt).all()
# Eager Loading으로 N+1 방지
from sqlalchemy.orm import selectinload
stmt = select(User).options(
selectinload(User.orders)
).where(User.status == 'active')
users_with_orders = session.scalars(stmt).all()
return results
def aggregate_query(self):
"""집계 쿼리"""
with Session(self.engine) as session:
# 월별 매출 통계
stmt = (
select(
func.date_trunc('month', Order.created_at).label('month'),
func.count(Order.id).label('order_count'),
func.sum(Order.total_amount).label('revenue'),
func.avg(Order.total_amount).label('avg_order')
)
.where(Order.status == 'completed')
.group_by(func.date_trunc('month', Order.created_at))
.having(func.sum(Order.total_amount) > 1000000)
.order_by(text('month DESC'))
)
return session.execute(stmt).all()
def subquery_example(self):
"""서브쿼리 예제"""
with Session(self.engine) as session:
# 주문한 적 있는 사용자
order_subquery = (
select(Order.user_id)
.where(Order.created_at >= datetime(2024, 1, 1))
.distinct()
.subquery()
)
stmt = select(User).where(
User.id.in_(select(order_subquery.c.user_id))
)
return session.scalars(stmt).all()
def raw_sql(self):
"""Raw SQL 쿼리 (복잡한 경우)"""
with Session(self.engine) as session:
result = session.execute(text("""
SELECT u.name,
COUNT(o.id) as order_count,
SUM(o.total_amount) as total_spent
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.status = :status
GROUP BY u.id, u.name
HAVING COUNT(o.id) > :min_orders
ORDER BY total_spent DESC
"""), {"status": "active", "min_orders": 5})
return [dict(row._mapping) for row in result]
def pagination(self, page: int = 1, per_page: int = 20):
"""페이지네이션"""
with Session(self.engine) as session:
offset = (page - 1) * per_page
# 전체 개수
count_stmt = select(func.count(User.id)).where(User.status == 'active')
total = session.scalar(count_stmt)
# 페이지 데이터
stmt = (
select(User)
.where(User.status == 'active')
.order_by(User.id)
.offset(offset)
.limit(per_page)
)
users = session.scalars(stmt).all()
return {
"data": users,
"total": total,
"page": page,
"per_page": per_page,
"total_pages": (total + per_page - 1) // per_page
}
# 사용 예시
if __name__ == "__main__":
engine = create_engine("postgresql://localhost/mydb")
examples = QueryExamples(engine)
# 기본 조회
users = examples.basic_select()
# 집계 쿼리
stats = examples.aggregate_query()
print(stats)
// 쿼리 예제 - Node.js + Prisma
import { PrismaClient, Prisma } from '@prisma/client';
const prisma = new PrismaClient({
log: ['query'], // 실행되는 SQL 확인
});
class QueryExamples {
/**
* 기본 SELECT 쿼리
*/
async basicSelect() {
// 전체 조회
const users = await prisma.user.findMany({
where: { status: 'active' },
orderBy: { createdAt: 'desc' },
take: 10,
});
// 특정 컬럼만 조회
const emails = await prisma.user.findMany({
select: { id: true, email: true },
where: { status: 'active' },
});
return users;
}
/**
* 복잡한 조건 필터
*/
async complexFilter() {
const oneMonthAgo = new Date();
oneMonthAgo.setDate(oneMonthAgo.getDate() - 30);
// AND, OR 조건
const users = await prisma.user.findMany({
where: {
AND: [
{ status: 'active' },
{
OR: [
{ email: { contains: '@gmail.com' } },
{ createdAt: { gte: oneMonthAgo } },
],
},
],
},
});
// NOT 조건
const notDeleted = await prisma.user.findMany({
where: {
NOT: { status: 'deleted' },
},
});
return users;
}
/**
* JOIN (관계 포함)
*/
async joinQuery() {
// 사용자와 주문 함께 조회
const usersWithOrders = await prisma.user.findMany({
where: { status: 'active' },
include: {
orders: {
where: { status: 'completed' },
orderBy: { createdAt: 'desc' },
take: 5,
},
},
});
// 중첩 관계 (주문 -> 주문상품 -> 상품)
const ordersWithDetails = await prisma.order.findMany({
include: {
user: { select: { name: true, email: true } },
orderItems: {
include: {
product: { select: { name: true, price: true } },
},
},
},
});
return usersWithOrders;
}
/**
* 집계 쿼리
*/
async aggregateQuery() {
// 기본 집계
const stats = await prisma.order.aggregate({
_count: { id: true },
_sum: { totalAmount: true },
_avg: { totalAmount: true },
_min: { totalAmount: true },
_max: { totalAmount: true },
where: { status: 'completed' },
});
// GROUP BY
const categoryStats = await prisma.product.groupBy({
by: ['category'],
_count: { id: true },
_avg: { price: true },
orderBy: { _count: { id: 'desc' } },
});
// HAVING
const popularCategories = await prisma.product.groupBy({
by: ['category'],
_count: { id: true },
having: {
id: { _count: { gt: 10 } },
},
});
return { stats, categoryStats };
}
/**
* Raw SQL 쿼리 (복잡한 경우)
*/
async rawQuery() {
// 타입 안전 Raw SQL
const result = await prisma.$queryRaw<
{ name: string; order_count: bigint; total_spent: number }[]
>`
SELECT u.name,
COUNT(o.id) as order_count,
COALESCE(SUM(o.total_amount), 0) as total_spent
FROM "User" u
LEFT JOIN "Order" o ON u.id = o.user_id
WHERE u.status = 'active'
GROUP BY u.id, u.name
HAVING COUNT(o.id) > 5
ORDER BY total_spent DESC
`;
// 동적 쿼리
const status = 'active';
const dynamicResult = await prisma.$queryRaw`
SELECT * FROM "User" WHERE status = ${status}
`;
return result;
}
/**
* 페이지네이션
*/
async pagination(page = 1, perPage = 20) {
const skip = (page - 1) * perPage;
// 트랜잭션으로 데이터와 카운트 동시 조회
const [users, total] = await prisma.$transaction([
prisma.user.findMany({
where: { status: 'active' },
orderBy: { id: 'asc' },
skip,
take: perPage,
}),
prisma.user.count({
where: { status: 'active' },
}),
]);
return {
data: users,
meta: {
total,
page,
perPage,
totalPages: Math.ceil(total / perPage),
},
};
}
/**
* 커서 기반 페이지네이션 (대용량 최적화)
*/
async cursorPagination(cursor?: number, limit = 20) {
const users = await prisma.user.findMany({
take: limit + 1, // 다음 페이지 존재 여부 확인
...(cursor && {
cursor: { id: cursor },
skip: 1, // 커서 자체는 제외
}),
orderBy: { id: 'asc' },
});
const hasNextPage = users.length > limit;
const data = hasNextPage ? users.slice(0, -1) : users;
const nextCursor = hasNextPage ? data[data.length - 1]?.id : null;
return { data, nextCursor, hasNextPage };
}
/**
* 트랜잭션 쿼리
*/
async transactionQuery(fromUserId: number, toUserId: number, amount: number) {
return prisma.$transaction(async (tx) => {
// 1. 출금
const sender = await tx.wallet.update({
where: { userId: fromUserId },
data: { balance: { decrement: amount } },
});
// 잔액 체크
if (sender.balance < 0) {
throw new Error('잔액 부족');
}
// 2. 입금
await tx.wallet.update({
where: { userId: toUserId },
data: { balance: { increment: amount } },
});
// 3. 거래 기록
return tx.transaction.create({
data: { fromUserId, toUserId, amount, type: 'transfer' },
});
});
}
}
// 사용 예시
async function main() {
const examples = new QueryExamples();
// 기본 조회
const users = await examples.basicSelect();
// 집계
const stats = await examples.aggregateQuery();
console.log(stats);
// 커서 페이지네이션
let cursor: number | undefined;
do {
const { data, nextCursor } = await examples.cursorPagination(cursor);
console.log(`Fetched ${data.length} users`);
cursor = nextCursor ?? undefined;
} while (cursor);
await prisma.$disconnect();
}
main();
"The reason this API is slow is N+1 queries. When retrieving the user list, it fetches each user's orders with a separate query. If you fetch them all at once with a JOIN or Eager Loading, you can reduce the number of queries from 100 to 1."
"Please specify only the necessary columns instead of SELECT *. In particular, this table has a BLOB column, so it transfers unnecessarily large data. If you change it to select: { id, name, email }, the response size will be reduced by 90%."
"After analyzing the Slow Query Log, this aggregate query takes more than 5 seconds. It scans the entire table every time. If you add a date range condition and create an appropriate index, you can reduce it to 0.1 seconds."
Do not concatenate user input directly into queries. Always use parameter binding (Prepared Statement). Write "WHERE id = $1" instead of "WHERE id = " + userId.
Running queries inside a loop causes performance to degrade sharply. Retrieve the data at once with a JOIN, Eager Loading, or an IN clause.
As OFFSET grows, performance degrades sharply (OFFSET 10000 reads 10000 rows and discards them). For large datasets, use cursor-based pagination.
Analyze the execution plan with EXPLAIN, SELECT only the necessary columns, use indexes, set an appropriate LIMIT, monitor Slow Queries, and encapsulate complex queries as views or functions.