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_totalmust look like a valid number, such as120or120.50. - Malformed totals must never be written to
orders, including during the first load from the existing tableorders_staging.
Which actions should you perform, in order?
You didn't answer this one.
CREATE TABLE orders (order_id INT, order_total STRING);ALTER TABLE orders ADD CONSTRAINT valid_order_total CHECK (order_total REGEXP '^[0-9]+(\\.[0-9]+)?$');INSERT INTO orders SELECT order_id, order_total FROM orders_staging;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_totalasDECIMAL(10,2)in the CREATE TABLE statement. The requirement is to storeorder_totalas 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.