| Lesson 7 | Complex Boolean logic and optional filters |
| Objective | Rewrite optional Boolean search conditions with set operators while preserving results and evaluating performance with execution evidence. |
An online search may accept several optional inputs. A compact WHERE clause can express all combinations, while a compound query can separate them into simpler cases. Before choosing between these forms, establish that they return the same results, including repeated values and rows containing nulls.
This lesson revisits a legacy tuning example for Oracle 26ai. Rewriting the SQL can be useful, but neither longer SQL nor the presence of a set operator guarantees better performance. The corrected rewrite below uses UNION ALL because ordinary UNION would change the duplicate behavior of the original query.
Assume the illustrative STUDENT table has the columns shown below. The colon-prefixed placeholders are bind variables supplied by the calling environment. Their datatypes should be compatible with the columns being compared; the application binds values rather than inserting raw input into the SQL text.
SELECT s.student_name
FROM student s
WHERE (s.student_nbr = :hostvar_student OR :hostvar_student IS NULL)
AND (s.social_security_nbr = :hostvar_social OR :hostvar_social IS NULL);
A null bind disables its corresponding filter. When both inputs are supplied, the AND between the optional conditions requires both identifiers to match the same row. This is not a request to return anyone matching either identifier.
| Student bind | Social bind | Required result |
|---|---|---|
| Non-null | Null | Match student_nbr. |
| Null | Non-null | Match social_security_nbr. |
| Non-null | Non-null | Match both identifiers on the same row. |
| Null | Null | Return every row. |
If supplied identifiers refer to different students, the query may return no rows. A null bind does not mean “find a null identifier.” It means that condition imposes no restriction. With a non-null bind, a null column comparison is UNKNOWN and does not pass; with both binds null, even rows with null identifiers are included.
UNION returns distinct selected rows. UNION ALL preserves all selected rows, including duplicates. The difference concerns the projected values, not whether the underlying records represent different people.
Suppose two students have the name Alex and both are returned by a search. The original SELECT, which has no DISTINCT, returns two occurrences of Alex. A compound query using UNION can reduce them to one because only student_name is selected. This can happen even when the duplicate names come from the same branch.
Adding a unique identifier to the projection would change the output contract. It is not a silent repair for a query whose required result is the original name column. Use UNION when distinct projected rows are the intended result; use UNION ALL here to preserve the original multiplicity.
Each branch below has explicit guards for one combination of null and non-null inputs. The selected column remains the same:
SELECT s.student_name
FROM student s
WHERE :hostvar_student IS NOT NULL
AND :hostvar_social IS NULL
AND s.student_nbr = :hostvar_student
UNION ALL
SELECT s.student_name
FROM student s
WHERE :hostvar_student IS NULL
AND :hostvar_social IS NOT NULL
AND s.social_security_nbr = :hostvar_social
UNION ALL
SELECT s.student_name
FROM student s
WHERE :hostvar_student IS NOT NULL
AND :hostvar_social IS NOT NULL
AND s.student_nbr = :hostvar_student
AND s.social_security_nbr = :hostvar_social
UNION ALL
SELECT s.student_name
FROM student s
WHERE :hostvar_student IS NULL
AND :hostvar_social IS NULL;
For a fixed pair of bind values, exactly one branch has true bind-state guards. That eligible branch can still return zero, one, or many rows. The guards prevent one base row from contributing through multiple branches, while UNION ALL preserves duplicate names from separate rows within the eligible branch.
The fourth branch is essential to equivalence: both null inputs return every row. If an application should reject an empty search, requiring an input is a separate behavior change. Omitting the fourth branch would not preserve the original query.
This construction does not justify replacing every OR with UNION ALL. General OR branches can overlap, causing a row to be returned twice, and exclusions must respect SQL null semantics. Here, exclusivity follows specifically from the four bind-state cases. Neither UNION nor UNION ALL guarantees displayed row order without an appropriate final ORDER BY.
Separating optional cases can expose simpler predicates and useful access paths. However, Oracle's optimizer understands the original Boolean expression; a full scan does not mean it became confused. Modern Oracle can consider transformations such as OR expansion when applicable and estimated to be beneficial. That does not mean this particular statement must be transformed automatically.
The best access path depends on available indexes, statistics, selected columns, data volume, and input values. Column names do not establish uniqueness or prove that a specific composite index exists. A full scan may be appropriate for the both-null request because that request returns the entire table.
A plan can also contain operations beneath branches that did not run for a particular execution. Where execution statistics are collected, operation starts and actual rows help distinguish listed operations from work that occurred. The presence of four branches alone proves neither four scans nor automatic physical elimination of the unused branches.
UNION requires duplicate elimination, whereas UNION ALL does not perform that elimination. This difference is relevant to cost, but it does not guarantee a particular sorting algorithm or a speedup for the complete query. No execution plan or timing is claimed for the illustrative statements on this page.
Validate all four input cases before evaluating a rewrite. Include student-only and social-only searches, no-match inputs, both identifiers matching, and conflicting identifiers. The both-null case should include rows with duplicate names and null identifiers.
Compare the returned values and their occurrence counts, not just the number of rows or the distinct names. A distinct comparison such as MINUS alone can miss duplicate-count differences. The two-Alex example provides a simple correctness check that exposes the problem with the legacy UNION rewrite.
Once equivalence is established, compare execution evidence for representative values, including frequent and infrequent matches where relevant. Assess actual work and elapsed time under comparable conditions. No Oracle SQL or benchmark has been executed for this lesson.
An application can alternatively select one of four predefined parameterized statement shapes based on which inputs are present. Values should remain bound. This avoids one large compound statement but moves case selection and maintenance into application code; it still requires the same correctness and performance checks.
Rewriting optional filters is therefore a choice to evaluate, not a universal cure for full scans. Continue to the historical rule-based optimization overview with the distinction between preserving SQL meaning and changing an execution strategy in mind.