AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How Database Developers and Data Analysts Use JetBrains AI Assistant in DataGrip to Optimize Complex SQL Queries and Explain Execution Plans

江野雄太 · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Complex enterprise databases rarely suffer from syntax errors; they suffer from silent, compounding performance degradation. A query spanning sixty lines—nested with multiple subqueries, defensive LEFT JOIN clauses, and dynamic date filters—can execute seamlessly in a staging environment with ten thousand rows, only to choke production clusters under millions of records.

For backend software engineers, database administrators (DBAs), and data analysts working inside JetBrains DataGrip, diagnosing these bottlenecks has historically been an uphill battle. Reading native database execution plans (EXPLAIN and EXPLAIN ANALYZE) requires parsing dense textual JSON/XML trees or untangling complex visual node graphs. Meanwhile, copy-pasting queries into external web-based LLMs fails because public chatbots lack database schema awareness: they do not know your table cardinalities, existing primary and foreign keys, or available indexes, leading to hallucinations and unexecutable tuning advice.

At 365Finds, our operational benchmark is clear: optimizing production SQL requires contextual coupling between the IDE's schema introspection engine and deep AI reasoning. JetBrains AI, embedded directly into DataGrip, bridges this gap. By combining real-time metadata awareness with native execution plan visualization, JetBrains AI Assistant transforms SQL tuning from speculative guesswork into an automated, closed-loop diagnostic workflow.


1. The Context Engine: Why Schema Awareness Changes SQL Optimization

Generic LLMs fail at database tuning because SQL optimization is an environmental science. An index recommendation that works brilliantly on a table with 5,000 rows can degrade write throughput catastrophically on a table with 50 million rows.

JetBrains AI Assistant inside DataGrip succeeds because it operates on top of DataGrip's Schema Introspection system:

  1. Introspection Levels and Metadata Binding: DataGrip automatically scans and indexes database objects (tables, columns, data types, constraints, and index definitions). In recent releases (such as DataGrip 2025.2 and 2025.3), introspection by levels scales metadata retrieval for massive enterprise databases like PostgreSQL, Microsoft SQL Server, and Amazon Redshift without freezing IDE memory.
  2. Granular Context Injection (@dbObject): Instead of dumping an entire database catalog into prompt memory, developers can inject specific contextual objects directly into the AI Chat using the @dbObject: or #dbObject: mention syntax (e.g., @dbObject:orders, @dbObject:order_items).
  3. Bundled Agent Skills: DataGrip provides built-in agent skills—including database-tools, database-text-to-sql, and database-connection-management—empowering JetBrains AI to introspect schemas, verify column relationships, and inspect data distributions safely.

Because the AI Assistant understands table schemas, nullability, and foreign key hierarchies before analyzing a statement, its recommendations match the actual database dialect (PostgreSQL, MySQL, Oracle, SQL Server, or Snowflake) rather than generic ANSI SQL approximations.


2. Generating and Understanding Execution Plans: EXPLAIN vs. EXPLAIN ANALYZE

Before prompting AI for query rewrites, developers must capture how the database query optimizer evaluates the query. DataGrip centralizes this via the Explain Plan dropdown on the code editor toolbar or context menu.

Choosing the Right Diagnostic Mode

Diagnostic ActionExecution BehaviorOutput MetricsIdeal Scenario365Finds Recommendation
Explain PlanPlans the query only; does not execute against live rowsEstimated Startup Cost; Estimated Total Cost; Planned Operator NodesProduction read/write queries; long-running analytical batchesUse on production instances to inspect estimated plan trees without resource lockups or side effects.
Explain AnalyseActually executes the statement against the database engineReal execution time in milliseconds; Actual row counts vs. Estimated row counts; Buffer hitsStaging environments; read-only production queries with predictable boundariesEssential when diagnosing optimizer estimation errors caused by stale table statistics.
-- Example: A bloated reporting query with correlated subqueries and non-SARGable filters
SELECT 
    c.customer_id,
    c.company_name,
    (SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.customer_id AND o.status = 'COMPLETED') AS completed_orders,
    SUM(oi.unit_price * oi.quantity) AS total_revenue
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
LEFT JOIN order_items oi ON o.order_id = oi.order_id
WHERE DATE(o.created_at) >= '2026-01-01'
  AND c.country = 'Germany'
GROUP BY c.customer_id, c.company_name;

Visualizing the Bottleneck in DataGrip

When triggered, the plan renders in the Query Plan tab of the Services tool window:


3. One-Click AI Plan Diagnosis: "Analyze SQL Plan with AI"

Once the execution plan is populated in the Query Plan tab, deciphering nested join algorithms and cost anomalies does not require scouring database manual pages.

Step-by-Step AI Plan Inspection

  1. In the Services tool window's Query Plan tab, locate the left vertical toolbar.
  2. Click the dedicated button: Analyze SQL Plan with AI.
  3. DataGrip automatically packages the plan's operator tree, cost estimations, and attached schema metadata, opening the AI Chat tool window with an immediate architectural breakdown.
