CertSafari
    Databricks Certified Data Analyst Associate· Lessons

    Domain 5 · Lesson 23/39

    Fix SQL queries that return wrong results in Databricks

    Fix a query to achieve the desired results.

    19 min read
    2.5% of exam
    10 sources
    Published 22 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Fix a GROUP BY error by grouping every non-aggregated column, and move a predicate between WHERE and HAVING or into a conditional aggregate
    • Recognize join fan-out and pre-aggregate before joining so sums and counts are no longer inflated
    • Use the null-safe equality operator <=> to match NULL to NULL, and spot rows lost to predicates that evaluate to NULL
    • Choose between cast, try_cast and a wider type when a cast errors or overflows
    • Add PARTITION BY so a window function restarts its calculation for each group

    Key concept

    A query that runs is not a query that is right — A broken query comes in one of two kinds: one that fails with an error, and one that runs but returns the wrong rows or totals. For the second kind you work out where rows were dropped, multiplied or merged, and then fix the logic at that step.

    1.Failing queries and queries that return wrong results

    Fixing a query starts with telling two problems apart. A query that fails gives you an error message, and the message usually names the problem: a column that has to be grouped, a value that cannot be cast, a type mismatch. A query that runs but answers the wrong question gives you no message at all. The revenue total is twice what finance reported, a region is missing from the dashboard, or a running total never resets. The second kind is more dangerous because nothing tells you it is wrong.

    Databricks Assistant is good at the first kind. Its Assistant Quick Fix, Diagnose Error and /fix features react to an error, and Quick Fix only targets errors that a single-line change can fix. When the query runs cleanly, nothing triggers them. If the logic is wrong, for example a join that duplicates rows or a filter that drops NULLs, you still have to find the faulty step yourself. Assistant cannot know that 4,812 orders should have been 5,000.

    The Query profile is the tool for that search. Each operator in its graph reports how many rows it took in and how many it produced. Follow the counts from the scans upward. If a join outputs more rows than its larger input, a join condition is multiplying rows. If a filter or inner join outputs far fewer rows than you expected, that step is where your missing rows went. Once you know which operator is at fault, you know which clause to rewrite.

    Checkpoint 1 of 9· Check yourself

    A revenue query in the Databricks SQL editor finishes without any error, but its total is roughly twice the figure finance reported. What is the best first step to find the cause?

    Sources12

    2.Fixing GROUP BY errors and misplaced filters

    Every column in the SELECT list must either appear in GROUP BY or sit inside an aggregate function. A query that selects region, product, SUM(sales_amount) but groups only by region breaks this rule. Databricks rejects it because a single region row would have to show many different products. The rule itself is covered under GROUP BY aggregation. What matters here is choosing the fix that matches the result you actually want.

    If the goal is totals per region and product, the only correct fix is GROUP BY region, product, so the grouping matches every non-aggregated column in the SELECT list. The other fixes that make the error go away each change the answer:

    • Wrapping the column in FIRST(product) removes the error, but each region row then shows one arbitrary product next to a total for all products.
    • Removing product from the SELECT list gives a region-only summary. The query is valid, but it no longer answers the per-product question.
    • Moving product into WHERE filters rows. It does not group them, so the error is still there for any product column left in the SELECT list.

    GROUP BY ALL is a shorthand that groups by every SELECT-list expression without an aggregate. It saves typing, but it uses exactly the columns you selected, so you still have to select the right ones.

    Filters placed in the wrong clause cause the next most common group of errors. The rules for WHERE vs HAVING vs QUALIFY are taught separately. They are needed here because of two mistakes that look alike. WHERE SUM(amount) > 1000 fails, because WHERE runs on individual rows before any group exists. Move the condition to HAVING. The opposite mistake, HAVING country = 'NL', only works if country is a grouping column. Even then it filters after the aggregation has done its work. As a row filter it belongs in WHERE. HAVING may reference only grouping expressions, aggregates and constants. Any other column triggers MISSING_AGGREGATION.

    Some questions need different filters for different columns of the same result, such as total sales next to returned sales per region. One WHERE clause cannot do that, because it would filter both columns. Use conditional aggregates instead. SUM(CASE WHEN status = 'returned' THEN amount END) adds only the matching rows, and so does the equivalent SUM(amount) FILTER (WHERE status = 'returned'). Rows that do not match still count towards the unconditional SUM(amount) next to it.

    Checkpoint 2 of 9· Check yourself

    For each region, a report must show total sales in one column and returned sales in the next. Which rewrite gives both columns correctly in a single query?

    Checkpoint 3 of 9· Exam question

    An analyst runs this query in Databricks SQL and gets an error that product must appear in the GROUP BY clause or be used in an aggregate function: SELECT region, product, SUM(sales_amount) AS total_sales FROM sales GROUP BY region The analyst wants total sales broken out by both region and product. What change fixes the query so it returns the intended per-product totals?

    Sources34

    3.Join fan-out, missing rows and miscounts

    Fan-out happens when a query joins one parent table to two child tables that each have several rows per parent. The joined result holds the product of the two row counts, not their sum. SUM, COUNT and AVG then run over that multiplied result. The query has no syntax problem, which is why the totals look believable and are still wrong.

    Aggregate each child table to one row per key before joining it. Replace order_items with a subquery such as SELECT order_id, SUM(quantity) AS total_qty FROM order_items GROUP BY order_id, then join that result to orders and order_notes. A per-order total can be repeated, but it is never added to itself again. Other fixes only look like they help. SELECT DISTINCT removes duplicate output rows after SUM has already counted every copy, so it changes nothing. Switching to LEFT JOIN decides which orders are kept, not how many copies each row gets. Dropping the notes table and appending the notes with UNION ALL stacks rows of a different shape under the result instead of joining them.

    Join conditions cause two other symptoms, both of which follow from how INNER, LEFT, RIGHT, FULL, SEMI, ANTI and CROSS joins behave:

    • Rows missing. An inner join drops every row that has no match. Customers with no orders disappear from a per-customer report. Use a LEFT JOIN from the table whose rows must all be kept.
    • Row explosion. If the ON clause is missing, or matches on only part of a composite key, for example store_id without sale_date, each row matches many rows it should not. Add the rest of the key.
    • Miscounts after an outer join. Unmatched rows carry NULLs on the outer side. count(*) counts those padding rows as 1, so a customer with no orders shows one order. count(o.order_id) correctly returns 0. Use count(*), count(expr), count(DISTINCT) and NULL-skipping aggregates on purpose.

    Checkpoint 4 of 9· Check yourself

    A report joins orders to both order_items and order_notes on order_id and returns SUM(oi.quantity) per order. The item totals come out several times too high. Which rewrite returns the correct totals?

    Checkpoint 5 of 9· Exam question

    An analyst wants one row per order with its total quantity, but this query returns multiple duplicated rows per order and inflated sums after joining to a table of order line notes: SELECT o.order_id, SUM(oi.quantity) AS total_qty FROM orders o JOIN order_items oi ON o.order_id = oi.order_id JOIN order_notes n ON o.order_id = n.order_id GROUP BY o.order_id Each order has many order_items rows and many order_notes rows. What is the correct fix so total_qty reflects the true quantity per order?

    Sources56

    4.Rows lost to NULL and the null-safe equality operator

    In SQL, a comparison involving NULL evaluates to NULL, not to false, and WHERE, HAVING and ON keep only rows whose predicate is true. The mechanics are covered under NULL three-valued logic in comparisons. The symptom to watch for is rows that disappear without an error. WHERE discount <> 0.1 silently drops every row where discount is NULL. A join on a.region = b.region never matches two rows whose region is NULL, even though both rows mean "unknown region".

    The null-safe equality operator <=> treats NULL as a value that can be compared. It never returns NULL. It returns true when both sides are NULL and false when only one side is. Writing ON a.cost_center <=> b.cost_center makes the NULL rows pair up, and WHERE NOT (discount <=> 0.1) keeps the NULL discounts that <> dropped. Use it only when NULL really means the same thing on both sides. If NULL means "unknown", two unknowns may be different things, and leaving them unmatched is correct.

    Ordinary equality and null-safe equality when NULL is involved
    Left operandRight operand=<=>
    NULLAny valueNULLFalse
    Any valueNULLNULLFalse
    NULLNULLNULLTrue

    Aggregates have the matching problem: they skip NULLs instead of treating them as zero. Suppose 4 stores report sales of 100, 200, NULL and 300. avg(sales) returns 200, because it divides 600 by the 3 non-NULL rows. If a missing value means "no sales", the intended answer is 150, and avg(coalesce(sales, 0)) gives it. Which answer is right depends on what NULL means in your data. The query only shows which assumption you made.

    Checkpoint 6 of 9· Check yourself

    Orders whose discount is NULL vanish from a result filtered with WHERE discount <> 0.1, though no error appears. Which filter keeps every order except those with a discount of exactly 0.1?

    Sources7

    5.Cast failures, try_cast and overflow

    A cast either errors or returns NULL, and ANSI mode decides which. With ansi_mode = true, cast refuses to guess. A string that is not a number raises an invalid-input error, and a value too large for the target type raises an overflow error. With ANSI mode off, the same invalid value becomes NULL without any error. An error stops the query where the bad value is. A silent NULL lets the query finish and then quietly removes those rows from later filters and joins, and from aggregates through the NULL-skipping described above.

    Under ANSI mode, cast errors on overflow and on invalid input, while try_cast returns NULLsql
    -- Protects against integral numeric overflow
    > SELECT cast(12345 AS TINYINT);
      Casting 12345 to tinyint causes overflow
    
    -- For invalid values raises errors instead of returning NULL.
    > SELECT cast('a' AS INTEGER);
      Invalid input syntax for type numeric: a.
      To return NULL instead, use 'try_cast'
    
    -- try_cast() is consistent for both modes
    > SELECT try_cast('a' AS INTEGER);
      NULL

    The two errors call for different fixes. An overflow means the target type is too small. TINYINT cannot hold 12345, so cast to INT, or BIGINT for large IDs and counters, rather than hiding the error. Invalid input means some source values really cannot be converted. When those rows should continue as NULL, use try_cast(amount AS INTEGER), which behaves the same with ANSI mode on or off. A useful habit is to count the rows that try_cast turns into NULL while the original value was not NULL. That count tells you how much bad data you are about to discard. It is safer than turning ANSI mode off, which also brings back lenient implicit casts elsewhere in the query.

    Checkpoint 7 of 9· Check yourself

    With ANSI mode turned off, a staging table holds 1,000 rows in a STRING column amount, and 40 of them contain 'n/a'. What does SELECT avg(cast(amount AS INTEGER)) return?

    Sources8

    6.Window functions that do not reset per group

    A window function with no PARTITION BY treats the whole result as a single partition. SUM(sales_amount) OVER (ORDER BY sale_date) therefore produces one running total that accumulates across every region. It never fails, so the only clue is a North figure that keeps growing with South's sales.

    Add the grouping column to the window: SUM(sales_amount) OVER (PARTITION BY region ORDER BY sale_date). PARTITION BY splits the rows into one window per region, and ORDER BY sets the order of accumulation within each window, so the total restarts at the first sale of every region. The tempting alternatives fail for specific reasons:

    • OVER (ORDER BY region, sale_date) sorts the rows by region, but there is still one partition, so the total carries over from one region into the next.
    • Adding GROUP BY region, sale_date collapses the rows to one per region and date. It still does not partition the window, so the total still runs across regions.
    • An outer WHERE region = region compares each row with itself. It is true for every row except NULL regions, so it filters nothing useful and leaves the window unchanged.

    Checkpoint 8 of 9· Match them up

    Match each version of a sales running-total query to the result it produces across regions.

    Tap a term, then the definition that fits it.

    Checkpoint 9 of 9· Exam question

    An analyst needs a running total of sales_amount per region, ordered by sale_date, but this query produces a single running total across all regions combined instead of resetting for each region: SELECT region, sale_date, sales_amount, SUM(sales_amount) OVER (ORDER BY sale_date) AS running_total FROM sales What change makes the running total restart correctly for each region?

    Sources9

    Sources

    (10)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “When code returns errors, Quick Fix automatically recommends fixes for basic errors that can be fixed in a single-line change.”
      ↩︎ Failing queries and queries that return wrong results
    2. 2.
      “You can visualize each query operator and related metrics, such as the time spent, number of rows processed, rows processed, and memory consumption.”
      ↩︎ Failing queries and queries that return wrong results
      “You can discover and fix common mistakes in SQL statements, such as exploding joins or full table scans.”
      ↩︎ Key concept
      “You can discover and fix common mistakes in SQL statements, such as exploding joins or full table scans.”
      ↩︎ Checkpoint
    3. 3.
      “A shorthand notation to add all SELECT-list expressions not containing aggregate functions as group_expressions.”
      ↩︎ Fixing GROUP BY errors and misplaced filters
      “When a FILTER clause is attached to an aggregate function, only the matching rows are passed to that function.”
      ↩︎ Fixing GROUP BY errors and misplaced filters
    4. 4.
      “If the expression references columns that are neither in the GROUP BY clause nor wrapped in aggregate functions, Databricks raises MISSING_AGGREGATION.”
      ↩︎ Fixing GROUP BY errors and misplaced filters
    5. 6.
      “Recommendation: Determine which result subset you need, then update the join condition or reduce the number of input rows from both relations.”
      ↩︎ Join fan-out, missing rows and miscounts
      “Recommendation: Determine which result subset you need, then update the join condition or reduce the number of input rows from both relations.”
      ↩︎ Exam trap 1
      “The join produces significantly more rows than it reads.”
      ↩︎ Prediction
      “Determine which result subset you need, then update the join condition or reduce the number of input rows from both relations.”
      ↩︎ Checkpoint
    6. 7.
      “which returns False when one of the operand is NULL and returns True when both the operands are NULL.”
      ↩︎ Rows lost to NULL and the null-safe equality operator
      “NULL values are ignored from processing by all the aggregate functions. Only exception to this rule is COUNT(*) function.”
      ↩︎ Rows lost to NULL and the null-safe equality operator
      “which returns False when one of the operand is NULL and returns True when both the operands are NULL.”
      ↩︎ Exam trap 2
      “NULL values are ignored from processing by all the aggregate functions. Only exception to this rule is COUNT(*) function.”
      ↩︎ Checkpoint
      “The result of these operators is unknown or NULL when one of the operands or both the operands are unknown or NULL.”
      ↩︎ Prediction
      “a null-safe equal operator (<=>), which returns False when one of the operand is NULL and returns True when both the operands are NULL”
      ↩︎ Checkpoint
      “NULL values are ignored from processing by all the aggregate functions.”
      ↩︎ Checkpoint
    7. 8.
      “For each of these casts you can use try_cast instead of cast to return NULL rather than of an error.”
      ↩︎ Cast failures, try_cast and overflow
      “Databricks recommends using the explicit cast or try_cast function instead of relying on ANSI_MODE = FALSE.”
      ↩︎ Cast failures, try_cast and overflow
      “For each of these casts you can use try_cast instead of cast to return NULL rather than of an error.”
      ↩︎ Exam trap 3
    8. 9.
      “cumulative sum of salary within each department.”
      ↩︎ Window functions that do not reset per group
      “SUM(salary) OVER (PARTITION BY dept ORDER BY salary”
      ↩︎ Exam trap 4

    Also cited

    Ready to test yourself?

    Practise the 10 questions on this subdomain.

    Spotted a mistake, or was something unclear? Tell us.