SQL Practical Guide with Claude Code
Learn about sql practical guide using Claude Code. Practical tips and code examples included.
SQLクエリ最適化をClaude Codeで実践する
データベースのパフォーマンス問題は多くのプロジェクトで発生します。Claude Codeを使えば、遅いクエリの原因特定からインデックス設計まで、SQLの最適化を効率的に進められます。
スロークエリの分析
実行計画の読み方
> 以下のクエリが遅い原因を分析して:
> SELECT u.*, COUNT(o.id) as order_count
> FROM users u
> LEFT JOIN orders o ON u.id = o.user_id
> WHERE u.created_at > '2025-01-01'
> GROUP BY u.id
> ORDER BY order_count DESC
> LIMIT 20;
Claude Codeは実行計画(EXPLAIN ANALYZE)の結果を貼り付けると、ボトルネックを特定して改善案を提示してくれます。
-- 改善後:必要なカラムのみ選択、インデックス活用
SELECT
u.id,
u.name,
u.email,
COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at > '2025-01-01'
GROUP BY u.id, u.name, u.email
ORDER BY order_count DESC
LIMIT 20;
-- 推奨インデックス
CREATE INDEX idx_users_created_at ON users(created_at);
CREATE INDEX idx_orders_user_id ON orders(user_id);
インデックス設計
複合インデックスの最適化
> 以下の検索条件に最適なインデックスを設計して:
> - status + created_at での範囲検索
> - category + price でのフィルター + ソート
-- 等価条件を先、範囲条件を後に配置
CREATE INDEX idx_products_status_created
ON products(status, created_at DESC);
-- カバリングインデックスで追加のテーブルアクセスを回避
CREATE INDEX idx_products_category_price
ON products(category, price)
INCLUDE (name, description);
Claude Codeは「カーディナリティの高いカラムを先にする」「範囲検索カラムはインデックスの末尾にする」といった設計原則も合わせて説明してくれます。
N+1問題の検出と解消
> このORMコードにN+1問題がないか確認して:
// N+1問題あり
const users = await prisma.user.findMany();
for (const user of users) {
const orders = await prisma.order.findMany({
where: { userId: user.id },
});
}
// 改善後:includeで一括取得
const users = await prisma.user.findMany({
include: {
orders: true,
},
});
ウィンドウ関数の活用
複雑な集計やランキングクエリは、ウィンドウ関数を使うことでサブクエリより効率的に記述できます。
-- 各カテゴリ内での売上ランキング
SELECT
product_name,
category,
revenue,
RANK() OVER (PARTITION BY category ORDER BY revenue DESC) as rank,
SUM(revenue) OVER (PARTITION BY category) as category_total
FROM product_sales;
パーティショニング
大量データのテーブルにはパーティショニングも有効です。Claude Codeに「このテーブルを月ごとにパーティション分割して」と依頼すると、適切なパーティション戦略を提案してくれます。
Summary
Claude Codeを使えば、SQLクエリのボトルネック分析からインデックス設計、ORMレベルでの最適化まで一貫して改善できます。データベースマイグレーションやPrisma ORM活用も合わせて参考にしてください。
SQLパフォーマンスの詳細はUse The Index, Lukeを参照してください。
Related Posts
How to Supercharge Your Side Projects with Claude Code [With Examples]
How to Supercharge Your Side Projects with Claude Code [With Examples]. A practical guide with code examples.
How to Automate Refactoring with Claude Code
Learn how to automate refactoring using Claude Code. Includes practical code examples and step-by-step guidance.
Complete CORS Configuration Guide with Claude Code
Learn about complete cors configuration guide using Claude Code. Practical tips and code examples included.