Sub topic 7
LIKE and Leading Wildcards
This chapter assumes that you know basic SELECT and WHERE syntax, Oracle data types, and the general purpose of a B-tree index. You should also be able to inspect an execution plan with DBMS_XPLAN.
How Oracle searches a LIKE pattern
The LIKE operator compares text with a pattern:
%matches zero or more characters._matches exactly one character.- Other characters match themselves.
A B-tree index stores text in sorted order. Oracle can use that order when the pattern starts with known characters. For example, Smi% identifies a contiguous part of the index, so Oracle can perform an index range scan.
-- A fixed prefix can be used to find an index range
SELECT customer_id, last_name
FROM customers
WHERE last_name LIKE 'Smi%';
-- A leading wildcard gives Oracle no starting point in the index
SELECT customer_id, last_name
FROM customers
WHERE last_name LIKE '%ith';The second query may use a full table scan because every value must be examined for a suffix match. The optimizer can choose other access paths in some situations, but a normal B-tree range scan cannot efficiently start with %.
Pattern behavior and selectivity
A pattern such as Smi_ can use the known prefix Smi, but Oracle must test the remaining character. A pattern such as _mith has no fixed prefix and normally cannot use a range scan.
| Pattern | Possible B-tree range scan | Reason |
|---|---|---|
| `'Smi%'` | Yes | The prefix `Smi` defines an index range |
| `'Smi_'` | Yes, with filtering | The prefix is known, but `_` still needs testing |
| `'%ith'` | No range scan | The first character is unknown |
| `'%mi%'` | No range scan | The pattern begins with a wildcard |
The optimizer also considers selectivity. Selectivity is the fraction of rows expected to match. If S% matches most rows, a full table scan may cost less than using the index and then visiting many table blocks. Index availability does not guarantee index usage.
Escaping wildcard characters
Use an ESCAPE character when the value itself contains % or _. In this example, \% means a literal percent sign.
SELECT product_id, product_code
FROM products
WHERE product_code LIKE 'A\%B%' ESCAPE '\';This finds codes that begin with the literal text A%B. The final % remains a wildcard.
Case and expressions
LIKE comparisons can be case-sensitive depending on the database settings and collation. Applying UPPER or LOWER to the column makes the expression non-sargable for an ordinary index:
SELECT customer_id
FROM customers
WHERE UPPER(last_name) LIKE 'SMI%';If this search is required, create a matching function-based index and use the same expression in the predicate.
Exercise
Which pattern is more likely to use an index range scan on last_name: '%son' or 'Son%'?
Show answer
'Son%' because the fixed prefix lets Oracle identify a contiguous range in the B-tree index.