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?
The query ran cleanly, so no error exists to trigger Diagnose Error, /fix, Quick Fix or an error message. To find a logic problem such as a join that multiplies rows, follow the row counts per operator in the query profile.
“You can discover and fix common mistakes in SQL statements, such as exploding joins or full table scans.”Source: docs.databricks.com
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
productfrom the SELECT list gives a region-only summary. The query is valid, but it no longer answers the per-product question. - Moving
productinto 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?
A WHERE clause filters the rows behind both columns, so total sales would shrink to returned sales too. A conditional aggregate adds only matching rows. Non-matching rows produce NULL, which SUM ignores, while the plain SUM(amount) still counts every row. HAVING fails because status is not a grouping column. Grouping by status splits each region into separate rows.
“NULL values are ignored from processing by all the aggregate functions. Only exception to this rule is COUNT(*) function.”Source: docs.databricks.com
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?
Correct answer: A — Add product to the grouping list so the clause reads GROUP BY region, product, matching every non-aggregated column named in the SELECT list.
- A. This is correct: every column referenced outside an aggregate function must be listed in
GROUP BY, so addingproductproduces one row per region-product pair with the sales correctly summed within each pair. - B. This removes the error but changes the result:
FIRST()returns whatever product happens to appear first for that region, so the query no longer reports true per-product totals as the analyst intended. - C. This avoids the grouping error, but dropping the column means the query can no longer show sales split out by product at all, which does not satisfy the stated requirement.
- D. Filtering on
productinWHERErestricts which rows are included rather than grouping by them, so the output still collapses to one row per region and never shows a per-product breakdown.
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_idwithoutsale_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?
When order_items is reduced to one row per order before the join, each order's total can be repeated for every note but is never added to itself again. DISTINCT only removes duplicate rows after SUM has already counted every copy, and LEFT JOIN decides which orders are kept, not how many times each row is copied. Swapping the join order changes nothing, because SUM runs over the joined result whichever table is joined first.
“Determine which result subset you need, then update the join condition or reduce the number of input rows from both relations.”Source: docs.databricks.com
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?
Correct answer: A — Aggregate order_items quantities into a per-order subquery first, then join that pre-aggregated result to orders and order_notes so the note join no longer multiplies item rows.
- A. This is correct: pre-aggregating
order_itemsbyorder_idbefore joining toorder_notesmeans each order contributes exactly one row to that join, so the fan-out from multiple notes per order no longer inflates the summed quantity. - B. Adding
DISTINCToperates on the final grouped output rows, not on the intermediate join rows that caused the inflated sum, so the quantities are already miscounted by the timeDISTINCTcould apply. - C. Switching to
LEFT JOINchanges which rows are included when a match is missing, but it does not address the row-multiplication problem that happens whenever an order has more than one matching note. - D. Dropping the join and reattaching notes through a
UNION ALLcombines row sets vertically rather than joining columns side by side, so the notes would need an entirely different, more complex query structure to appear per order.
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.
| Left operand | Right operand | = | <=> |
|---|---|---|---|
| NULL | Any value | NULL | False |
| Any value | NULL | NULL | False |
| NULL | NULL | NULL | True |
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?
NULL <=> 0.1 returns false rather than NULL, so NOT turns it into true and the NULL discounts are kept. NOT (discount = 0.1) and discount = NULL both still evaluate to NULL for those rows, so the filter drops them. discount <=> 0.1 keeps only the rows where the discount is 0.1.
“a null-safe equal operator (<=>), which returns False when one of the operand is NULL and returns True when both the operands are NULL”Source: docs.databricks.com
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.
-- 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);
NULLThe 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?
With ANSI mode off, cast turns each invalid value into NULL instead of raising an error. avg skips NULLs, so the 40 'n/a' rows drop out of the average and nothing warns you. The invalid-input error appears only with ANSI mode on. Overflow means a valid number is too large for the target type, which is not the case for 'n/a'.
“NULL values are ignored from processing by all the aggregate functions.”Source: docs.databricks.com
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_datecollapses 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 = regioncompares each row with itself. It is true for every row except NULL regions, so it filters nothing useful and leaves the window unchanged.
With no PARTITION BY, ROW_NUMBER numbers all products as one list, so only the top 3 overall get ranks 1 to 3. Use ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) so numbering restarts in each category. Each category then has its own ranks 1 to 3.
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.
Only PARTITION BY splits the rows into a separate window for each region, so only that version restarts the total. ORDER BY just sorts the rows inside the one window. GROUP BY reduces the rows to one per region and date, but the window still has no partition. Without PARTITION BY, the whole result is a single partition.
“A window function without PARTITION BY. Add a PARTITION BY clause so that the window doesn't span the whole dataset.”Source: docs.databricks.com
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?
Correct answer: A — Add PARTITION BY region to the window clause, so it reads OVER (PARTITION BY region ORDER BY sale_date), restarting the running sum within each region.
- A. This is correct:
PARTITION BY regiontells the window function to treat each region as its own independent frame, so the cumulative sum restarts at zero every time the region value changes in the ordered rows. - B. Mixing a
GROUP BYclause into a query that also uses a window function over ungrouped columns likesale_dateandsales_amountproduces an error or forces those columns into an aggregate, breaking the row-level output. - C. Ordering by
region, sale_datechanges the sequence in which rows are summed but does not create separate partitions, so the running total still accumulates continuously across region boundaries instead of resetting. - D. A self-referential filter like
region = regionis always true for every row and has no effect on how the window function groups or partitions its calculation, so the running total stays unpartitioned across regions.
Sources9
Sources
(10)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 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.
“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.https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-qry-select-groupbyOfficial docs
“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.https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-qry-select-havingOfficial docs
“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.https://docs.databricks.com/aws/en/optimizations/spark-ui-guide/slow-spark-stage-low-ioOfficial docs
“an exploding join or explode() might be the cause”
↩︎ Join fan-out, missing rows and miscounts - 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 - 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 - 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 - 9.https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-window-functions-frameOfficial docs
“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
“A window function without PARTITION BY. Add a PARTITION BY clause so that the window doesn't span the whole dataset.”
↩︎ Checkpoint