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/SQL/What is the difference between WHERE and HAVING clauses in SQL?

What is the difference between WHERE and HAVING clauses in SQL?

SQLmedium2 min read

Reviewed by Aditya Kumar · Last reviewed 2026-03-24

The WHERE and HAVING clauses both filter data in SQL, but they operate at different stages of query execution and on different types of data. WHERE filters individual rows before any grouping or…

🤖 Analyze Your Answer
Frequency
Low
Asked at 4 companies
Category
487
questions in SQL
Difficulty Split
130E|271M|86H
in this category
Total Bank
1,863
across 7 categories
Asked at these companies
AccentureCognizantEPAMYash Technologies
Interview Pro Tip

Red Flag: Using HAVING for non-aggregate conditions (e.g., HAVING status = 'active')—belongs in WHERE. Pro-Move: Say you push filters to WHERE first, and use HAVING only for aggregate conditions (e.g., HAVING COUNT(*) > 1).

Key Concepts Tested
sql

Why This Question Matters

This medium-level SQL question appears frequently in data engineering interviews at companies like Accenture, Cognizant, EPAM, and 1 others. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (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
396 wordsIncludes code

The WHERE and HAVING clauses both filter data in SQL, but they operate at different stages of query execution and on different types of data.

WHERE filters individual rows before any grouping or aggregation takes place. It cannot reference aggregate functions. In contrast, HAVING filters groups of rows after they have been grouped and aggregated, and it is specifically used to filter based on the results of aggregate functions.

Mechanics and Why it Matters

SQL queries generally follow a logical processing order: FROM -> JOIN -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY.
  • WHERE Clause: Applied early in the process, it evaluates conditions on individual rows produced by FROM and JOIN clauses. This means WHERE predicates operate on the raw, unaggregated column values. Since aggregation hasn't occurred yet, you cannot use functions like SUM(), COUNT(), or AVG() in a WHERE clause.
  • HAVING Clause: Applied later, after GROUP BY has formed groups and aggregate functions have computed values for each group. HAVING then filters these resulting groups based on conditions that often involve aggregate function outputs.
  • Performance and Scalability

    Understanding this distinction is crucial for query performance and cost efficiency, especially in data engineering contexts. Early Filtering with WHERE: Filtering rows with WHERE reduces the dataset size before* potentially expensive operations like GROUP BY and aggregation. This minimizes the amount of data that needs to be processed, shuffled (e.g., in Spark), or scanned (e.g., from Snowflake micro-partitions). Fewer rows mean less I/O, less memory usage, and faster computation, directly impacting query execution time and cloud compute costs. * Late Filtering with HAVING: HAVING operates on the (potentially much smaller) set of groups. While necessary for aggregate conditions, if a condition could have been applied earlier with WHERE, applying it with HAVING means the aggregation engine still had to process all the initial rows to form the groups, which can be inefficient. Always prefer WHERE when possible to reduce data volume early.

    Example

    SELECT
        customer_id,
        SUM(order_total) AS total_spent,
        COUNT(order_id) AS num_orders
    FROM
        orders
    WHERE
        order_date >= '2023-01-01' -- Filters individual orders before grouping
    GROUP BY
        customer_id
    HAVING
        SUM(order_total) > 1000 AND COUNT(order_id) > 5; -- Filters groups based on aggregates
    

    In the interview, also mention that misplacing predicates can lead to incorrect results or significantly degrade performance, making this a fundamental concept for optimizing data pipelines.

    ⚡
    Pro Tip

    Red Flag: Using HAVING for non-aggregate conditions (e.g., HAVING status = 'active')—belongs in WHERE. Pro-Move: Say you push filters to WHERE first, and use HAVING only for aggregate conditions (e.g., HAVING COUNT(*) > 1).

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

    SQL Window Functions & CTEs: The Complete Interview Guide for Data Engineers (2026)

    Window functions and CTEs are the #1 tested SQL topics at Amazon, Google, and Databricks. This guide covers every pattern you'll face with production-ready answers.

    18 min read →

    Related SQL Questions

    mediumWrite an SQL query to find the second-highest salary from an employee table.FreemediumDemonstrate the difference between DENSE_RANK() and RANK()FreemediumDiscuss differences between ROW_NUMBER(), RANK(), and DENSE_RANK(), and provide examples from your projects.FreemediumExplain the differences between Data Warehouse, Data Lake, and Delta LakeFreemediumExplain the differences between Repartition and Coalesce. When would you use each?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 SQL interview questions, reported at 4 companies. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

    ← Back to all questionsMore SQL 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