Complete the code to create a simple function that returns the square of a number.
CREATE FUNCTION square(num INT) RETURNS INT AS $$ BEGIN RETURN num [1] num; END; $$ LANGUAGE plpgsql;The function multiplies the input number by itself to return its square.
Complete the code to create a function that returns the length of a given text.
CREATE FUNCTION text_length(txt TEXT) RETURNS INT AS $$ BEGIN RETURN [1](txt); END; $$ LANGUAGE plpgsql;count which counts rows, not string length.char_length is valid but here only length is accepted.The length function returns the number of characters in the text.
Fix the error in the function that calculates the factorial of a number.
CREATE FUNCTION factorial(n INT) RETURNS INT AS $$ BEGIN IF n = 0 THEN RETURN 1; ELSE RETURN n [1] factorial(n - 1); END IF; END; $$ LANGUAGE plpgsql;
The factorial is calculated by multiplying the number by the factorial of one less than the number.
Fill both blanks to create a function that returns the maximum of two numbers.
CREATE FUNCTION max_two(a INT, b INT) RETURNS INT AS $$ BEGIN IF a [1] b THEN RETURN a; ELSE RETURN [2]; END IF; END; $$ LANGUAGE plpgsql;
a in the else branch is incorrect.The function compares a and b. If a is greater, it returns a, otherwise it returns b.
Fill all three blanks to create a function that returns a greeting message with the user's name.
CREATE FUNCTION greet_user(name TEXT) RETURNS TEXT AS $$ BEGIN RETURN 'Hello, ' || [1] || [2] || [3]; END; $$ LANGUAGE plpgsql;
The function concatenates 'Hello, ' with the user's name, a space, and an exclamation mark to form a greeting.