Use Cases (अपडेट: 1/6/2026)

Claude Code से SQL Optimization: धीमी Query से Rollout तक

Claude Code से SQL optimization करें: slow query, EXPLAIN, index, N+1, pagination, aggregation, tests और rollout checklist.

Claude Code से SQL Optimization: धीमी Query से Rollout तक

SQL optimization का असली मतलब

SQL optimization का मतलब है query, index और data access pattern को इस तरह ठीक करना कि वही result कम पढ़ाई और कम waiting time में लौटे। यह सिर्फ SQL को छोटा या चतुर बनाना नहीं है। व्यवहार में आपको endpoint code, ORM calls, execution plan, production जैसे data volume, regression tests और rollout के बाद monitoring को साथ में देखना पड़ता है।

Claude Code उपयोगी है क्योंकि यह सिर्फ SQL string नहीं, बल्कि route handler, Prisma या दूसरे ORM model, migrations, slow-query logs और tests को साथ पढ़ सकता है। असली systems में latency अक्सर एक कठिन query से नहीं आती। यह कई छोटे patterns से बनती है: list page पर SELECT *, N+1 loop, गहरी OFFSET pagination, query से mismatch composite index, और dashboard aggregation जो हर request पर synchronous चलती है।

यह guide PostgreSQL को मुख्य उदाहरण मानती है, पर कई बातें MySQL पर भी लागू होती हैं। Execution plan पढ़ते समय official docs भी देखें: PostgreSQL Using EXPLAIN, PostgreSQL EXPLAIN, PostgreSQL Indexes, PostgreSQL Multicolumn Indexes, और MySQL 8.4 Using EXPLAIN

Related पढ़ाई के लिए database design, database migration, Prisma ORM, और performance optimization देखें।

तीन practical use cases

पहले screen या workflow तय करें। इससे Claude Code को generic index advice देने के बजाय सही जगह सुधार करने का context मिलता है।

Use caseSymptomMain fixRisk
Admin list pagesearch slow है, deep page slow हैcomposite index, keyset pagination, fewer selected columnsoptional filters बहुत ज्यादा हों तो index sprawl होता है
SaaS या ecommerce pagetraffic बढ़ते ही list API slow हो जाती हैWHERE और ORDER BY से match index, cache, async aggregationtenant, stock या permission filter हटना खतरनाक है
Dashboarddaily/monthly chart बड़ी table scan करता हैsummary table, materialized view, scheduled refreshdata freshness पहले तय करनी होगी

Code बदलने से पहले query budget रखें: जैसे p95 300ms से कम, list request में अधिकतम 5 SQL statements, और response JSON compatible रहे।

Claude Code prompt:
इस list API की SQL performance optimize करें।
Goal: p95 300ms से कम, max 5 SQL statements, response JSON unchanged.
Review: src/routes/admin/orders.ts, prisma/schema.prisma, migrations, slow-query.log.
Do: slow SQL identify करें, EXPLAIN ANALYZE पढ़ें, index proposal दें, N+1 हटाएं, regression tests जोड़ें।
Constraint: change scoped रहे और production compatibility न टूटे।

Step 1: slow query capture करें

Guess करके index न बनाएं। पहले असली slow SQL capture करें। PostgreSQL में pg_stat_statements या database logs useful हैं। ORM logs भी जरूरी हैं क्योंकि वे SQL को calling endpoint से जोड़ते हैं।

CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

SELECT
  query,
  calls,
  ROUND(total_exec_time::numeric, 2) AS total_ms,
  ROUND(mean_exec_time::numeric, 2) AS mean_ms,
  rows
FROM pg_stat_statements
WHERE query NOT ILIKE '%pg_stat_statements%'
ORDER BY total_exec_time DESC
LIMIT 10;

Prisma में development environment के लिए real Prisma Client API से slow query log कर सकते हैं:

import { PrismaClient } from "@prisma/client";

export const prisma = new PrismaClient({
  log: [
    { emit: "event", level: "query" },
    { emit: "stdout", level: "error" },
    { emit: "stdout", level: "warn" },
  ],
});

