Essential cookies keep authentication working. With your permission, we also use analytics cookies to understand and improve the product. Read our Privacy Policy

DataEngPrep.tech
QuestionsPracticeAI CoachDashboardPricingBlog
ProLogin
Home/Questions/General/Other/How would you optimize a slow-running SQL query?

How would you optimize a slow-running SQL query?

General/Othermedium2 min read

Reviewed by Aditya Kumar · Last reviewed 2026-08-08

To optimize a slow SQL query, I'd systematically analyze its execution plan to identify bottlenecks, then apply targeted improvements like indexing, query refactoring, and leveraging database features…

🤖 Analyze Your Answer
Frequency
Low
Asked at 1 company
Category
243
questions in General/Other
Difficulty Split
151E|43M|49H
in this category
Total Bank
1,863
across 7 categories
Asked at these companies
Wipro
Key Concepts Tested
joinpartitionsql

Why This Question Matters

This medium-level General/Other question appears frequently in data engineering interviews at companies like Wipro. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (join, partition, sql) will help you answer variations of this question confidently.

How to Approach This

Break this problem into components. Identify the core trade-offs involved, then walk the interviewer through your reasoning step by step. Demonstrate awareness of edge cases and production considerations - this is what separates good answers from great ones. The expert answer includes a code example that demonstrates the implementation pattern.

Expert Answer
386 wordsIncludes code

To optimize a slow SQL query, I'd systematically analyze its execution plan to identify bottlenecks, then apply targeted improvements like indexing, query refactoring, and leveraging database features such as partitioning, always measuring performance before and after changes.

Optimization Steps

  • Analyze Execution Plan (EXPLAIN / EXPLAIN ANALYZE): This is the crucial first step. It reveals how the database executes the query, highlighting expensive operations like full table scans, large sorts, and inefficient joins.
  •     EXPLAIN ANALYZE SELECT user_name, order_total FROM users u JOIN orders o ON u.user_id = o.user_id WHERE u.registration_date > '2023-01-01';
        
  • Indexing: Create indexes on columns frequently used in WHERE clauses, JOIN conditions, ORDER BY, and GROUP BY clauses. Indexes allow the database to quickly locate relevant rows without scanning the entire table. Consider composite indexes for multi-column filters.
  • Statistics: Ensure database statistics are up-to-date (UPDATE STATISTICS). The query optimizer relies on these to estimate data distribution and cardinality, making informed decisions about the most efficient execution plan.
  • Query Refactoring:
  • * EXISTS vs IN: For subqueries, EXISTS can often be more performant than IN because EXISTS stops processing upon finding a match. * CTEs vs Subqueries: While CTEs improve readability, their performance relative to subqueries can vary by database optimizer. Avoid SELECT : Explicitly select only necessary columns to reduce data transfer and processing.
  • Partitioning and Clustering: For large tables, partition data based on frequently filtered columns (e.g., date). This enables "partition pruning," where the database only scans relevant partitions. Systems like Snowflake use micro-partitions and clustering keys for similar benefits.
  • Join Order and Types: The optimizer usually determines the best join order. However, sometimes rewriting queries to join smaller, filtered datasets first can improve performance.
  • Concrete Example & Trade-offs

    If a query joining users and orders tables on user_id is slow, an EXPLAIN plan might show a full table scan on orders. Creating an index on orders.user_id would be a primary optimization.

    It's crucial to measure performance before and after each change and focus on the biggest bottleneck first. While indexing is powerful, avoid over-indexing as it increases write operation costs (inserts, updates, deletes) and storage overhead, and can sometimes confuse the optimizer.

    In the interview, also mention: The iterative nature of optimization, emphasizing that it's a process of identifying, implementing, and validating changes.

    ⚡
    Pro Tip

    Red Flag: 'Add more indexes' without analysis. Pro-Move: 'EXPLAIN showed seq scan on 10M rows. Index on (user_id, date). Query 10s -> 200ms. Measured with EXPLAIN ANALYZE.'

    Want all answers as a PDF for offline study?
    Seven focused volumes with 750+ in-depth answers — Answer Vault →

    Related General/Other Questions

    hardHave you worked on Data Warehousing projects?FreemediumHow would you read data from a web API? What steps would you follow after reading the data?FreehardRetrieve the most recent sale_timestamp for each product (Latest Transaction).FreehardWhat is the difference between OLTP and OLAP?FreemediumWhat is the difference between SQL and NoSQL databases?Free

    Level up your prep

    Recommended
    Educative
    Educative Unlimited

    800+ hands-on courses — Grokking System Design, Coding Patterns, and AI mock interviews for your DE loop.

    Start learning →

    Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you — it helps keep DataEngPrep free.

    According to DataEngPrep.tech, this is one of the most frequently asked General/Other interview questions, reported at 1 company. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

    ← Back to all questionsMore General/Other questions →
    Categories
    All QuestionsSQLSpark / Big DataPython / CodingSystem DesignCloud / ToolsBehavioral
    By Company
    AmazonGoogleDatabricksSnowflakeAWSAzureMicrosoftNetflixUberTCS
    Interview Guides
    All GuidesTop SQL QuestionsTop Spark QuestionsPySpark QuestionsTop Python QuestionsTop System DesignKafka QuestionsAirflow QuestionsSQL Window FunctionsETL QuestionsData Modeling
    Products
    AI Interview CoachAnswer AnalyzerSQL PlaygroundResume AnalyzerAnswer Vault PDFsPricing
    Company
    About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
    © 2026 DataEngPrep.tech. All rights reserved.
    AboutBlogContactDisclaimer