Sub topic 10
Using the functions in WHERE, UPDATE, and ORDER BY
This chapter assumes you can already call SUBSTR, INSTR, and REPLACE in a SELECT list. You should know that INSTR returns 0 when it finds no match, that a SUBSTR start position of 0 behaves like 1, and that a NULL argument gives a NULL result. Here you apply those functions to filter rows, change stored data, and control sort order. Each placement has its own failure modes.
The working model
SUBSTR, INSTR, and REPLACE are ordinary scalar functions. Anywhere Oracle accepts an expression, you can put a call to one of them. The clause you choose decides three things:
- how many rows the function runs against,
- whether an index can still help,
- what a NULL or a zero result does to the statement.
The examples below use one small table. Run this first.
CREATE TABLE contacts (
contact_id NUMBER PRIMARY KEY,
full_name VARCHAR2(60),
email VARCHAR2(80),
phone VARCHAR2(20),
file_name VARCHAR2(100)
);
INSERT INTO contacts VALUES (1, 'Smith, John', '[email protected]', '(555) 123-4567', 'report.final.pdf');
INSERT INTO contacts VALUES (2, 'Garcia, Maria', '[email protected]', '555-987-6543', 'notes.txt');
INSERT INTO contacts VALUES (3, 'Lee, Wei', '[email protected]', '555 222 3333', 'archive');
INSERT INTO contacts VALUES (4, 'Nguyen', NULL, NULL, 'photo.JPG');
COMMIT;Row 4 is deliberately awkward. It has no comma in the name, no email, and no phone number. Most of the problems in this chapter come from rows like it.
Functions in WHERE
Filtering on a parsed piece
To keep rows whose email domain is example.com, parse the domain in the WHERE clause.
SELECT contact_id, email
FROM contacts
WHERE SUBSTR(email, INSTR(email, '@') + 1) = 'example.com';This returns rows 1 and 3. Row 2 is excluded because Example.org differs in case and in suffix. Row 4 is excluded because INSTR(NULL, '@') is NULL, the whole expression is NULL, and a comparison with NULL is never true. A NULL does not raise an error. The row silently drops out.
For a case-insensitive match, wrap the parsed piece in LOWER:
SELECT contact_id, email
FROM contacts
WHERE LOWER(SUBSTR(email, INSTR(email, '@') + 1)) = 'example.org';INSTR as a "contains" test
Comparing INSTR with 0 tells you whether a substring is present.
SELECT contact_id, full_name
FROM contacts
WHERE INSTR(full_name, ',') > 0;This returns rows 1 to 3. Use = 0 to find the rows that lack the delimiter, which is how you audit data before parsing it:
SELECT contact_id, file_name
FROM contacts
WHERE INSTR(file_name, '.') = 0;This returns archive. LIKE '%,%' gives the same answer for a plain contains test. Prefer INSTR when you need the position or the Nth occurrence, and LIKE when you only need a yes or no.
Prefix tests and indexes
A normal B-tree index on file_name can serve LIKE 'report%'. It cannot serve INSTR(file_name, 'report') = 1, because the function wraps the column. Use LIKE for prefix searches.
When you must filter on an expression, create a function-based index on exactly that expression:
CREATE INDEX contacts_domain_ix
ON contacts (SUBSTR(email, INSTR(email, '@') + 1));SUBSTR, INSTR, and REPLACE are deterministic, so this is allowed. The optimizer considers the index only when the query repeats the same expression. LOWER(SUBSTR(...)) is a different expression and needs its own index.
Evaluation order is not guaranteed
Do not write WHERE INSTR(x, ',') > 0 AND SUBSTR(x, 1, INSTR(x, ',') - 1) = 'Smith' and expect the first condition to protect the second. Oracle may evaluate AND conditions in any order. For SUBSTR and INSTR this rarely raises an error, but it does for functions such as TO_NUMBER (shown later). If a guard matters, put it in a CASE expression, which does evaluate in order:
SELECT contact_id, file_name,
CASE WHEN INSTR(file_name, '.') > 0
THEN LOWER(SUBSTR(file_name, INSTR(file_name, '.', -1) + 1))
END AS ext
FROM contacts;The extensions come back as pdf, txt, NULL, and jpg. Without the CASE, archive would produce archive as its "extension". INSTR returns 0 when the dot is missing, 0 + 1 is 1, and SUBSTR(file_name, 1) is the whole string.
Aliases are not visible in WHERE
A column alias defined in the SELECT list cannot be used in WHERE of the same query. Wrap the query in an inline view:
SELECT contact_id, domain
FROM (SELECT contact_id,
SUBSTR(email, INSTR(email, '@') + 1) AS domain
FROM contacts)
WHERE domain = 'example.com';The diagram shows why. WHERE runs before the SELECT list exists, and ORDER BY runs after it.
Functions in UPDATE
Cleaning a column with nested REPLACE
In an UPDATE, the functions rewrite stored data. To keep only digits in phone, strip each unwanted character in turn:
UPDATE contacts
SET phone = REPLACE(REPLACE(REPLACE(REPLACE(phone, '(', ''), ')', ''), ' ', ''), '-', '')
WHERE phone IS NOT NULL;The phone values become 5551234567, 5559876543, and 5552223333. Before running any UPDATE like this, run the same expression in a SELECT and read the output. Check the "rows updated" count afterward. If it is wrong, issue ROLLBACK before COMMIT.
Filling new columns from a split
You can also derive new columns from an existing one:
ALTER TABLE contacts ADD (last_name VARCHAR2(40), first_name VARCHAR2(40));
UPDATE contacts
SET last_name = SUBSTR(full_name, 1, INSTR(full_name, ',') - 1),
first_name = SUBSTR(full_name, INSTR(full_name, ',') + 2)
WHERE INSTR(full_name, ',') > 0;Two points matter here.
- Old values on the right. Every right-hand expression in SET sees the row as it was before the statement changed it. The order of assignments does not matter, and you can safely read
full_namein both. - The WHERE clause is a safety guard. Without it, row 4 (
Nguyen) getslast_name = NULL, because the length0 - 1is below 1. It also getsfirst_name = 'guyen', becauseINSTRreturned 0 and0 + 2is position 2. That is wrong data with no error. Always exclude rows that lack the delimiter, or handle them with CASE.
Functions in ORDER BY
Sorting on a derived key
ORDER BY accepts any expression. To sort by domain, with the NULL email last:
SELECT contact_id, email
FROM contacts
ORDER BY SUBSTR(email, INSTR(email, '@') + 1);Oracle sorts NULLs last in ascending order. Add NULLS FIRST to change that. To sort by last name, with a fallback for names that have no comma, use CASE:
SELECT contact_id, full_name
FROM contacts
ORDER BY CASE WHEN INSTR(full_name, ',') > 0
THEN SUBSTR(full_name, 1, INSTR(full_name, ',') - 1)
ELSE full_name
END;The order is Garcia, Lee, Nguyen, Smith.
Sorting text that contains numbers
A plain string sort puts INV-10 before INV-2, because the character 1 sorts before 2. Extract the number and convert it:
WITH invoices AS (
SELECT 'INV-2' AS code FROM dual UNION ALL
SELECT 'INV-10' FROM dual UNION ALL
SELECT 'INV-1' FROM dual
)
SELECT code
FROM invoices
ORDER BY TO_NUMBER(SUBSTR(code, INSTR(code, '-') + 1));The result is INV-1, INV-2, INV-10. If any row has a non-numeric suffix, TO_NUMBER raises ORA-01722 and the whole query fails. Clean or filter the data first.
Aliases and DISTINCT
ORDER BY can use a select-list alias, because it runs after the SELECT list. With SELECT DISTINCT, though, every ORDER BY expression must appear in the select list. Otherwise Oracle raises ORA-01791 (not a SELECTed expression).
Choosing the clause
| Clause | What the function does | Main risk |
|---|---|---|
| WHERE | Decides which rows qualify | NULL results drop rows silently. Wrapping a column blocks a normal index. |
| UPDATE ... SET | Rewrites stored values | Rows without the delimiter get wrong data unless guarded. |
| UPDATE ... WHERE | Limits which rows change | An unguarded statement rewrites every row. |
| ORDER BY | Builds a sort key | Conversion errors such as ORA-01722. NULLs sort last by default. |
Practice
Exercise
Write a query that returns the contact_id of every contact whose file extension is pdf, in any letter case. Does a name with no dot, such as archive, need a separate guard in this particular query?
Show answer
SELECT contactid FROM contacts WHERE LOWER(SUBSTR(filename, INSTR(file_name, '.', -1) + 1)) = 'pdf'; The backward INSTR finds the last dot, so report.final.pdf gives pdf. For archive, INSTR returns 0, so SUBSTR returns the whole string archive, which is not equal to pdf. No guard is needed for a pdf test, but a guard would be required for a name such as pdf with no dot, which would match wrongly.
Exercise
Row 4 has fullname 'Nguyen' and no comma. What do lastname and first_name become if you run the split UPDATE without its WHERE clause, and why?
Show answer
lastname becomes NULL, because SUBSTR(fullname, 1, INSTR(fullname, ',') - 1) is SUBSTR('Nguyen', 1, -1) and a length below 1 returns NULL. firstname becomes 'guyen', because INSTR returns 0 and 0 + 2 starts the extraction at position 2. The fix is WHERE INSTR(full_name, ',') > 0, or a CASE expression.