prisma.$on("query", (event) => {
  if (event.duration > 100) {
    console.log({
      durationMs: event.duration,
      query: event.query,
      params: event.params,
    });
  }
});

Claude Code को sanitized logs दें। Email, token और customer identifier mask करें। फिर कहें कि वह screen, caller, average time, call count और suspected cause के हिसाब से SQL patterns group करे।

Step 2: EXPLAIN और EXPLAIN ANALYZE पढ़ें

Candidate query मिलने के बाद EXPLAIN से planned execution देखें। Safe environment और representative data हो तो EXPLAIN (ANALYZE, BUFFERS) चलाएं। ध्यान रखें, ANALYZE query को सच में execute करता है, इसलिए UPDATE या DELETE पर सावधानी जरूरी है।

EXPLAIN (ANALYZE, BUFFERS)
SELECT
  o.id,
  o.created_at,
  o.status,
  c.name AS customer_name
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'paid'
  AND o.created_at >= DATE '2026-01-01'
ORDER BY o.created_at DESC, o.id DESC
LIMIT 50;

हर Seq Scan bug नहीं होता। छोटी table या low-selectivity condition में sequential scan सही हो सकता है। ज्यादा ध्यान दें: estimated rows और actual rows का gap, बड़ा sort, बहुत ज्यादा buffer reads, और unexpected join order।

Claude Code prompt:
इस EXPLAIN ANALYZE को review करें। Answer को bottleneck, row-estimate mismatch, index candidates और safe SQL rewrites में बांटें। Result set बदलना नहीं है।

Step 3: composite index design करें

Index reads को तेज करता है, लेकिन writes, storage और migration risk बढ़ाता है। Real queries से design करें: equality predicates, range predicates, sort columns, फिर join needs।

CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_orders_status_created_id
  ON orders (status, created_at DESC, id DESC);

CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_orders_customer_created
  ON orders (customer_id, created_at DESC);

PostgreSQL में CREATE INDEX CONCURRENTLY write blocking कम करता है, लेकिन normal transaction block में नहीं चल सकता। Migration tool इसे कैसे run करेगा, PR में साफ लिखें।

Claude Code से index suggestion मांगने से पहले existing indexes दें:

SELECT
  indexname,
  indexdef
FROM pg_indexes
WHERE schemaname = 'public'
  AND tablename = 'orders'
ORDER BY indexname;

Step 4: N+1 हटाएं

N+1 तब होता है जब पहले list fetch होती है और फिर हर row के लिए related data अलग से fetch होता है। इससे database work और network wait दोनों बढ़ते हैं।

// खराब: हर order के लिए अलग customer query
const orders = await prisma.order.findMany({
  take: 100,
  orderBy: { createdAt: "desc" },
});

const rows = [];
for (const order of orders) {
  const customer = await prisma.customer.findUnique({
    where: { id: order.customerId },
  });
  rows.push({ ...order, customerName: customer?.name ?? "" });
}
// बेहतर: UI को चाहिए वही columns एक साथ fetch करें
const orders = await prisma.order.findMany({
  take: 100,
  orderBy: { createdAt: "desc" },
  select: {
    id: true,
    createdAt: true,
    status: true,
    totalAmount: true,
    customer: {
      select: {
        id: true,
        name: true,
      },
    },
  },
});

Claude Code से कहें कि response shape बचाते हुए query count कम करे। इससे वह UI या serializer पढ़ेगा, सिर्फ बड़ा include नहीं जोड़ेगा।

Step 5: deep OFFSET को keyset pagination से बदलें

OFFSET 10000 LIMIT 50 धीमा होता जाता है क्योंकि database skipped rows से होकर गुजरता है। Timeline, order list और infinite scroll के लिए last seen created_at और id cursor बनाएं।

SELECT id, created_at, status, total_amount
FROM orders
WHERE status = 'paid'
ORDER BY created_at DESC, id DESC
LIMIT 50;

SELECT id, created_at, status, total_amount
FROM orders
WHERE status = 'paid'
  AND (created_at, id) < (TIMESTAMP '2026-05-01 10:30:00', 98765)
ORDER BY created_at DESC, id DESC
LIMIT 50;

