, , ,

Inline view : Subqueries in a from Clause

You can also write subqueries that appear in your from clause. Writing subqueries in the from clause of the main query can be a handy way to collect an intermediate set of data that the main query treats as a table for its own query-access purposes. This subquery in the from clause of your main query is called an inline view. You must enclose the query text for the inline view in parentheses and also give a label for the inline view so that columns in it can be referenced later. The subquery can be a select statement that utilizes joins, the group by clause, or the order by clause
Select a.PO_HEADER_ID, a.Segment1, b.unit_price, b.Quantity
Select unit_price, Quantity, po_header_id
) b
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
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *