Inline view : Subqueries in a from Clause
Select a.PO_HEADER_ID, a.Segment1, b.unit_price, b.Quantity
From PO_HEADERS_ALL a,
(
Select unit_price, Quantity, po_header_id
From PO_LINES_ALL
) b
Where a.PO_HEADER_ID=b.PO_HEADER_ID
Inline Views and Top-N QueriesTop-N queries use inline views and are handy for displaying a short list of table data, based on “greatest” or “least” criteria. For example, let’s say that profits for our company were exceptionally strong this year, and we want a list of the three lowest-paid employees in our company so that we could give them a raise. A top-N query would be useful for this purpose. Take a look at a top-N query that satisfies this business scenario:
SQL> select ename, job, sal, rownum
2 from (select ename, job, sal from emp
3 order by sal)
4 where rownum <=3;
ENAME JOB SAL ROWNUM
———- ——— ——— ———
SMITH CLERK 800 1
JAMES CLERK 950 2
ADAMS CLERK 1100 3
You need to know two important things about top-N queries for OCP. The first is their use of the inline view to list all data in the table in sorted order. The second is their use of ROWNUM—a virtual column identifying the row number in the table—to determine the top number of rows to return as output. Conversely, if we have to cut salaries based on poor company performance and want to obtain a listing of the highest-paid employees, whose salaries will be cut, we would reverse the sort order inside the inline view, as shown here:
SQL> select ename, job, sal, rownum
2 from (select ename, job, sal from emp
3 order by sal desc)
4 where rownum <=3;
ENAME JOB SAL ROWNUM
———- ——— ——— ———
KING PRESIDENT 5000 1
SCOTT ANALYST 3000 2
FORD ANALYST 3000 3
Leave a Reply
Want to join the discussion?Feel free to contribute!