Sub topic 12
How Oracle logically processes a query
This chapter assumes you can write a basic SELECT ... FROM ... WHERE ... ORDER BY statement and know what a column alias is. It also assumes you have run queries against the HR sample schema. Here you learn the order in which Oracle logically evaluates the clauses of a query. That order explains most "why can't I use my alias here?" errors.
Written order and logical order
You write a query in this order:
SELECT ... FROM ... WHERE ... GROUP BY ... HAVING ... ORDER BY ... FETCH FIRST ...Oracle does not evaluate it that way. The statement starts with SELECT, but the select list is evaluated near the end. Conceptually, Oracle first finds the rows, then filters them, then computes the output columns, and finally sorts and trims the result.
The order described here is the logical one. It defines what the query means, and the result must be the same as if the steps ran in this order. The optimizer is free to execute the query differently: it can use an index, push filters down, or reorder joins. It must still return the answer the logical order defines. The logical order is therefore the right model for predicting results and errors. It is not a guide to performance.
The steps in order
| Step | Clause | What happens | Can it use a SELECT-list alias? |
|---|---|---|---|
| 1 | FROM | Identify the row source: a table, a view, a join, or `dual` | No, aliases do not exist yet |
| 2 | WHERE | Keep only rows for which the condition is TRUE | No |
| 3 | GROUP BY | Collapse rows into groups | No (see the callout below) |
| 4 | HAVING | Keep only groups for which the condition is TRUE | No (see the callout below) |
| 5 | SELECT | Evaluate the expressions in the select list and name the columns | Defines the aliases |
| 6 | DISTINCT | Remove duplicate result rows | Not applicable |
| 7 | ORDER BY | Sort the result | Yes |
| 8 | FETCH FIRST | Return only the first rows of the sorted result | Not applicable |
This chapter focuses on steps 1, 2, 5, 6, 7 and 8, the clauses you have seen so far. GROUP BY and HAVING are listed so you can see where they fit.
Why a WHERE clause cannot see an alias
An alias is created in step 5. WHERE runs in step 2, so the alias does not exist yet when the filter is evaluated. This query fails:
SELECT employee_id, salary * 12 AS annual_salary
FROM employees
WHERE annual_salary > 100000;Oracle reports ORA-00904: "ANNUAL_SALARY": invalid identifier. There are two standard fixes. The first repeats the expression in the WHERE clause:
SELECT employee_id, salary * 12 AS annual_salary
FROM employees
WHERE salary * 12 > 100000;The second moves the calculation into an inline view. The inner query finishes its SELECT step first, so the outer query can filter on the alias:
SELECT employee_id, annual_salary
FROM (
SELECT employee_id, salary * 12 AS annual_salary
FROM employees
)
WHERE annual_salary > 100000;The inline view is the better choice when the expression is long or when you would otherwise repeat it several times.
Why ORDER BY can see an alias
ORDER BY runs after the select list, so the alias is available:
SELECT last_name, salary * 12 AS annual_salary
FROM employees
WHERE department_id = 50
ORDER BY annual_salary DESC, last_name;ORDER BY also accepts a column's position in the select list, such as ORDER BY 2 DESC. Position numbers break silently when someone edits the select list, so prefer names or aliases in code you keep.
ORDER BY can also sort by a column that is not in the select list, as long as DISTINCT is not used. The next section explains why that restriction exists.
DISTINCT and ORDER BY together
DISTINCT (step 6) works on the finished select list. When ORDER BY runs, each output row represents a set of identical rows, so a column outside the select list has no single value to sort by. Oracle rejects the query:
SELECT DISTINCT department_id
FROM employees
ORDER BY salary;The error is ORA-01791: not a SELECTed expression. Sort only by what you select:
SELECT DISTINCT department_id
FROM employees
ORDER BY department_id;If you need another sort key, include it in the select list. Doing so changes what "distinct" means, because uniqueness now applies to the combination of columns.
FETCH FIRST works on the sorted result
FETCH FIRST is the last step, so it keeps the first rows after sorting:
SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 5 ROWS ONLY;Because it follows ORDER BY, this returns the five highest salaries. If several employees tie for the fifth place, ROWS ONLY returns just one of them, and which one is not guaranteed. To include every tied row, use FETCH FIRST 5 ROWS WITH TIES. This requires an ORDER BY clause.
Without ORDER BY, FETCH FIRST returns an arbitrary set of rows. Oracle does not guarantee any row order unless you ask for one.
The ROWNUM trap
Before Oracle Database 12c, people limited rows with the ROWNUM pseudocolumn, and you will still meet it in older code. Oracle assigns ROWNUM as rows pass the WHERE step, which is before ORDER BY. This query does not return the five highest salaries:
SELECT employee_id, last_name, salary
FROM employees
WHERE ROWNUM <= 5
ORDER BY salary DESC;Oracle takes any five rows first and then sorts only those five. The old fix puts the sort in an inline view so it finishes before ROWNUM is applied:
SELECT employee_id, last_name, salary
FROM (
SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary DESC
)
WHERE ROWNUM <= 5;On Oracle Database 12c and later, FETCH FIRST is simpler and is the standard syntax.
The logical order also applies to DUAL
DUAL is a row source like any other table, so WHERE filters it too. The next query starts with one row from dual. The condition 1 = 0 is false for that row, so the query returns no rows:
SELECT SYSDATE AS today
FROM dual
WHERE 1 = 0;This is a useful way to confirm that a SELECT against DUAL is not a special case. A query on DUAL also does not always return exactly one row. It returns one row only when nothing filters it out.
NULL and the sort step
WHERE keeps a row only when its condition is TRUE. A comparison with NULL such as commission_pct = NULL is neither true nor false, so those rows are dropped. This is why you write IS NULL.
ORDER BY runs after WHERE, so it only sorts the rows that survived. In Oracle, NULLs sort last in ascending order and first in descending order by default. You can override this:
SELECT last_name, commission_pct
FROM employees
WHERE department_id = 80
ORDER BY commission_pct DESC NULLS LAST, last_name;Because ORDER BY follows the select list, the same query can sort by a computed alias, such as NVL(commission_pct, 0) AS commission.
A combined example
Read this query in logical order, not written order:
SELECT DISTINCT job_id, salary * 12 AS annual_salary
FROM employees
WHERE department_id IN (50, 80)
AND commission_pct IS NULL
ORDER BY annual_salary DESC
FETCH FIRST 3 ROWS ONLY;FROM employeesmakes the whole table the row source.WHEREkeeps employees in departments 50 or 80 with no commission.SELECTcomputesjob_idandannual_salaryfor each remaining row.DISTINCTremoves repeated pairs ofjob_idandannual_salary.ORDER BYsorts the pairs by the alias, highest first.FETCH FIRSTkeeps the top three.
Common errors and what they mean
| Error | Typical cause | Logical-order explanation |
|---|---|---|
| `ORA-00904: invalid identifier` | Alias used in `WHERE` | `WHERE` runs before the alias exists |
| `ORA-01791: not a SELECTed expression` | `DISTINCT` with `ORDER BY` on a column not selected | Rows are already collapsed when sorting |
| `ORA-00934: group function is not allowed here` | Aggregate such as `COUNT(*)` in `WHERE` | Groups do not exist until after `WHERE` |
| Wrong "top N" rows | `ROWNUM <= n` with `ORDER BY` in the same query | `ROWNUM` is assigned before sorting |
Summary
- Oracle logically evaluates
FROM,WHERE,GROUP BY,HAVING,SELECT,DISTINCT,ORDER BY,FETCH FIRST, in that order. - Aliases are created at the
SELECTstep, soORDER BYcan use them andWHEREcannot. DISTINCThappens before sorting, soORDER BYcan only use selected expressions.FETCH FIRSTtrims the sorted result, butROWNUMis assigned before sorting.WHEREfiltersDUALjust like any other table.
Exercise
This query fails with ORA-00904. Explain why in terms of processing order, then rewrite it so it works. SELECT lastname, salary + NVL(commissionpct, 0) * salary AS totalpay FROM employees WHERE totalpay > 10000;
Show answer
WHERE is evaluated in step 2, but the alias total_pay is created by the SELECT list in step 5, so the name does not exist when the filter runs. Repeat the expression in WHERE: WHERE salary + NVL(commission_pct, 0) * salary > 10000. Or wrap the calculation in an inline view and filter on total_pay in the outer query.
Exercise
A developer wants the three lowest-paid employees and writes SELECT last_name, salary FROM employees WHERE ROWNUM <= 3 ORDER BY salary;. Why is the result wrong, and what is a correct query on Oracle Database 12c or later?
Show answer
ROWNUM is assigned as rows pass WHERE, before ORDER BY, so Oracle takes any three rows and then sorts only those. A correct query is SELECT last_name, salary FROM employees ORDER BY salary FETCH FIRST 3 ROWS ONLY;. Add WITH TIES instead of ONLY if tied salaries at the cutoff must all be returned.
Exercise
What does SELECT 'x' AS letter FROM dual WHERE 1 = 2; return, and why?
Show answer
It returns no rows. FROM dual supplies one row, but WHERE 1 = 2 evaluates to false for it, so the row is filtered out before the select list produces any output.