AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How Database Engineers Use JetBrains AI in DataGrip to Optimize Slow SQL, Translate Dialects, and Explain Execution Plans

Daly Zaloom · 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

Tuning relational databases, resolving slow queries, and migrating SQL across database engines often force database administrators (DBAs) and backend engineers into tedious manual labor. When a critical production query stalls under deep subqueries and multi-table joins, or when migrating thousands of lines of MySQL queries to PostgreSQL or Snowflake, standard LLMs running in a browser tab fall short. Generic web chats lack your schema metadata, know nothing about your table constraints, cannot see your indexing topology, and pose grave data leakage risks.

At 365Finds, our engineering judgment is clear: generic chat windows are an anti-pattern for database performance engineering; in-IDE schema-aware AI tooling is the only scalable path forward. Inside DataGrip—JetBrains’ flagship database IDE—JetBrains AI connects generative language models directly to the active database introspection engine, AST parser, and query execution analyzer.

This guide delivers an end-to-end operational blueprint for database engineers: from injecting active schema context and diagnosing opaque EXPLAIN plans with "Analyze SQL Plan with AI", to refactoring bottlenecked SQL statements and safely translating dialects without leaving DataGrip.


1. Schema Context Injection: Why Generic AI Fails and DataGrip Succeeds

The fundamental obstacle to AI-assisted SQL tuning has always been context blindness. An external LLM does not know whether orders.customer_id is indexed, whether created_at has high selectivity, or what foreign key constraints link your billing schema. Pasting DDL schemas manually into web prompts wastes context tokens and exposes corporate table designs to third-party retention risks.

In DataGrip, JetBrains AI solves this by integrating with the native Database Explorer and schema tree.

How to Inject Schema Metadata into JetBrains AI

  1. Open AI Chat: Click the AI Chat tool window icon in the header or toolbar (or select More tool windows | AI Assistant).
  2. Explicit Object Attachment via @dbObject:: In the AI Chat input box, type @dbObject: to open a quick-selection popup of your active data sources, schemas, tables, and views. Selecting an object attaches its DDL definition, columns, types, primary keys, and foreign keys directly to the prompt context.
  3. Attaching Full Schemas: Click the Attach Schema icon (Add Attachment | Database Schema) directly in the AI Chat window to bind the active database schema.
  4. Context Settings: Under Settings | Tools | AI Assistant, ensure Allow attaching database schemas to AI Assistant chat is active. DataGrip protects sensitive data by transferring only schema metadata, DDL structures, and query strings—never your internal table rows or customer records.
  5. Contextual File Association: Starting with recent releases, any SQL snippet extracted from AI Chat into a new scratchpad or console automatically inherits the attached data source and target dialect.
Prompt Pattern for Performance Tuning:
@dbObject:production.ecommerce.orders @dbObject:production.ecommerce.order_items
"We are observing latency spikes on customer order retrieval over 90-day intervals. 
Review the attached table structures, detect missing composite indexes or anti-pattern predicates, 
and suggest a rewritten query."

2. Deciphering Query Plans: "Analyze SQL Plan with AI"

Reading raw EXPLAIN or EXPLAIN ANALYZE outputs across different database engines (such as PostgreSQL JSON plans, MySQL tabular formats, or Snowflake profile trees) is exhausting. Identifying whether an expensive operation stems from a missing join index, a sequential table scan, or an inaccurate planner row estimate requires cross-referencing hundreds of lines of cost metrics.

DataGrip streamlines this diagnostic process with Analyze SQL Plan with AI.

Execution Plan Diagnosis Workflow

  1. Run the Plan: In your SQL console, place the cursor on the problematic query. Right-click and choose Explain Plan (planner estimation) or Explain Analyse (actual execution with runtime statistics in milliseconds), or use the dropdown icon on the console toolbar.
  2. Open the Query Plan Tab: The execution plan populates inside the Query Plan tab of the Services tool window, displaying the execution tree, startup cost, total cost, and row count estimations.
  3. Trigger AI Plan Inspection: On the left toolbar of the Query Plan tab, click the Analyze SQL Plan with AI button.
  4. Interactive Breakdown: JetBrains AI ingests the plan's cost numbers, join strategies, and node operators, outputting a clear, plain-language breakdown in the AI Chat window:
    • Cost Bottlenecks: Pinpoints nodes with disproportionate cost percentages (e.g., Seq Scan on a 50-million-row partition).
    • Join Inefficiencies: Identifies nested loops operating on unindexed columns that should be hash joins or merge joins.
    • Filter Predicate Leaks: Detects implicit type conversions or functions on filtered columns (e.g., WHERE DATE(created_at) = ...) that invalidate index lookups.
    • Remediation Action Items: Generates exact DDL index statements (e.g., composite B-Tree or partial indexes) and rewritten query syntax.
Plan IndicatorJetBrains AI InterpretationActionable IDE Resolution
Sequential Scan (Seq Scan) with High Total CostFull table read due to unindexed filter or low selectivity predicatePrompt AI for optimal composite index matching WHERE + ORDER BY
Nested Loop with High Loop CountPlanner chose nested loops due to missing foreign key indexAdd foreign key index or restructure query join order
Hash Aggregate / Sort Spill to DiskWorking memory exhausted; sorting or grouping spilling to temp filesPrompt AI to optimize grouping keys or split into window functions
Row Estimate Discrepancy (Rows=1 vs Actual=450,000)Outdated planner statistics misleading query optimizerSuggests ANALYZE table_name before query refactoring

