Sub topic 3
Working with NULL, Sorting, Duplicates, and Row Limits
This section assumes you can write a basic SELECT ... FROM query, connect to an Oracle session, and query the HR sample schema.
Working with NULL
A NULL means a value is missing or unknown. Any comparison with NULL using = or <> evaluates to unknown, so a WHERE clause never matches it. Use IS NULL or IS NOT NULL instead. NVL(expr, default) returns the default when expr is NULL.
SELECT first_name, last_name, NVL(commission_pct, 0) AS commission
FROM employees
WHERE commission_pct IS NULL OR commission_pct > 0.2;::: callout note A WHERE clause keeps only rows where the condition is TRUE. Rows where it is unknown are dropped. :::
Sorting with ORDER BY
ORDER BY sorts the result. DESC sorts high to low, and the default is ASC. Add a second column to break ties.
SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary DESC, last_name;Removing duplicates with DISTINCT
DISTINCT returns each combination of selected values once. It applies to the whole select list, not to a single column.
SELECT DISTINCT department_id
FROM employees
ORDER BY department_id;Limiting rows with FETCH FIRST
Oracle Database 12c and later support FETCH FIRST n ROWS ONLY. It returns at most n rows after sorting.
SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 5 ROWS ONLY;How Oracle logically processes a query
Oracle evaluates clauses in a fixed logical order, not in the order you write them. The diagram shows that order.
Because SELECT runs after WHERE, you cannot use a column alias from the select list inside WHERE.
SELECT without FROM in Oracle Database 23ai
Oracle Database 23ai accepts a SELECT with no FROM clause. Earlier releases require FROM dual.
| Release | `SELECT 1 + 1 AS two;` |
|---|---|
| 23ai and later | Returns one row |
| Earlier releases | Fails; use `SELECT 1 + 1 AS two FROM dual;` |
Exercise
Which query returns the employees with no commission, sorted by last name, without duplicate departments?
Show answer
SELECT DISTINCT departmentid FROM employees WHERE commissionpct IS NULL ORDER BY department_id; DISTINCT applies to the selected column, so it returns each department once. The sort uses ORDER BY on that same column.