Launch price: every exam for $29.99 a year, for the first 300 buyers. See the price

CertStreak
Menu

Implement data type checks

A worked example

Put in order

You are building a new Unity Catalog Delta table named orders in Azure Databricks. A partner sends order totals as text, and the business wants order_total stored as STRING so the original value is kept exactly as received.

Requirements:

  • Every value written to order_total must look like a valid number, such as 120 or 120.50.
  • Malformed totals must never be written to orders, including during the first load from the existing table orders_staging.

Which actions should you perform, in order?

Your order

You didn't answer this one.

Correct order
1Run CREATE TABLE orders (order_id INT, order_total STRING);
2Run ALTER TABLE orders ADD CONSTRAINT valid_order_total CHECK (order_total REGEXP '^[0-9]+(\\.[0-9]+)?$');
3Run INSERT INTO orders SELECT order_id, order_total FROM orders_staging;
Why

A CHECK constraint is enforced whenever data is inserted or updated. A REGEXP pattern on a STRING column can therefore reject totals that do not look like numbers while the raw text is kept. The table has to exist before the constraint can be added. The constraint has to exist before the first load, or malformed totals from staging could be written to the table.

  • Step 1: Run CREATE TABLE orders (order_id INT, order_total STRING); The table must exist before a constraint can be added to it or data loaded into it, so nothing can come first.
  • Step 2: Run ALTER TABLE orders ADD CONSTRAINT valid_order_total CHECK (order_total REGEXP '^[0-9]+(\\.[0-9]+)?$'); ALTER TABLE needs the table created in step 1. The REGEXP check confirms that the STRING column holds values that look like numbers.
  • Step 3: Run INSERT INTO orders SELECT order_id, order_total FROM orders_staging; CHECK constraints are enforced on insert. The first load must therefore run after the constraint exists, so that malformed totals are never written to the table.
  • Not needed: Declare order_total as DECIMAL(10,2) in the CREATE TABLE statement. The requirement is to store order_total as STRING and keep the original value, so changing the column type breaks a stated requirement.
  • Not needed: Run ALTER TABLE orders ADD CONSTRAINT valid_order_total CHECK (order_total IS NOT NULL); This constraint only rejects missing values. Malformed text such as 'fifty' would still be accepted, so the numeric-format requirement is not met.

Practise this topic until it's automatic.

Ten questions a day, every answer explained, and misses that come back until you beat them.

Start free