3. In-Editor SQL Refactoring: Converting Slow Anti-Patterns

Database engineers routinely inherit queries burdened with anti-patterns: correlated subqueries executed row-by-row, heavy NOT IN clauses on nullable columns, and redundant Cartesian joins.

DataGrip allows you to invoke JetBrains AI directly inside the SQL query editor using contextual intentions (Alt+Enter on Windows/Linux or Option+Enter on macOS).

Step-by-Step Refactoring Workflow

  1. Highlight the inefficient query in the editor.
  2. Press Alt+Enter / Option+Enter and choose AI Actions | Suggest Refactoring or Explain Code.
  3. Select Suggest Refactoring to open a side-by-side interactive diff view showing original versus optimized SQL.

Practical Refactoring Example: Subquery to CTE & Window Function

Before (Slow Correlated Subquery & Suboptimal Join):

SELECT 
    o.id, 
    o.customer_id, 
    o.total_amount,
    (SELECT AVG(total_amount) FROM orders WHERE customer_id = o.customer_id) AS avg_cust_amount
FROM orders o
WHERE o.status = 'COMPLETED'
  AND o.id IN (
      SELECT order_id 
      FROM order_items 
      WHERE product_id IN (SELECT id FROM products WHERE category = 'Electronics')
  );

After (JetBrains AI In-Editor Refactor with Schema Context):

WITH TargetProducts AS (
    SELECT id 
    FROM products 
    WHERE category = 'Electronics'
),
EligibleOrders AS (
    SELECT DISTINCT oi.order_id
    FROM order_items oi
    INNER JOIN TargetProducts tp ON oi.product_id = tp.id
)
SELECT 
    o.id,
    o.customer_id,
    o.total_amount,
    AVG(o.total_amount) OVER(PARTITION BY o.customer_id) AS avg_cust_amount
FROM orders o
INNER JOIN EligibleOrders eo ON o.id = eo.order_id
WHERE o.status = 'COMPLETED';

Why this matters: Replacing the correlated subquery with an analytical OVER (PARTITION BY ...) eliminates repetitive index seeks. Replacing IN (SELECT ...) with an explicit INNER JOIN against an early-filtered Common Table Expression (CTE) allows the database planner to utilize hash joins efficiently.


4. Cross-Dialect SQL Translation: Moving Across Engines Safely

Database migrations—such as transitioning legacy services from MySQL to PostgreSQL, or porting transactional data into Snowflake or BigQuery—often stall over syntactic and semantic discrepancies. Small variations in dialect rules can introduce silent data corruption or execution runtime errors.

When translating queries with JetBrains AI in DataGrip, the engine considers target dialect quirks and constraints automatically.

Key Cross-Dialect Pitfalls Handled by JetBrains AI

Cross-Dialect Translation Example: MySQL to PostgreSQL

MySQL Source Query:

INSERT INTO user_analytics (user_id, login_count, last_login)
VALUES (101, 1, NOW())
ON DUPLICATE KEY UPDATE
    login_count = login_count + 1,
    last_login = VALUES(last_login);

PostgreSQL Target Query Generated by JetBrains AI:

INSERT INTO user_analytics (user_id, login_count, last_login)
VALUES (101, 1, CURRENT_TIMESTAMP)
ON CONFLICT (user_id) DO UPDATE
SET 
    login_count = user_analytics.login_count + 1,
    last_login = EXCLUDED.last_login;

Engineering review: JetBrains AI recognizes that PostgreSQL requires an explicit unique target constraint (user_id) in ON CONFLICT and uses the special EXCLUDED virtual table rather than MySQL’s VALUES() function.


5. Security, Token Hygiene, and Operational Best Practices

When operating AI within enterprise database infrastructure, technical rigor is paramount. 365Finds recommends adhering to the following production rules:

  1. Verify Statistics Before Refactoring: AI cannot compensate for stale planner statistics. If the execution plan shows large discrepancies between expected and actual row counts, execute ANALYZE or VACUUM ANALYZE before altering query structure.
  2. Do Not Attach Raw Data: Rely strictly on schema metadata. JetBrains AI in DataGrip does not upload your table content by default. Never paste real customer rows, API keys, or proprietary data into the AI Chat.
  3. Inspect Generated DDL in "Modify Table": When prompting AI to generate table alterations or add composite indexes via DataGrip's Modify Table dialog, review the generated DDL in the preview pane before applying it against staging or production environments.
  4. Use Side-by-Side Diff Reviews: When accepting AI refactoring suggestions, never overwrite queries blindly. Always use DataGrip's split diff viewer to confirm that nullability handling, sorting stability, and join semantics remain identical.

365Finds Recommendation & Final Verdict

For database engineers, DBAs, and backend data architects, JetBrains AI in DataGrip is the premier choice for integrated database performance tuning. While standalone LLMs require dangerous copy-pasting of sensitive DDLs and lack execution plan integration, DataGrip unifies schema introspection, graphical query plans, and in-editor AI refactoring into a coherent workstation.

Adopt "Analyze SQL Plan with AI" as your default diagnostic tool for slow queries, attach schema objects via @dbObject: to ensure grounded query generation, and leverage side-by-side diffs to validate dialect migrations. This workflow reduces query tuning time from hours of manual guesswork to minutes of structured, verified engineering.


References