11. Advanced Searching

Paginating Through a Result Set

We want to paginate a result set. For example, we want to return the first five rows from a table, then the next five, and so forth.

There is no concept of first, last, or next in SQL, and we must impose order on the rows needed.

with series as 
(
select rownum id, level*10 data from dual 
connect by level <= 10
) 
select * from series where id between 1 and 5;

Skipping n Rows from a Table

We want to skip the second or fourth or nth row from a result set.

To skip the second or fourth or nth row from a result set, we must impose order on the result set

-- Skip even-numbered rows
select ename
from (
    select row_number() over (order by ename) rn,
    ename
    from emp
) x
where mod(rn,2) = 1

Incorporating OR Logic When Using Outer Joins

We want to return the name and department information for all employees in departments 10 and 20 along with department information for departments 30 and 40 (but no employee information).

Selecting the Top n Records

We want to limit a result set to a specific number of records based on a ranking of some sort. For example, you want to return the names and salaries of the employees with the top five salaries.

Finding Records with the Highest and Lowest Values

We want to find the employees with the highest and lowest salaries in table EMP.

Investigating Future Rows

We want to find any employees who earn less than the employee hired immediately after them. Based on the following result set: ENAME SAL HIREDATE

SMITH, WARD, MARTIN, JAMES, and MILLER earn less than the person hired immediately after they were hired, so those are the employees you want to find with a query.

Shifting Row Values

We want to return each employee’s name and salary along with the next highest and lowest salaries. If there are no higher or lower salaries, then results to wrap (first SAL shows last SAL and vice versa)

Sample result set

Ranking Results

We want to rank the salaries in table EMP like below while allowing for ties.

Suppressing Duplicates

We want to find the distinct different job types in table EMP

Finding Knight Values

We want to return a result set that contains each employee’s name, the department they work in, their salary, the date they were hired, and the salary of the last employee hired, in each department.

Sample result set

Generating Simple Forecasts

We want to return additional rows and columns representing future actions. For example, consider the following input data. We want to return three rows per row returned in the result set (each row plus two additional rows for each order). Along with the extra rows, we would like to return two additional columns providing dates for expected order processing.

Order takes two days to process. Verification occurs one day after processing, and shipment occurs one day after verification.

Sample Input

Sample Output

Last updated