+-----------------------------------------------------------------------------------+
| DataGrip Services Tool Window -> [Query Plan] Tab                                  |
|                                                                                   |
| [Analyze SQL Plan with AI]  <-- Click button on left toolbar                      |
|                                                                                   |
| Tree: -> Hash Aggregate                                                          |
|         -> Nested Loop (Cost: 18450.00..45230.00)                                |
|           -> Seq Scan on orders o (Filter: DATE(created_at) >= '2026-01-01')      |
|                                                                                   |
| ==> AI Chat automatically opens with:                                             |
|     1. Root Cause Identification (e.g., Seq Scan caused by DATE() function)     |
|     2. Cost Spikes (Nested Loop performing N * M iterations)                     |
|     3. Actionable remediation roadmap                                             |
+-----------------------------------------------------------------------------------+

What JetBrains AI Detects in the Plan


4. In-Editor Query Refactoring and Automated Optimization

Understanding the bottleneck is only half the battle. Developers must rewrite the SQL without altering the business logic or result set.

DataGrip allows direct code refactoring via context-aware AI actions:

Executing "Optimize Query with AI"

  1. In the query console, place the caret inside the query or highlight the SQL block.
  2. Right-click and navigate to AI Actions | Optimize Query with AI (or press Alt + Enter and select the AI action).
  3. JetBrains AI reviews the SQL alongside the execution plan and schema context, returning a refactored query with line-by-line performance rationale.

The Refactored SQL Output

Applying AI optimization to our sample query eliminates the correlated subquery, removes the redundant join on orders, and restores predicate SARGability (Search Argument Ability):

-- AI-Optimized Query: Pre-aggregated CTE + Direct Date Range Comparison
WITH completed_order_metrics AS (
    SELECT 
        o.customer_id,
        COUNT(DISTINCT o.order_id) AS completed_orders,
        SUM(oi.unit_price * oi.quantity) AS total_revenue
    FROM orders o
    JOIN order_items oi ON o.order_id = oi.order_id
    WHERE o.status = 'COMPLETED'
      -- SARGable date filter: Allows B-tree index seeks
      AND o.created_at >= '2026-01-01 00:00:00'
      AND o.created_at < '2027-01-01 00:00:00'
    GROUP BY o.customer_id
)
SELECT 
    c.customer_id,
    c.company_name,
    COALESCE(m.completed_orders, 0) AS completed_orders,
    COALESCE(m.total_revenue, 0.00) AS total_revenue
FROM customers c
LEFT JOIN completed_order_metrics m ON c.customer_id = m.customer_id
WHERE c.country = 'Germany';

Architectural Changes Explained by JetBrains AI

  1. Elimination of Correlated Subquery: Moving the COUNT(*) subquery into a Common Table Expression (CTE) aggregates order counts once across the dataset rather than executing a distinct sub-select for every single customer record ($O(1)$ batch vs. $O(N)$ row-by-row iteration).
  2. Predicate SARGability: Replacing DATE(o.created_at) >= '2026-01-01' with direct range boundaries (o.created_at >= ... AND o.created_at < ...) allows the engine to perform an Index Range Scan instead of evaluating a function over millions of rows during a full table scan.
  3. Join Redundancy Reduction: In the original query, joining orders twice (once in the main query and once in the subquery) produced cartesian multiplication before grouping. The pre-aggregated CTE reduces the join volume by several orders of magnitude.

5. Precision Index Recommendations: Avoiding Index Sprawl

A common trap in SQL tuning is creating single-column indexes on every field in the WHERE clause. This practice bloats storage, degrades write throughput during INSERT and UPDATE operations, and rarely satisfies multi-column predicates.

Because JetBrains AI Assistant inspects DataGrip’s active schema metadata, it does not suggest indexes that already exist or clash with existing primary keys. It generates composite index DDL tailored to the optimizer's access paths:

-- Precision composite index suggested by JetBrains AI Assistant
-- Order: Equality filters first, range filters second, covering columns included
CREATE INDEX idx_orders_customer_status_created 
ON orders (customer_id, status, created_at)
INCLUDE (order_id);

-- Supporting index for order item aggregation
CREATE INDEX idx_order_items_order_id_covering
ON order_items (order_id)
INCLUDE (unit_price, quantity);

Why This Index Structure Works


6. Closing the Loop: Verification and Performance Benchmarking

Tuning is never complete until the metrics confirm the improvement. At 365Finds, we insist on a strict four-step verification cycle directly within DataGrip:

flowchart LR
    A["Original Query\n(Explain Plan)"] --> B["AI Assistant\nDiagnosis"]
    B --> C["SQL Refactor &\nIndex DDL"]
    C --> D["Smart Introspection\nRefresh"]
    D --> E["Re-Run Explain Analyse\n(Cost & Latency Drop)"]
  1. Apply DDL: Execute index creation in the DataGrip query console.
  2. Refresh Metadata: Run a smart introspection refresh on the data source so DataGrip and AI Assistant register the new indexes immediately.
  3. Re-Run Explain Plan / Explain Analyse: Trigger the plan comparison.
  4. Compare Metrics: Verify that the execution plan shifted from Seq Scan to Index Only Scan or Bitmap Index Scan, and confirm that total cost units and execution time in milliseconds dropped significantly.

7. Operational Best Practices and Critical Boundaries

While JetBrains AI Assistant provides unmatched convenience, enterprise database administration requires operational discipline:

By combining DataGrip's deep schema introspection with JetBrains AI Assistant's contextual reasoning, developers and analysts can transform sluggish, sprawling SQL queries into hardened, high-performance database statements—without ever leaving their IDE.


References