What you will be able to do
- Explain why comparisons with NULL never match, and find missing values with IS NULL, IS NOT NULL and the null-safe <=> operator
- Measure how much of each column is missing before choosing how to handle it
- Replace missing values with COALESCE or NVL, turn placeholder values into real NULLs with NULLIF or CASE WHEN, and handle unparseable text with try_cast
- Remove or correct invalid rows in a Delta table with DELETE and UPDATE, and know when to quarantine rows on write instead
- Add NOT NULL and CHECK constraints so that invalid data is rejected when it is written
Key concept
Three-valued logic with NULL — In SQL a comparison has three possible results: true, false, or unknown (NULL). Comparing anything with NULL gives NULL, and WHERE keeps only rows where the condition is true. So missing values drop out of filters silently unless you test for them with IS NULL.
1.Why NULL slips through ordinary filters
Cleaning data starts with finding the bad values, and missing values hide from the usual tools. In SQL, NULL means a value that was not known when the row was written, such as an age nobody recorded. Comparisons do not treat it as an ordinary value. 5 > null gives NULL, and so does null = null. A comparison operator returns NULL whenever either side is NULL.
WHERE, HAVING and JOIN conditions all work the same way. The condition can come out True, False or Unknown, and only True keeps the row. That is why WHERE age > 0 quietly drops the two people with no recorded age: for them the condition is unknown, not false. The query raises no error, and the row count is simply smaller than you expected.
To find missing values, use IS NULL. To exclude them, use IS NOT NULL. If you want to keep valid ages and also keep the rows whose age is unknown, add IS NULL as an OR branch. When you need to compare two columns that might both be NULL, for example in a join key, the null-safe equal operator <=> returns true when both sides are NULL and false when only one side is. Plain = returns NULL in both of those cases.
-- `IS NULL` expression is used in disjunction to select the persons
-- with unknown (`NULL`) records.
> SELECT * FROM person WHERE age > 0 OR age IS NULL;Logical operators follow the same rules. true OR null is true, but null OR false is NULL and NOT(null) is still NULL. So wrapping a condition in NOT does not bring back the rows it lost. A validity predicate such as quantity >= 0 returns the good rows. Its opposite, quantity < 0, returns the bad ones. Neither returns the rows where quantity is NULL, so test for those separately. A WHERE predicate filters individual rows, and that is the clause you clean with; see WHERE vs HAVING vs QUALIFY for how it differs from the other two.
Before you choose a fix, measure how much is missing. count(*) counts every row, while count(col) skips NULLs. Their difference, count(*) - count(col), is the number of missing values in that column. On the person table that is 7 − 5 = 2. Two missing values in a column of millions might be fine to delete. Forty percent missing calls for a default value or a conversation with the upstream team. count(*), count(expr), count(DISTINCT) and NULL-skipping aggregates covers the counting functions themselves.
Checkpoint 1 of 8· Fill the gap
Some rows in the person table have no recorded age. You want the rows with a positive age and also the rows where age is unknown. Which operator completes the query?
> SELECT * FROM person WHERE age > 0 OR age ? NULL;age = NULL evaluates to NULL for every row, so WHERE never keeps a row from that branch. IS NULL returns true for missing ages, so the OR branch keeps those rows. IS NOT would add nothing, and <> gives NULL just like =.
Sources1
2.Replacing and normalising missing values in a query
COALESCE replaces NULL with something usable. It returns the first argument that is not NULL, reading left to right. It also stops evaluating as soon as it finds one, which is unusual: coalesce(2, 5 / 0) returns 2 without raising the division error, while coalesce(NULL, 5 / 0) fails. If every argument is NULL, the result is NULL. That makes a list of fallbacks easy to write. COALESCE(region, cost_center, 'UNKNOWN') returns region when it is present. It returns cost_center only when region is NULL, and 'UNKNOWN' only when both are NULL. The function returns one value, not an array, and its arguments must share a least common type, which is also the type of the result.
NVL(expr1, expr2) is a synonym for two-argument COALESCE: nvl(NULL, 2) returns 2 and nvl(3, 2) returns 3. IFNULL belongs to the same group of NULL-handling functions. The typing rule is the same for NVL: the second argument must share a least common type with the first, and the result takes that type. Calls such as coalesce(NULL, 1, NULL), which returns the number 1, and coalesce(NULL, 'hello'), which returns the string 'hello', each mix NULL with values of one type.
COALESCE only helps when the bad value is actually NULL. Many source systems cannot write NULL, so they use a placeholder instead: -1 for an unknown weight, an empty string, 'N/A'. NULLIF(expr1, expr2) returns NULL when the two arguments are equal and returns expr1 otherwise. NULLIF(weight, -1) therefore turns the placeholder into a real NULL, and the NULL-aware tools above start working on it. NULLIF produces NULL, not a replacement value. If the report needs 0, you still have to supply it, for example with COALESCE(NULLIF(order_total, -1), 0).
CASE WHEN is the most general option because it can test several different conditions in one expression. A report that must show 0 for both NULL and -1 can write CASE WHEN order_total IS NULL OR order_total = -1 THEN 0 ELSE order_total END. The IS NULL test is required here: order_total = -1 alone evaluates to NULL for missing rows, and CASE then falls through to ELSE and returns NULL. All of these expressions belong in the SELECT list, so the table stays unchanged. Filtering the problem rows out with WHERE is a different result entirely: those rows disappear from the report instead of showing 0.
INSERT INTO silver_table
SELECT
* EXCEPT weight,
CASE
WHEN weight = -1 THEN NULL
ELSE weight
END AS weight
FROM bronze_table;Text columns that should hold numbers or dates cause a related problem. A plain cast fails the whole query when it reaches a malformed value. try_cast returns NULL for that value instead: try_cast('10' AS INT) gives 10 and try_cast('a' AS INT) gives NULL. After the cast, unparseable entries are ordinary missing values, and you can count, filter or replace them like any other NULL.
| Expression | What it returns | Use it when |
|---|---|---|
| COALESCE(a, b, c) | The first non-NULL argument, or NULL if all are NULL | You have a chain of fallback columns or a default value |
| NVL(a, b) / IFNULL(a, b) | b when a is NULL, otherwise a | You need a single fallback for one column |
| NULLIF(a, b) | NULL when a equals b, otherwise a | A placeholder such as -1 or '' should become a real NULL |
| CASE WHEN ... THEN ... ELSE ... END | Whatever each branch specifies | Several different conditions must map to one value |
| ISNULL(a) | true for NULL input, false otherwise | You need a boolean flag for missing values |
Checkpoint 2 of 8· Check yourself
In a bronze table, the weight column is NULL for some rows and holds the upstream placeholder -1 for others. A report query must show 0 for both kinds of missing weight and keep every other weight unchanged. Which SELECT expression does this?
NULLIF turns the -1 placeholder into a real NULL, and COALESCE then replaces every NULL with 0. COALESCE alone leaves -1 unchanged because -1 is not NULL. NULLIF alone returns NULL, not 0. The CASE version sends NULL rows to ELSE because weight = -1 is NULL for them, so it returns NULL.
“Returns NULL if expr1 equals expr2, or expr1 otherwise.”Source: docs.databricks.com
Checkpoint 3 of 8· Exam question
A Unity Catalog table sales.orders has an order_total column where some rows hold NULL because the value was never captured, and other rows hold -1 as a placeholder inserted by a legacy loader. An analyst wants a query that reports 0 for both cases without altering the underlying table. Which SQL statement produces the correct result?
Correct answer: A — SELECT CASE WHEN order_total IS NULL OR order_total = -1 THEN 0 ELSE order_total END FROM sales.orders
- A. A CASE expression can test both conditions explicitly, mapping a true NULL and the -1 placeholder to 0 while leaving every other value unchanged, which is exactly what the analyst needs without modifying the stored rows.
- B. COALESCE only substitutes when an argument is NULL, so it would replace NULL with -1 (the second argument) rather than 0, and it never touches rows that already contain -1, producing the wrong output for both cases.
- C. Filtering rows out with WHERE removes the problem rows from the result set entirely instead of reporting them as 0, so the row count and totals would no longer reflect all orders.
- D. NULLIF converts -1 into NULL rather than into 0, and it leaves genuinely NULL rows unchanged, so neither placeholder case ends up reported as 0.
Checkpoint 4 of 8· Exam question
An analyst runs SELECT COALESCE(region, cost_center, 'UNKNOWN') AS region FROM catalog.dim_store against a Unity Catalog dimension table where region is missing for some rows and cost_center is missing for a different subset of rows. What determines the value returned for each row?
Correct answer: A — COALESCE evaluates arguments left to right and returns the first non-NULL one, so cost_center only applies when region is NULL and 'UNKNOWN' only when both are NULL
- A. This matches documented COALESCE behavior: it short-circuits on the first non-NULL argument in left-to-right order, so cost_center is only reached when region is NULL, and the literal fallback only fires when both columns are NULL.
- B. COALESCE short-circuits rather than evaluating every argument, and it never simply returns the last item in the list; if it did, the literal fallback would overwrite valid region and cost_center values, which is not how the function behaves.
- C. COALESCE has no equality requirement between its arguments; it only checks each one for NULL in order, so this description invents a constraint the function does not enforce.
- D. COALESCE returns a single scalar value per row matching the first non-NULL argument's type, not a collection, so there is no array to explode.
3.Removing and correcting invalid rows with DELETE and UPDATE
Query-time fixes leave the bad rows in the table, so every query has to repeat the fix. When the rows are simply wrong, such as hire dates in the future from a faulty feed, change the table itself. Unity Catalog tables stored in Delta Lake support DELETE and UPDATE, and both statements work only on Delta Lake tables.
DELETE FROM table WHERE predicate permanently removes the matching rows. DELETE FROM hr.employees WHERE hire_date > current_date() removes the future-dated rows, and later queries never see them. The WHERE clause matters a great deal: without a predicate, DELETE removes every row in the table. The predicate can use subqueries such as IN, EXISTS and scalar subqueries. Prefer NOT EXISTS to NOT IN, because DELETE with a NOT IN subquery can be slow.
> DELETE FROM events WHERE date < '2017-01-01'
> DELETE FROM all_events
WHERE session_time < (SELECT min(session_time) FROM good_events)
> DELETE FROM orders AS t1
WHERE EXISTS (SELECT oid FROM returned_orders WHERE t1.oid = oid)UPDATE table SET col = expr WHERE predicate corrects values and keeps the row. Like DELETE, it applies to every row when you leave out the WHERE clause. Inside SET, column references hold the row's values before the update. That means UPDATE ... SET weight = NULL WHERE weight = -1 converts placeholders to real NULLs in the table, just as NULLIF does in a query. Use UPDATE when the row is worth keeping and you know the correct value or are willing to leave it as NULL. Setting a bad date to NULL is not the same as removing the row: the row stays, now with a missing value.
Sometimes the raw table must stay intact, for example because it is a landing table that other jobs read from. In that case, split rows on write instead of editing in place. One INSERT writes rows that pass a validity predicate to a clean table. A second INSERT, with the opposite predicate, writes the failures to a quarantine table where someone can inspect them. Run them as two separate writes.
DECLARE current_time = now()
INSERT INTO silver_table
SELECT * FROM bronze_table
WHERE event_timestamp <= current_time AND quantity >= 0;
INSERT INTO quarantine_table
SELECT * FROM bronze_table
WHERE event_timestamp > current_time OR quantity < 0;| Approach | Stored rows changed? | Wins when |
|---|---|---|
| SELECT ... WHERE valid | No: bad rows are only hidden from this result | You need a one-off answer and the table must stay as it is |
| CREATE VIEW ... WHERE valid | No: the view filters at query time | Many readers need the clean subset and the raw rows must remain |
| UPDATE ... SET ... WHERE invalid | Yes: values are corrected and the rows remain | The row is valid apart from one fixable column |
| DELETE FROM ... WHERE invalid | Yes: the rows are permanently removed | The rows are wrong and should not exist in the table |
| INSERT into clean and quarantine tables | Raw table unchanged; clean copy written | Bad records must be kept for review and not reach downstream tables |
Checkpoint 5 of 8· Check yourself
A faulty HR feed wrote hire dates in the future into the Delta table hr.employees. These rows are simply wrong, and no later query should ever see them. Which statement fixes this?
Only DELETE removes the matching rows from the stored table. A view or a SELECT hides them only at query time. UPDATE ... SET NULL keeps each bad row, which now has a missing hire date.
“Deletes the rows that match a predicate. When no predicate is provided, deletes all rows.”Source: docs.databricks.com
Checkpoint 6 of 8· Check yourself
You run the two quarantine INSERTs: quantity >= 0 for silver_table and quantity < 0 for quarantine_table, each combined with the timestamp test. A bronze row has a past event_timestamp and a NULL quantity. Where does that row end up?
Both quantity >= 0 and quantity < 0 evaluate to NULL when quantity is NULL. WHERE keeps only rows whose condition is true, so neither INSERT writes the row. To quarantine it, add OR quantity IS NULL to the quarantine predicate.
“The result of these operators is unknown or NULL when one of the operands or both the operands are unknown or NULL.”Source: docs.databricks.com
Checkpoint 7 of 8· Exam question
A Unity Catalog managed table hr.employees has a small number of rows with clearly invalid hire_date values (e.g. dates far in the future) that were introduced by a faulty upstream feed. The team wants these specific rows permanently removed from the table itself, not just filtered out of query results. Which statement accomplishes this?
Correct answer: A — DELETE FROM hr.employees WHERE hire_date > current_date() to remove the future-dated rows
- A. DELETE FROM with a WHERE predicate permanently removes the matching rows from the Delta table's data files, which is the only listed operation that changes the stored table rather than just changing what a query returns.
- B. A plain SELECT with a WHERE clause only filters the rows returned to the client; it does not modify the underlying table, so the invalid rows remain in
hr.employeesafterward. - C. UPDATE would overwrite the invalid hire_date with NULL but keep the row in the table, which fixes the value rather than removing the row as the requirement specifies.
- D. Creating a view layers a filtered read on top of the same underlying data without deleting anything, so the invalid rows still physically exist in
hr.employees.
4.Preventing bad data with NOT NULL and CHECK constraints
After a cleanup, the same faulty feed can write the same bad rows again the next night. Constraints stop that. Delta tables support two enforced constraints. NOT NULL means a column cannot hold NULL. CHECK means a boolean expression must be true for every row. If a write violates either one, the transaction fails with an error and nothing is written. Primary key, foreign key and unique constraints, by contrast, are informational only and are not enforced. All constraints on Databricks require Delta Lake.
NOT NULL is part of the column definition. You can declare it in CREATE TABLE, or add and remove it later with ALTER TABLE ... ALTER COLUMN ... SET NOT NULL or DROP NOT NULL.
CREATE OR REPLACE TABLE main.default.people_demo (
id INT NOT NULL,
firstName STRING,
middleName STRING NOT NULL,
lastName STRING,
gender STRING,
birthDate TIMESTAMP,
ssn STRING,
salary INT
);
ALTER TABLE main.default.people_demo ALTER COLUMN middleName DROP NOT NULL;
ALTER TABLE main.default.people_demo ALTER COLUMN ssn SET NOT NULL;The order of the steps matters. Before adding a constraint to an existing table, Databricks checks every existing row, and the ALTER fails if any row breaks the rule. You cannot set ssn to NOT NULL while some rows still have a NULL ssn. So the cleanup comes first: DELETE or UPDATE the offending rows, then add the constraint. CHECK constraints work the same way.
CHECK constraints are managed with ALTER TABLE ADD CONSTRAINT and ALTER TABLE DROP CONSTRAINT, and each one has a name. They can enforce value ranges (column_name >= 0 AND column_name <= 100) or text patterns with REGEXP or RLIKE. The expression must be deterministic, and it cannot use user-defined functions, aggregate functions, window functions or functions that return multiple rows. A rule such as 'no more than ten rows per customer' therefore cannot be a CHECK constraint. To list a table's CHECK constraints, run DESCRIBE DETAIL or SHOW TBLPROPERTIES. Adding a constraint can upgrade the table's writer protocol, which may affect external Delta Lake clients.
ALTER TABLE main.default.people_demo ADD CONSTRAINT dateWithinRange CHECK (birthDate > '1900-01-01');
ALTER TABLE main.default.people_demo DROP CONSTRAINT dateWithinRange;Checkpoint 8 of 8· Put it in order
Some rows of main.default.people_demo have a NULL ssn. You want future writes with a missing ssn to be rejected. Arrange the steps in the order that works.
- 1.Run ALTER TABLE main.default.people_demo ALTER COLUMN ssn SET NOT NULL
- 2.A later write with a NULL ssn fails with an error and writes nothing
- 3.UPDATE or DELETE the rows whose ssn is NULL
- 4.Measure the missing values with count(*) - count(ssn)
Before Databricks adds a NOT NULL constraint, it checks every existing row. If any row still has a NULL ssn, the ALTER fails, so the cleanup has to come first. Once the constraint is in place, any transaction that breaks it fails with an error.
“Databricks verifies that all existing rows satisfy the constraint before adding a NOT NULL constraint to a table.”Source: docs.databricks.com
Sources
(9)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“The result of these operators is unknown or NULL when one of the operands or both the operands are unknown or NULL.”
↩︎ Why NULL slips through ordinary filters“a condition expression is a boolean expression and can return True, False or Unknown (NULL).”
↩︎ Why NULL slips through ordinary filters“NULL values are ignored from processing by all the aggregate functions. Only exception to this rule is COUNT(*) function.”
↩︎ Why NULL slips through ordinary filters“The result of these operators is unknown or NULL when one of the operands or both the operands are unknown or NULL.”
↩︎ Key concept“a condition expression is a boolean expression and can return True, False or Unknown (NULL).”
↩︎ Exam trap 1“The result of these operators is unknown or NULL when one of the operands or both the operands are unknown or NULL.”
↩︎ Checkpoint - 2.
“coalesce evaluates arguments left to right until a non-null value is found”
↩︎ Replacing and normalising missing values in a query“If all arguments are NULL, the result is NULL.”
↩︎ Replacing and normalising missing values in a query“The result type is the least common type of the arguments.”
↩︎ Replacing and normalising missing values in a query“coalesce evaluates arguments left to right until a non-null value is found”
↩︎ Exam trap 2“Returns the first non-null argument.”
↩︎ Prediction - 3.
“This function is a synonym for coalesce(expr1, expr2) with two arguments.”
↩︎ Replacing and normalising missing values in a query - 4.
“Returns NULL if expr1 equals expr2, or expr1 otherwise.”
↩︎ Replacing and normalising missing values in a query - 5.
“you could use a case when statement to dynamically replace these records as a transformation.”
↩︎ Replacing and normalising missing values in a query“You can use filters and WHERE clauses to define custom logic that quarantines bad records and prevents them from propagating to downstream tables.”
↩︎ Removing and correcting invalid rows with DELETE and UPDATE“To enforce a pattern using regex, you can use the REGEXP or RLIKE functions in SQL.”
↩︎ Preventing bad data with NOT NULL and CHECK constraints - 6.
“If a sourceExpr value is not well formed or contains invalid characters the result is NULL instead of an invalid data error.”
↩︎ Replacing and normalising missing values in a query - 7.
“Deletes the rows that match a predicate. When no predicate is provided, deletes all rows.”
↩︎ Removing and correcting invalid rows with DELETE and UPDATE“This statement is only supported for Delta Lake tables.”
↩︎ Removing and correcting invalid rows with DELETE and UPDATE“We recommend using NOT EXISTS whenever possible, as DELETE with NOT IN subqueries can be slow.”
↩︎ Removing and correcting invalid rows with DELETE and UPDATE“Deletes the rows that match a predicate. When no predicate is provided, deletes all rows.”
↩︎ Exam trap 3 - 8.
“Updates the column values for the rows that match a predicate.”
↩︎ Removing and correcting invalid rows with DELETE and UPDATE“If you reference table_name columns they represent the state of the row prior the update.”
↩︎ Removing and correcting invalid rows with DELETE and UPDATE - 9.
“When a constraint is violated, the transaction fails with an error.”
↩︎ Preventing bad data with NOT NULL and CHECK constraints“CHECK: indicates that a specified boolean expression must be true for each input row.”
↩︎ Preventing bad data with NOT NULL and CHECK constraints“Databricks verifies that all existing rows satisfy the constraint before adding a NOT NULL constraint to a table.”
↩︎ Preventing bad data with NOT NULL and CHECK constraints“except the following types of functions: User-defined functions. Aggregate functions. Window functions. Functions returning multiple rows.”
↩︎ Preventing bad data with NOT NULL and CHECK constraints“Databricks verifies that all existing rows satisfy the constraint before adding a NOT NULL constraint to a table.”
↩︎ Exam trap 4