Bird
0
0

You want to create a function that returns the length of a text input only if the input is not empty; otherwise, it returns zero. Which function body correctly implements this logic in PostgreSQL?

hard📝 Application Q8 of 15
PostgreSQL - PL/pgSQL Fundamentals
You want to create a function that returns the length of a text input only if the input is not empty; otherwise, it returns zero. Which function body correctly implements this logic in PostgreSQL?
ABEGIN IF input IS NULL THEN RETURN 0; ELSE RETURN LENGTH(input); END IF; END;
BBEGIN RETURN LENGTH(input) WHERE input <> ''; END;
CBEGIN RETURN LENGTH(input) IF input != ''; ELSE RETURN 0; END;
DBEGIN IF input = '' THEN RETURN 0; ELSE RETURN LENGTH(input); END IF; END;
Step-by-Step Solution
Solution:
  1. Step 1: Understand the condition for empty string

    We check if input = '' to detect empty text.
  2. Step 2: Verify correct PL/pgSQL syntax for IF statement

    BEGIN IF input = '' THEN RETURN 0; ELSE RETURN LENGTH(input); END IF; END; uses correct IF-THEN-ELSE-END IF syntax and returns 0 or length accordingly.
  3. Step 3: Check other options for syntax errors

    Options B and C use invalid syntax; A checks for NULL, not empty string.
  4. Final Answer:

    BEGIN IF input = '' THEN RETURN 0; ELSE RETURN LENGTH(input); END IF; END; -> Option D
  5. Quick Check:

    Use IF-THEN-ELSE-END IF for conditional logic [OK]
Quick Trick: Use IF-THEN-ELSE-END IF for conditions in PL/pgSQL [OK]
Common Mistakes:
  • Using WHERE inside function body incorrectly
  • Confusing NULL with empty string
  • Incorrect IF syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes