Bird
0
0

You want to declare two integer variables x and y, assign 15 to x and 30 to y, then swap their values inside a PL/pgSQL block. Which code snippet correctly performs this swap?

hard📝 Application Q8 of 15
PostgreSQL - PL/pgSQL Fundamentals
You want to declare two integer variables x and y, assign 15 to x and 30 to y, then swap their values inside a PL/pgSQL block. Which code snippet correctly performs this swap?
ADECLARE x integer := 15; y integer := 30; temp integer; BEGIN temp := x; x := y; y := temp; END;
BDECLARE x integer := 15; y integer := 30; BEGIN x := y; y := x; END;
CDECLARE x integer := 15; y integer := 30; BEGIN x = y; y = x; END;
DDECLARE x integer := 15; y integer := 30; BEGIN x := x + y; y := x - y; x := x - y; END;
Step-by-Step Solution
Solution:
  1. Step 1: Understand the Swap Logic

    Swapping two variables requires a temporary variable to hold one value during the exchange.
  2. Step 2: Analyze Options

    DECLARE x integer := 15; y integer := 30; temp integer; BEGIN temp := x; x := y; y := temp; END; uses a temporary variable temp to hold x's value, then assigns y to x, and finally assigns temp to y, correctly swapping the values.
  3. Step 3: Identify Incorrect Options

    DECLARE x integer := 15; y integer := 30; BEGIN x := y; y := x; END; overwrites x with y and then assigns x (already overwritten) to y, losing original x value.
    DECLARE x integer := 15; y integer := 30; BEGIN x = y; y = x; END; uses '=' instead of ':=' for assignment, which is invalid.
    DECLARE x integer := 15; y integer := 30; BEGIN x := x + y; y := x - y; x := x - y; END; uses arithmetic swap logic but is missing the declaration of temp and is more complex than necessary.
  4. Final Answer:

    DECLARE x integer := 15; y integer := 30; temp integer; BEGIN temp := x; x := y; y := temp; END; correctly swaps the values using a temporary variable.
  5. Quick Check:

    Use temp variable for swap [OK]
Quick Trick: Use a temp variable to swap values [OK]
Common Mistakes:
  • Overwriting variables without temp storage
  • Using '=' instead of ':=' for assignment
  • Not declaring temporary variable

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes