Conditional Logic in SQL statements


I have been banging my head on the desk trying to debug an SQL statement that returns the wrong result. Or so the developer says.

The problem is understand the restriction (WHERE clause) on the SQL statement. It consists of twenty (20) sub-clauses combined in a complex way. Intermixed among these are the table join clauses.

It took me a while to realise that there were several SQL statements combined into one through the use of bind variable clauses. For example, instead of writing the following PL/SQL code:

IF p_search_term = 'NAME' THEN
  OPEN l_search_csr FOR
    SELECT name FROM emp WHERE name LIKE p_search_value;
ELSE IF p_search_term = 'DEPT' THEN
  OPEN l_search_csr FOR
    SELECT name FROM emp WHERE dept = TO_NUMBER(p_search_value);
ELSE
  OPEN l_search_csr FOR
    SELECT name FROM emp;
END IF;

The following SQL code was used instead:

SELECT
    name
  FROM
    emp
  WHERE
      ( :1 = 'NAME' AND name LIKE :2 )
	OR
	  ( :1 = 'DEPT' AND dept = TO_NUMBER( :2 ) )
	OR
	  ( :1 IS NULL )
;

Yes, I know Tom Kyte says to use SQL statements in preference to PL/SQL, but this obscures the logic. And it forces the CBO to do a full table scan. Yes, I know that adaptive SQL plans can get around this through examining the bind variables for bad plans. Still it is no subsitute for clear thinking about what you are trying to achieve.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s