Databricks Data Engineer Associate Question 197
Single answerYou are working on a Databricks SQL project and need to create a User-Defined Function (UDF) to calculate the square of a given number. Which of the following SQL commands correctly defines and registers the UDF?
- A
CREATE FUNCTION square AS 'org.apache.spark.sql.udf.SquareFunction';
- B
CREATE FUNCTION square(x DOUBLE) RETURNS DOUBLE LANGUAGE PYTHON AS 'def square(x): return x * x';
- C
CREATE FUNCTION square(x DOUBLE) RETURNS DOUBLE AS 'x * x';
- D
CREATE FUNCTION square AS (x DOUBLE) RETURNS DOUBLE USING 'def square(x): return x * x';
Show answer and explanation
Correct answer: B
Explanation
The correct syntax for defining a SQL UDF in Databricks includes specifying the function name, input and return types, the programming language (e.g., Python), and the function logic. Option 2 adheres to this format and correctly defines the UDF using Python.
- A. Incorrect.
This syntax is incorrect because it references a Java class ('org.apache.spark.sql.udf.SquareFunction') but does not follow the syntax for defining a UDF in SQL within Databricks.
- B. Correct.
This is the correct syntax for defining a SQL UDF in Databricks using Python. It specifies the function name, input type, return type, programming language, and the function definition.
- C. Incorrect.
This syntax is incorrect because it does not specify the programming language and does not follow the SQL UDF creation syntax in Databricks.
- D. Incorrect.
This syntax is invalid because it does not conform to Databricks SQL UDF standards. The use of 'USING' is not appropriate in this context.