C.W.K.
Stream
Lesson 07 of 10 · published

ANALYZE 와 PRAGMA optimize

~12 min · analyze, stats, optimizer

Level 0Scout
0 XP0/80 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Planner 한테 더 좋은 선택 도와주기

SQLite query planner 가 어떤 인덱스 쓸지 결정에 sqlite_stat1통계 사용. 통계 없으면 합리적 default, 있으면 skewed 데이터에 극적으로 더 좋은 plan.

알아둘 명령 두 개:

  • ANALYZE — 전체 DB (또는 단일 테이블) 통계 수집. 큰 데이터 변경 후, 또는 deploy step 으로 실행.
  • PRAGMA optimize — 모던 lightweight. SQLite 가 어떤 테이블이 re-analyze 필요한지 추적, 필요한 것만 다시 돌림. Connection close 마다 호출하기 싸.
Tip: 추천 모던 패턴: connection close 마다 PRAGMA optimize 호출. SQLite 가 (있으면) 뭐 필요한지 알아냄, 보통 거의 공짜. Long-running 앱에서 maintenance window 없이 통계 fresh 유지.

Code

통계 fresh 유지 3 패턴·sql
-- 큰 import 후 one-shot
ANALYZE;

-- 단일 테이블
ANALYZE messages;

-- 추천: connection close 시 PRAGMA optimize
-- (마지막 analyze 이후 충분히 안 바뀐 테이블엔 아무 것도 안 함)
PRAGMA optimize;
Python — connection lifecycle 에 wire·python
import sqlite3, atexit

conn = sqlite3.connect('demo.db')
conn.execute('PRAGMA journal_mode = WAL')

def on_close():
    try:
        conn.execute('PRAGMA optimize')
    finally:
        conn.close()

atexit.register(on_close)

External links

Exercise

100k+ row DB 에서 multi-index query EXPLAIN. ANALYZE 실행 후 re-EXPLAIN. Planner 가 다른 인덱스 골랐는지 기록. Long-running 앱 패턴 추가: 모든 connection close 가 PRAGMA optimize 호출; 시간 지나며 통계 fresh 유지 관찰.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.