Home

CASE should be used rather than DECODE

Description

    The CASE statement in PL/SQL is used to select one of several blocks of statements based on a given condition. It is similar to the DECODE statement, but it is more powerful and more flexible. The CASE statement can be used to replace multiple DECODE statements, making the code more readable and efficient. The CASE statement can also be used to evaluate multiple conditions and execute different statements based on the result.

Key Benefits

  • Simplicity: CASE is simpler to use than DECODE, as it requires fewer lines of code.
  • Ease of Maintenance: CASE is easier to maintain than DECODE, as it is easier to read and understand.
  • Flexibility: CASE allows for more flexibility than DECODE, as it can be used to compare multiple values.
  • Performance: CASE is more efficient than DECODE, as it requires fewer calculations.

 

Non-compliant Code Example

SELECT Id,
DECODE (statecode, 101, 'New York', --Non compliant code
    201, 'New Jersey', 
    301, 'Seattle', 
    401, 'San Francisco',
    'Unknown') 
"Service Center Location"
FROM cars
WHERE cars.Id < 1000; 

Compliant Code Example

SELECT Id,
       CASE statecode --Compliant code
			WHEN 101 THEN 'New York' 
			WHEN 201 THEN 'New Jersey' 
			WHEN 301 THEN 'Seattle' 
			WHEN 401 THEN 'San Francisco'
			Else 'Unknown'
		END
FROM cars
WHERE Id < 1000;
Visual Expert 2024
 VEPLSQLRULE87