इस pattern के लिए (status, created_at DESC, id DESC) index अच्छा match है। id tie-breaker है ताकि same timestamp वाली rows की ordering stable रहे।

Step 6: aggregation को hot request से अलग करें

Dashboard slow होता है जब हर request वही totals फिर से calculate करती है। अगर business थोड़ी delay accept कर सकता है, तो summary table या scheduled refresh इस्तेमाल करें।

CREATE TABLE IF NOT EXISTS daily_sales_summary (
  sales_date date PRIMARY KEY,
  order_count integer NOT NULL,
  revenue numeric(12, 2) NOT NULL,
  updated_at timestamptz NOT NULL DEFAULT now()
);

INSERT INTO daily_sales_summary (sales_date, order_count, revenue)
SELECT
  created_at::date AS sales_date,
  COUNT(*) AS order_count,
  SUM(total_amount) AS revenue
FROM orders
WHERE status = 'paid'
  AND created_at >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY created_at::date
ON CONFLICT (sales_date) DO UPDATE
SET
  order_count = EXCLUDED.order_count,
  revenue = EXCLUDED.revenue,
  updated_at = now();

Claude Code को data freshness साफ बताएं: one minute, five minutes, daily या strict realtime. वरना optimization dashboard के business meaning को बदल सकती है।

Query budget और regression tests

Optimization बाद में regress हो सकती है। Exact execution plan snapshot brittle होता है; पहले query count, response compatibility और representative cases test करें।

import { PrismaClient } from "@prisma/client";
import { expect, it } from "vitest";

it("keeps the order list within the query budget", async () => {
  const queries: string[] = [];
  const prisma = new PrismaClient({
    log: [{ emit: "event", level: "query" }],
  });

  prisma.$on("query", (event) => {
    queries.push(event.query);
  });

  await prisma.order.findMany({
    take: 50,
    orderBy: [{ createdAt: "desc" }, { id: "desc" }],
    select: {
      id: true,
      createdAt: true,
      status: true,
      customer: { select: { id: true, name: true } },
    },
  });

  await prisma.$disconnect();
  expect(queries.length).toBeLessThanOrEqual(2);
});

Workflow map

flowchart LR
  A["Slow query log"] --> B["EXPLAIN / EXPLAIN ANALYZE"]
  B --> C["Index और SQL changes"]
  C --> D["N+1, pagination, aggregation fixes"]
  D --> E["Query budget tests"]
  E --> F["Rollout और monitoring"]

Common pitfalls

  • List page पर SELECT * से बड़े columns पढ़ना।
  • सिर्फ low-cardinality column जैसे status पर index बनाकर बड़ा सुधार उम्मीद करना।
  • Normal B-tree index से LIKE '%keyword%' तेज करने की कोशिश करना।
  • छोटे development data पर production plan judge करना।
  • Peak traffic में index migration चलाना और locks, disk, replica lag न देखना।
  • ORM include से पूरा relation graph return करना।

Rollout checklist

1. Endpoint और user-facing screen identify हुआ।
2. Slow SQL logs या pg_stat_statements से capture हुआ।
3. Before/after EXPLAIN save हुआ।
4. Existing indexes check हुए।
5. N+1, OFFSET, selected columns और synchronous aggregation review हुए।
6. Response compatibility test हुई।
7. Query count या latency regression check जुड़ा।
8. Index change के lock risk, runtime और rollback documented हैं।
9. Release के बाद देखने वाले metrics तय हैं।

SQL optimization एक workflow है, one-line trick नहीं। Claude Code code, migrations और tests को जोड़ सकता है, लेकिन final decision real data, execution plans और product requirements पर आधारित होना चाहिए।

ClaudeCodeLab ऐसे practical review पर आधारित training और consultation देता है। Slow endpoint, logs और schema लेकर आएं, तो आपकी team के लिए repeatable SQL optimization checklist बनाई जा सकती है।

#Claude Code #SQL #database #performance #optimization
मुफ़्त

मुफ़्त PDF: Claude Code cheatsheet

Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.

हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.

Masa

लेखक के बारे में

Masa

Claude Code workflow और team adoption पर काम करने वाला engineer.