Databricks Data Engineer Associate Question 317
Single answerYou are working with a Delta table in Databricks and need to add a generated column that calculates the total price as the product of 'quantity' and 'unit_price'. Which of the following commands will correctly create this generated column?
- A
ALTER TABLE sales ADD COLUMN total_price GENERATED ALWAYS AS (quantity * unit_price);
- B
ALTER TABLE sales ADD COLUMN total_price AS (quantity * unit_price);
- C
ALTER TABLE sales ADD COLUMN total_price GENERATED ALWAYS AS (quantity * unit_price) STORED;
- D
ALTER TABLE sales ADD COLUMN total_price COMPUTED AS (quantity * unit_price) STORED;
Show answer and explanation
Correct answer: C
Explanation
Delta tables in Databricks support generated columns using the syntax 'GENERATED ALWAYS AS (...) STORED'. This ensures that the column's value is automatically calculated based on an expression and physically stored in the table. The correct command for adding a generated column must include both the GENERATED ALWAYS AS and STORED keywords.
- A. Incorrect.
This option is incorrect because it is missing the STORED keyword, which is required for adding a generated column in Delta tables.
- B. Incorrect.
This option is incorrect because it uses an invalid syntax for defining a generated column. The GENERATED ALWAYS AS syntax is required.
- C. Correct.
This option is correct because it uses the correct syntax to define a generated column in a Delta table, including the GENERATED ALWAYS AS statement and the STORED keyword.
- D. Incorrect.
This option is incorrect because the 'COMPUTED AS' keyword is not valid syntax for defining a generated column in Delta tables.