CertSafari
    Databricks Certified Data Analyst Associate· Lessons

    Domain 2 · Lesson 6/39

    Cleaning Unity Catalog tables in SQL: NULLs, invalid rows and constraints

    Perform data cleaning on Unity Catalog Tables in SQL, including removing invalid data or handling missing values.

    19 min read
    2.67% of exam
    9 sources
    Published 22 Oct 2026
    Docs as of 30 Sep 2026

    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.

    Adding IS NULL as an OR branch keeps rows whose age is unknownsql
    -- `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;

    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.

    Replacing the placeholder -1 with a real NULL while copying data into a cleaner tablesql
    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.

    Which NULL-handling function to use
    ExpressionWhat it returnsUse it when
    COALESCE(a, b, c)The first non-NULL argument, or NULL if all are NULLYou have a chain of fallback columns or a default value
    NVL(a, b) / IFNULL(a, b)b when a is NULL, otherwise aYou need a single fallback for one column
    NULLIF(a, b)NULL when a equals b, otherwise aA placeholder such as -1 or '' should become a real NULL
    CASE WHEN ... THEN ... ELSE ... ENDWhatever each branch specifiesSeveral different conditions must map to one value
    ISNULL(a)true for NULL input, false otherwiseYou 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?

    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?

    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?

    Sources23456

    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 with a simple predicate, a scalar subquery and an EXISTS subquerysql
    > 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.

    Quarantining bad rows on write: one predicate for good rows, its opposite for bad rowssql
    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;
    What each approach does to the stored data
    ApproachStored rows changed?Wins when
    SELECT ... WHERE validNo: bad rows are only hidden from this resultYou need a one-off answer and the table must stay as it is
    CREATE VIEW ... WHERE validNo: the view filters at query timeMany readers need the clean subset and the raw rows must remain
    UPDATE ... SET ... WHERE invalidYes: values are corrected and the rows remainThe row is valid apart from one fixable column
    DELETE FROM ... WHERE invalidYes: the rows are permanently removedThe rows are wrong and should not exist in the table
    INSERT into clean and quarantine tablesRaw table unchanged; clean copy writtenBad 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?

    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?

    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?

    Sources785

    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.

    Declaring NOT NULL at creation, then dropping it from one column and adding it to anothersql
    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.

    Adding a named CHECK constraint, then dropping itsql
    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. 1.Run ALTER TABLE main.default.people_demo ALTER COLUMN ssn SET NOT NULL
    2. 2.A later write with a NULL ssn fails with an error and writes nothing
    3. 3.UPDATE or DELETE the rows whose ssn is NULL
    4. 4.Measure the missing values with count(*) - count(ssn)

    Sources95

    Sources

    (9)

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

    1. 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. 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. 3.
      “This function is a synonym for coalesce(expr1, expr2) with two arguments.”
      ↩︎ Replacing and normalising missing values in a query
    4. 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
    5. 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
    6. 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
    7. 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
    8. 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

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