Order by clause in Sub query
Hi,
Can we use order by clause in Sub query?
While using the order by clause, I am getting the "missing expression error" . If I remove order by clause query executing fine.
Here is my query:
select *
from emp_mstr
where emp_no in(select
emp_no
from emp_mstr
order by branch_no);
Thanks & Regards,
Mahi
May be you miss some required spaces also, other than wrong use of ORDER BY
select *
from emp_mstr
where emp_no in
( select e2.emp_no
from emp_mstr e2
-- order by e2.branch_no
);Why do you want to ORDER BY in the subquery, which you use with IN clause? That will not make any difference in the result..Means the result you get with ORDER BY will be same as without that.. And in this case, ORDER by is a unncessary overhead.. And Ordering is very costly..
And why do you want to have the IN clause at all in your query? You are referring the same tables in the main query and sub query..
The below will give the same result
select *
from emp_mstr
where emp_no is not nullIf you want to use another table in the subquery, always use aliasess...
select *
from emp_mstr
where emp_no in
( select e2.emp_no
from emp_mstr2 e2
-- order by e2.branch_no
);
Similar Messages
-
Suppress "Order By" clause in Answers Query
Hello,
Is it possible to Suppress "Order By" clause in Answers Query.
I'm using a database view as data source. In the view definition, "order by" clause is already specified. Is it possible to get the same order in the OBIEE report??
I do not want to use Sort Order column in the repository.
Thanks,
GirishYou add a rownumber to your DB view and use that to 'sort' your report.
regards
John
http://obiee101.blogspot.com/ -
Order by clause with Named Query
hi
i have to give order by clause in Named Query
how we have to specify is can any body help
thanks
HarishAssuming an Entity called Handset:
select h from Handset h order by h.description -
IS IT POSSIBLE TO WRITE ORDER BY CLAUSE WITHIN INNER QUERY
IS IT POSSIBLE TO WRITE ORDER BY CLAUSE WITHIN INNER QUERY
So you still can't :) I still don't see it that strict:
You know of course that this is possible:
select ename, (select ename
from (select empno, ename
from emp
where deptno = 10
order by 1) e2
where e.empno = e2.empno) a
from emp eso we have an »ORDER BY CLAUSE WITHIN INNER QUERY« which is even correlated (though through the outer query).
Whether this makes sense or not is not question imho :-) ... but you can -
IN clause with ORDER BY clause in sub-queries
Hello,
We generate dynamic queries with the following statement pattern (could be many union/intersect sub-queries):
select my_col
from my_table
where my_col IN
select table_2.my_col , x_col from table_2 where x_col > 10
UNION
select table_3.my_col , y_col from table_3 where y_col > 20
INTERSECT
select table_4.my_col , z_col from table_4 where z_col is between 30 and 50
I know that I can do just the sub-queries w/ an ORDER BY clause as follows (as long as the 2nd parameter in the select stmts are of the same type):
select table_2.my_col , x_col from table_2 where x_col > 10
UNION
select table_3.my_col , y_col from table_3 where y_col > 20
INTERSECT
select table_4.my_col , z_col from table_4 where z_col is between 30 and 50
order by 2 desc
But my questions are:
1. What is (if there is) the syntax that will ensure that the result set order will be that of the ordering of the sub-queries?
Or does my SQL stmt have to have syntactically (but not semantically) change to achieve this?
Thanks,
JimRandolf Geist wrote:
just a minor doubt - I think it is not officially supported to have separate ORDER BYs in a compound query with set operators (e.g. UNION / UNION ALL subsets). Of course one could use inline views with NO_MERGE + NO_ELIMINATE_OBY hints, but I think the only officially supported approach is to use a single, final ORDER BY (that needs to use positional notation as far as I remember).
Randolf,
You're right, of course, about the separate "order by" clauses.
Interestingly the following type of thing does work though (in 10.2.0.3, at least):
with v1 as (
select * from t1 where col1 = 'ABC' order by col2
v2 as (
select * from t1 where col1 = 'DEF' order by col2
select * from v1
union all
select * from v2
;A quick check the execution plan suggsts that Oracle appears to be convering this to the following - even though its technically not acceptable in normal circumstances:
select * from t1 where col1 = 'ABC' order by col2
union all
select * from t1 where col1 = 'DEF' order by col2
;Regards
Jonathan Lewis
http://jonathanlewis.wordpress.com
http://www.jlcomp.demon.co.uk
To post code, statspack/AWR report, execution plans or trace files, start and end the section with the tag {noformat}{noformat} (lowercase, curly brackets, no spaces) so that the text appears in fixed format.
"Science is more than a body of knowledge; it is a way of thinking"
Carl Sagan -
[10g] Need help with order by clause in hierarchical query
I have the following sample data:
CREATE TABLE bill_test1
( parent_part CHAR(25)
, child_part CHAR(25)
, line_nbr NUMBER(5)
, qty_per NUMBER(9,5)
INSERT INTO bill_test1 VALUES ('ABC-1','ABC-10',100,1);
INSERT INTO bill_test1 VALUES ('ABC-1','ABC-20',200,2);
INSERT INTO bill_test1 VALUES ('ABC-1','ABC-30',300,3);
INSERT INTO bill_test1 VALUES ('ABC-1','HARDWARE-1',401,10);
INSERT INTO bill_test1 VALUES ('ABC-1','HARDWARE-2',402,5);
INSERT INTO bill_test1 VALUES ('ABC-10','ABC-155',100,2);
INSERT INTO bill_test1 VALUES ('ABC-10','HARDWARE-1',200,1);
INSERT INTO bill_test1 VALUES ('ABC-155','RAW-2',100,4.8);
INSERT INTO bill_test1 VALUES ('ABC-155','HARDWARE-3',200,3);
INSERT INTO bill_test1 VALUES ('ABC-20','RAW-1',100,10.2);
INSERT INTO bill_test1 VALUES ('ABC-30','RAW-3',100,3);And the query below gives me exactly what I want, in the order I want it. However, I am wondering if there is a way to get this order without creating the SEQ column, since I don't need it in my results
SELECT part_nbr
, parent_part
, child_part
FROM (
SELECT CONNECT_BY_ROOT b.parent_part AS part_nbr
, b.parent_part
, b.child_part
, SYS_CONNECT_BY_PATH(b.line_nbr,' ') AS seq
FROM bill_test1 b
, dual
CONNECT BY parent_part = PRIOR child_part
WHERE part_nbr = 'ABC-1'
ORDER BY seq
Results of above query, except with SEQ included in SELECT (just to show what I'm sorting off of):
PART_NBR PARENT_PART CHILD_PART SEQ
ABC-1 ABC-1 ABC-10 100
ABC-1 ABC-10 ABC-155 100 100
ABC-1 ABC-155 RAW-2 100 100 100
ABC-1 ABC-155 HARDWARE-3 100 100 200
ABC-1 ABC-10 HARDWARE-1 100 200
ABC-1 ABC-1 ABC-20 200
ABC-1 ABC-20 RAW-1 200 100
ABC-1 ABC-1 ABC-30 300
ABC-1 ABC-30 RAW-3 300 100
ABC-1 ABC-1 HARDWARE-1 401
ABC-1 ABC-1 HARDWARE-2 402Hi,
As long as there's only one root, you can say ORDER SIBLINGS BY, but you can't do that in a sub-query (well, you can, but usually there's no point in doing it in a sub-query). If the CONNECT BY is being done in a sub-query, there is no guarantee that the main query will preserve the hierarchical order that the sub-query provides.
The query you posted doesn't require a suib-query, so you can say:
SELECT CONNECT_BY_ROOT b.parent_part AS part_nbr
, b.parent_part
, b.child_part
--, SYS_CONNECT_BY_PATH(b.line_nbr,' ') AS seq
FROM bill_test1 b
WHERE CONNECT_BY_ROOT b.parent_part = 'ABC-1'
CONNECT BY parent_part = PRIOR child_part
ORDER SIBLINGS BY b.line_nbr
;I said the query you posted doesn't require a sub-query. It also doesn't require dual, so I suspect what you posted is a simplification of what you're really doing, and that may need a sub-query. In particular, if you intend to GROUP BY part_nbr, then you need the sub-query. We can repeat the CONNECT_BY_ROOT expression in the WHERE clause (or, now that I think about it, use a START WITH clause instead of WHERE), but, for some reason, we can't use CONNECT_BY_ROOT in a GROUP BY clause; we need to compute CONNECT_BY_ROOT in a sub-query, give it a name (like part_nbr), and GROUP BY that column in a super-query.
This assumes that there is only one root node. ORDER SIBLINGS BY means just that: children of a common parent will appear in order, but the root nodes, who have no parents, will not necessarily be in order.
Here's what I meant by using START WITH instead of WHERE:
SELECT CONNECT_BY_ROOT b.parent_part AS part_nbr
, b.parent_part
, b.child_part
--, SYS_CONNECT_BY_PATH(b.line_nbr,' ') AS seq
FROM bill_test1 b
START WITH b.parent_part = 'ABC-1'
CONNECT BY parent_part = PRIOR child_part
ORDER SIBLINGS BY b.line_nbr
;This should be much more efficient, because it narrows down the results before you waste time getting their descendants.
Using a START WITH clause here is analagous to me sending you an e-mail, saying "Come to a meeting a my office at 3:00."
Using a WHERE clause here is analagous to me sending an e-mail to everyone in the company, saying "Come to a meeting a my office at 3:00", and then, as people get here, telling everyone except you that they can go back.
ORDER SIBLINGS BY was introduced in Oracle 9.
Edited by: Frank Kulash on Dec 9, 2010 2:39 PM
Added version with START WITH clause -
Where to place ORDER BY clause when a query includes UNION
I have a query that has UNION in it. could you please tell me where to place the ORDER BY clause. Because it's throwing an error if i place the ORDER BY clause at the end
Because you are using the UNION set operator, you need to either specifically list your columns or use positional notation.
Without a set operator we can order by the column name without specifically listing it:
SQL> select * from dual
2 order by dummy;
D
X
1 row selected.This doesn't work once you introduce a set operator:
SQL> ed
Wrote file afiedt.buf
1 select * from dual union all
2 select * from dual union all
3 select * from dual
4* order by dummy
SQL> /
order by dummy
ERROR at line 4:
ORA-00904: "DUMMY": invalid identifierSo you need to either use positional notation:
SQL> ed
Wrote file afiedt.buf
1 select * from dual union all
2 select * from dual union all
3 select * from dual
4* order by 1
SQL> /
D
X
X
X
3 rows selected.Or, specifically list or alias the columns you are projecting:
SQL> ed
Wrote file afiedt.buf
1 select dummy from dual union all
2 select dummy from dual union all
3 select dummy from dual
4* order by dummy
SQL> /
D
X
X
X
3 rows selected.
SQL> ed
Wrote file afiedt.buf
1 select dummy as d from dual union all
2 select dummy as d from dual union all
3 select dummy as d from dual
4* order by d
SQL> /
D
X
X
X
3 rows selected.cheers,
Anthony -
How can i use Order by inside a sub query in Oracle
Hi!,
Please help me, it's an urgent... how can i use Order by clause
SELECT SalesProductKeyID,ActualUnitPrice,BillDateKeyID,ProductKeyID
,Qty,Profit,DD.dDate
, (SELECT nvl(S.Qty,0) FROM Stock S , DateDimension DD1
WHERE S.DateKeyID = DD1.DateKeyID AND
S.ProductKeyID = SF.ProductKeyID AND
DD1.dDate <= DD.dDate and rownum=1
ORDER BY DD1.dDate DESC*) as StockQty
, (SELECT nvl(SUM(Qty),0) from salesfact SF2,DATEDIMENSION DD2
WHERE SF2.BillDateKeyID=DD2.DatekeyID AND SF2.ProductKeyID=SF.ProductKeyid
AND DD2.dDate > DD.dDate
AND DD2.dDATE=DD.dDate
) as TotalQtySold
FROM SalesFact SF INNER JOIN DATEDIMENSION DD
ON SF.billdatekeyid =DD.Datekeyid
WHERE
IsProfitCalculated = 1 AND
IsSalesFactSuppPopulated =0 AND
Qty > 0;
kindly help
Thank you.Actually I'm converting Procedures from SQL Server to Oracle.
Actual Stored Procedure in SQL Server is as follows.
SELECT --top 10000
SalesProductKeyID,ActualUnitPrice,BillDateKeyID,ProductKeyID
,Qty,Profit,DD.Date
, (SELECT TOP 1 ISNULL(S.Qty,0) FROM dbo.Stock S , dbo.DateDimension DD1
WHERE S.DateKeyID = DD1.DateKeyID AND
S.ProductKeyID = SF.ProductKeyID AND
DD1.Date <= DD.Date
ORDER BY DD1.Date DESC) as StockQty
, (SELECT ISNULL(SUM(Qty),0) from salesfact SF2,DATEDIMENSION DD2
WHERE SF2.BillDateKeyID=DD2.DatekeyID AND SF2.ProductKeyID=SF.ProductKeyid
AND DD2.Date > DD.Date
AND DD2.DATE=DD.Date
) as TotalQtySold
--INTO TEMP_Salesfact
FROM dbo.SalesFact SF INNER JOIN DATEDIMENSION DD
ON SF.billdatekeyid =DD.Datekeyid
WHERE
IsProfitCalculated = 1 AND
IsSalesFactSuppPopulated =0 AND
Qty > 0 -
Query taking 6mins to execute wityh order by clause, 3secs without orderby
Dear All,
The below query is taking nearly 6minutes time to execute (as i have order by clause in the query)
/* Formatted on 2007/09/26 10:03 (Formatter Plus v4.8.0) */
SELECT (SELECT DISTINCT grndate
FROM fs_lg_grnhdr
WHERE grnid = pl.grnid AND custwhid = pl.custwhid)
grndate,
pl.grnid,
(SELECT DISTINCT vi.orderno
FROM fs_lg_vendorinvoicehdr vi, fs_lg_grndtl gd
WHERE gd.vendorinvoiceid = vi.vendorinvoiceid
AND gd.custwhid = vi.custwhid
AND gd.custwhid = pl.custwhid
AND gd.grnid = pl.grnid
AND gd.partid = pl.partid) orderno,
pl.expirydate, pl.batchno, pl.packuom,
NVL (pl.receiptqty, 0) receiptqty, pl.putawayid, pl.lineno,
(SELECT customscontrolno
FROM fs_lg_putawaydtl
WHERE custwhid = pl.custwhid
AND putawayid = pl.putawayid
AND partid = pl.partid
AND locationto = pl.locationid) cctrlno,
(SELECT customspermitno
FROM fs_lg_putawayhdr
WHERE custwhid = pl.custwhid
AND putawayid = pl.putawayid) cpermitno,
(SELECT SUM (pdtl.pickqty)
FROM fs_lg_pickticketdtl pdtl,
fs_lg_picktickethdr phdr
WHERE pdtl.custwhid = pl.custwhid
AND pdtl.putawayid = pl.putawayid
AND pdtl.putawaylineno = pl.lineno
AND phdr.custwhid = pdtl.custwhid
AND phdr.pickticketid = pdtl.pickticketid
AND phdr.pickdate < '01-SEP-2007'
AND pdtl.status = 'CM') previousoutqty,
(SELECT SUM (pdtl.pickqty)
FROM fs_lg_pickticketdtl pdtl,
fs_lg_picktickethdr phdr
WHERE pdtl.custwhid = pl.custwhid
AND pdtl.putawayid = pl.putawayid
AND pdtl.putawaylineno = pl.lineno
AND phdr.custwhid = pdtl.custwhid
AND phdr.pickticketid = pdtl.pickticketid
AND phdr.pickdate BETWEEN '01-SEP-2007'
AND '25-SEP-2007'
AND pdtl.status = 'CM') presentoutqty,
NVL ((SELECT SUM (qty)
FROM fs_lg_internaltransdtl
WHERE putawayid = pl.putawayid
AND fromputawaylineno = pl.lineno
AND custwhid = pl.custwhid),
0
) toistqty,
NVL ((SELECT SUM (qty)
FROM fs_lg_internaltransdtl
WHERE custwhid = pl.custwhid
AND putawayid = pl.putawayid
AND slno = pl.lineno),
0
) fromistqty
FROM fs_lg_partloads pl
WHERE pl.partid = '2ERCH-2022'
AND pl.custwhid = 'RNH-CSM'
AND inventoryflag IN ('AVAIL','')
AND pl.status = 'CM'
AND pl.grndate <= '25-SEP-2007'
ORDER BY grndate, pl.grnid, pl.putawayid, pl.lineno;
But when i don't use the order by clause it is executing within 3 seconds. But i need to get the output in the sorted order as shown in the order by clause.
Is there any way to avoid order by clause and to get the same output as with order by clasue, and i need to execute the query with less time.
Please help me in this.
Thanks in advance
MahiDear Alok Kumar,
When i execute sql>set autotrace traceonly statistics ;
I am getting the below errors...
SP2-0618: Cannot find the Session Identifier. Check PLUSTRACE role is enabled
SP2-0611: Error enabling STATISTICS report
What could be the problem, how to resolve this to get the statistics?
But when i use sql>set autotrace traceonly explain; i got the below output for the above query..
Execution Plan
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_GRNHDR'
2 1 INDEX (UNIQUE SCAN) OF 'SYS_C00293078' (UNIQUE)
3 0 SORT (UNIQUE)
4 3 NESTED LOOPS
5 4 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_GRNDTL'
6 5 INDEX (RANGE SCAN) OF 'SYS_C00293075' (UNIQUE)
7 4 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_VENDORINVOICEH
DR'
8 7 INDEX (UNIQUE SCAN) OF 'PK_VENDORINVOICE' (UNIQUE)
9 0 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_PUTAWAYDTL'
10 9 INDEX (UNIQUE SCAN) OF 'SYS_C00293260' (UNIQUE)
11 0 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_PUTAWAYHDR'
12 11 INDEX (UNIQUE SCAN) OF 'SYS_C00293263' (UNIQUE)
13 0 SORT (AGGREGATE)
14 13 NESTED LOOPS
15 14 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_PICKTICKETDTL'
16 15 INDEX (RANGE SCAN) OF 'F_L_P_CWI_IND1' (NON-UNIQUE)
17 14 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_PICKTICKETHDR'
18 17 INDEX (UNIQUE SCAN) OF 'SYS_C00293202' (UNIQUE)
19 0 SORT (AGGREGATE)
20 19 NESTED LOOPS
21 20 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_PICKTICKETDTL'
22 21 INDEX (RANGE SCAN) OF 'F_L_P_CWI_IND1' (NON-UNIQUE)
23 20 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_PICKTICKETHDR'
24 23 INDEX (UNIQUE SCAN) OF 'SYS_C00293202' (UNIQUE)
25 0 SORT (AGGREGATE)
26 25 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_INTERNALTRANSDTL
27 26 INDEX (RANGE SCAN) OF 'PK_INTERNALTRANSDTL' (UNIQUE)
28 0 SORT (AGGREGATE)
29 28 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_INTERNALTRANSDTL
30 29 INDEX (RANGE SCAN) OF 'PK_INTERNALTRANSDTL' (UNIQUE)
31 0 SORT (ORDER BY)
32 31 TABLE ACCESS (BY INDEX ROWID) OF 'FS_LG_PARTLOADS'
33 32 INDEX (RANGE SCAN) OF 'PK_PARTLOADS' (UNIQUE)
Please advice me regarding this...
Thanks in advance
Mahi -
Order by clause in PL/SQL cursors
I am trying to execute a procedure with some input parameters. I open a cursor
with a select statement. However, the order by clause in the query does not
recognize parameter sent through the procedure input parameters.
For example:
open <<cursor name>> for
select id from member order by <<dynamic parameter>>" does not work (Compiles fine but does not return the right result).
But if I try and give a static order by <<column name>> it works. Is the
order by clause in the PL/SQL a compile time phenomenon?
I have also tried it through dynamic sql. All the other parameters work except the order by <<parameter>> asc|desc
Also "asc" and "desc" does not work if given dynamically.
What alternatives do I have?
nullI don't think order by can be dynamic in a cursor, but it sure can be using dynamic sql. The only issue is that you must do a replace in the sql string with the dynamic variable. For example:
create or replace procedure test_dyn(p_col in varchar2, p_order in varchar2) as
q varchar2(500);
u_exec_cur number;
u_columnnumber NUMBER;
u_columndate DATE;
u_columnvarchar varchar2(50);
u_cur_count number;
u_ename varchar2(20);
u_sal number;
begin
q := 'select ename, sal from scott.emp order by p_col p_order';
-- got to do these two replaces
q:= replace(q,'p_col',p_col);
q:= replace(q,'p_order',p_order);
u_exec_cur := dbms_sql.open_cursor;
dbms_sql.parse(u_exec_cur,q,dbms_sql.v7);
dbms_sql.define_column(u_exec_cur, 1, u_columnvarchar, 20);
dbms_sql.define_column(u_exec_cur, 2, u_columnnumber);
u_cur_count := dbms_sql.execute(u_exec_cur);
loop
exit when (dbms_sql.fetch_rows(u_exec_cur) <= 0);
dbms_sql.column_value(u_exec_cur, 1, u_ename);
dbms_sql.column_value(u_exec_cur, 2, u_sal);
dbms_output.put_line(u_ename);
dbms_output.put_line(u_sail);
--htp.p(u_ename);
--htp.p(u_sal);
end loop;
end;
show errors;
Now when when I execute my procedure I can change the order by clause all I want, for example:
SQL> set serveroutput on;
SQL> exec gmika.test_dyn('sal','asc');
SMITH
800
ADAMS
1100
WARD
1250
MARTIN
1250
MILLER
1300
TURNER
1500
ALLEN
1600
JLO
2222
BLAKE
2850
JONES
2975
SCOTT
3000
FORD
3000
LOKITZ
4500
KING
5000
JAMES
5151
JAMES
5555
PL/SQL procedure successfully completed.
SQL>
null -
I need to dynamically build the order by clause of my query.
I tried this:
<named-query name="list">
<query>
<![CDATA[
SELECT p FROM Person p
ORDER BY :orderby
]]>
</query>
</named-query>
@SuppressWarnings("unchecked")
public List<Person> list(String sort) {
Query query = getEntityManager().createNamedQuery("list");
query.setParameter("orderby", sort);
return query.getResultList();
}But at runtime it throws an exception:
com.microsoft.sqlserver.jdbc.SQLServerException:
L'elemento SELECT identificato da ORDER BY 1 include una variabile nell'espressione che identifica la posizione di una colonna.
Le variabili sono consentite solo nell'ordinamento in base a un'espressione che fa riferimento a un nome di colonna.The translation of the italian message is something like:
The SELECT element identified by ORDER BY 1 includes a variable that identifies the position of a column.
The valid variables in the order by clause must refer to the name of a columnThe value of the parameter sort is_ the name of a column!
Any hint?My solution was to append the order clause to an "namedQuery" like this:
- declare the named query as usual, with annotation
- create a simple helper function like findNamedQuery to find the query string for a given class and queryName (using reflection)
- if you need to execute the query without sort order - use EntityManager.createNamedQuery (as usual)
- BUT: if you want to sort data: use EntityManager.createQuery with the string obtained from findNamedQuery and the sort clause
I guess the is a performance penalty, but.. .it works. -
Popup lov with order by clause
I created a form manually using the document from the url:
http://otn.oracle.com/products/database/htmldb/howtos/tabular_form.html#MANUAL
I used the following query from that document.
select htmldb_item.hidden(1,empno) empno,
ename,
htmldb_item.select_list_from_query(3,job,'select distinct job, job from emp') job,
htmldb_item.popupkey_from_query(4,mgr,'select ename, empno from emp',10) mgr,
wwv_flow_item.date_popup(6,null,hiredate) hiredate,
htmldb_item.text(7,sal,10) sal,
htmldb_item.text(8,comm,10) comm,
htmldb_item.select_list_from_query(9,deptno,'select dname, deptno from dept') deptno
from emp
This works fine.
But if I add an order by clause to the query the popup key for mgr column doesn't work.
select htmldb_item.hidden(1,empno) empno,
ename,
htmldb_item.select_list_from_query(3,job,'select distinct job, job from emp') job,
htmldb_item.popupkey_from_query(4,mgr,'select ename, empno from emp',10) mgr,
wwv_flow_item.date_popup(6,null,hiredate) hiredate,
htmldb_item.text(7,sal,10) sal,
htmldb_item.text(8,comm,10) comm,
htmldb_item.select_list_from_query(9,deptno,'select dname, deptno from dept') deptno
from emp
order by ename
Thanks
Chandra.Duplicate post, see:
popup lov in a report is not working if I have an order by caluse
Sergio -
Order By Clause - Slows performance
On 10.2 when adding an order by clause to a query affects performance that returns 6 rows of data.
Before:
select distinct col1
from table1
Cost: 3,000
Execution Time: less than a second
Chooses: Bitmap Index Fast Full Scan Index (BitMap)
After:
select distinct col1
from table1
order by col1
Cost: 14,000
Execution time: 90 seconds
Chooses: Full TableScan
Any ideas as to why the order by causes the slow down ?
Thanks,Venzi wrote:
Now you add the order by clause to it and Oracle has now to do a sort on it. It can't sort on the BITMAP index in that case so it has to go to the table. It is possible for Oracle to do the order by through the bitmap index - the reason it doesn't is probably down to arithmetic. (The situation is made a little messier by the fact that the table and index have been parallel enabled). Here's a plan from 10.2.0.3 showing the "order by" query running through the bitmap index:
| Id | Operation | Name | Rows | Bytes | Cost | TQ |IN-OUT| PQ Distrib |
| 0 | SELECT STATEMENT | | 6 | 18 | 356 | | | |
| 1 | PX COORDINATOR | | | | | | | |
| 2 | PX SEND QC (ORDER) | :TQ10001 | 6 | 18 | 356 | Q1,01 | P->S | QC (ORDER) |
| 3 | SORT GROUP BY | | 6 | 18 | 356 | Q1,01 | PCWP | |
| 4 | PX RECEIVE | | 2000K| 5859K| 63 | Q1,01 | PCWP | |
| 5 | PX SEND RANGE | :TQ10000 | 2000K| 5859K| 63 | Q1,00 | P->P | RANGE |
| 6 | PX BLOCK ITERATOR | | 2000K| 5859K| 63 | Q1,00 | PCWC | |
| 7 | BITMAP CONVERSION TO ROWIDS | | 2000K| 5859K| 63 | Q1,00 | PCWP | |
| 8 | BITMAP INDEX FAST FULL SCAN| T1_B1 | | | | Q1,00 | PCWP | |
------------------------------------------------------------------------------------------------------------Note how the optimizer can recognise that the "group by" operation will allow it to avoid an explicit "order by" operation, and uses the "(ORDER)" distribution to pass the data to the Query Coordinator to enforce correct ordering.
Running up a test case with a couple of million rows, it looks like the underlying problem the OP has is that the CBO bypasses a few of the execution options in this particular case when parallel execution is possible. (I had to hint this plan - the default plan was a serial full scan of the index that allowed the optimizer to bypass the "sort order" because of a "sort unique", but the cost was much higher than this parallel plan - see below).
| Id | Operation | Name | Rows | Bytes | Cost |
| 0 | SELECT STATEMENT | | 6 | 18 | 2269 |
| 1 | SORT UNIQUE NOSORT | | 6 | 18 | 2269 |
| 2 | BITMAP INDEX FULL SCAN| T1_B1 | 2000K| 5859K| 278 |
-----------------------------------------------------------------Regards
Jonathan Lewis
http://jonathanlewis.wordpress.com
http://www.jlcomp.demon.co.uk
To post code, statspack/AWR report, execution plans or trace files, start and end the section with the tag {noformat}{noformat} (lowercase, curly brackets, no spaces) so that the text appears in fixed format.
There is a +"Preview"+ tab at the top of the text entry panel. Use this to check what your message will look like before you post the message. If it looks a complete mess you're unlikely to get a response. (Click on the +"Plain text"+ tab if you want to edit the text to tidy it up.)
+"I believe in evidence. I believe in observation, measurement, and reasoning, confirmed by independent observers. I'll believe anything, no matter how wild and ridiculous, if there is evidence for it. The wilder and more ridiculous something is, however, the firmer and more solid the evidence will have to be."+
Isaac Asimov -
Problem in a inner query- order by clause
hi...
I have a update statement with a simple select clause present as inner query..
(select col1 from table1 where col2='abc' and rownum=1 order by col3 desc)
since it is a inner query, thats why i can not remove the brackets.
col3 may be 0 or 1(1 can occur only once...0 can be multiple times)
my target is to fetch the record if the col3 is 1
if it is not 1, then it will fetch the first record with col3=0...thats why i have put order by col3.
moreover i want only one record, thats why i have put rownum=1.
but it is failing with 'missing right parenthesis'.
please help..Hi,
Remember that the ORDER BY clause is applied last, after the WHERE clause is completed, so when you way
WHERE ROWNUM = 1
ORDER BY col3 DESCin the same sub-query, you're picking one row (arbitrarily), and then "sorting" that one row.
Here's one way to get the results you want:
SELECT col1
FROM (
SELECT col1
, ROW_NUMBER () OVER (ORDER BY col3 DESC)
AS r_num
FROM table1
WHERE col2 = 'abc'
AND col3 IN (0, 1)
WHERE r_num = 1
)Depending on how this is used in your complete query, there may be better ways to get the same results. -
Problem in sql query because of order by clause
Hi All,
I am facing a one problem in my one sql query.I am using Oracle 10gR2.
Query is given below:
SELECT t1.ename
FROM T1, T2
WHERE T1.EMPNO = 1234
AND T1.ACCOUNTNO = T2.ACCOUNTNO
AND T1.SEQ = T2.SEQ
ORDER BY T2.SEQThe Plan of the query is :
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 2 | 218 | 11716 (1)| 00:00:41 |
|* 1 | TABLE ACCESS BY INDEX ROWID | T1 | 1 | 89 | 1 (0)| 00:00:01 |
| 2 | NESTED LOOPS | | 2 | 218 | 11716 (1)| 00:00:41 |
|* 3 | TABLE ACCESS BY INDEX ROWID| T2 | 2 | 40 | 11715 (1)| 00:00:41 |
| 4 | INDEX FULL SCAN | PK_T2_SEQ | 58752 | | 122 (5)| 00:00:01 |
|* 5 | INDEX RANGE SCAN | FK_ACCOUNTNO | 3 | | 0 (0)| 00:00:01 |
----------------------------------------------------------------------------------------------------Now i want to reduce the time of this query.
If i am removing Order by clause from query than performance of the query is totally perfect but with order by clause its taking a time.
I have already set SORT_AREA_SIZE but still nothing is improving.
Welcome and thanks for your suggestions.
Thanks,
Edited by: BluShadow on 23-Jun-2011 07:55
added {noformat}{noformat} tags and formatted explain plan to make it readable. Please see {message:id=9360002} for details on how to post code and dataHi,
There are a couple of things I do not understand.
1. Why don't you put {noformat}{noformat} around your code, it makes it so much easier to read, especially your explain plan
2. You claim that the ORDER BY is problematic compared to no order by. Then why do you choose to post only one plan?
3. It is hard to understand how your tables relate, and which indexes you have and which you don't.
- PK_T2_SEQ, does this mean that SEQ alone is primary key of T2?
- If SEQ is primary key of T2, why do you join on accountno, seq and not just seq?
- If SEQ is primary key of T2 one of the tables is denormalized.
4. FK_ACCOUNTNO, is this an index on accountno, alone?
- Or is this AccountNo, Seq?
5. Is there no index on T1.EMPNO?
Above could of course just be a case of my not understanding the names of your indexes.
So, here are my guesses:
Above plan is for the ORDER BY query. That means the optimizer, has chosen to full scan PK_T2_SEQ, since data is then read according to the ORDER BY.
(This could be a bad choice)I
You could try and order by t1.seq, instead. Result should be the same.
Regards
Peter
Maybe you are looking for
-
How to make the text fields as mandatory (in 'notes and attachment' tab)?
Hi, We have defined some Fixed Values for texts under IMG>SRM>SRM Server>Cross Application Basic Settings>Text Schema>Define Fixed Values for Texts, for a certain transaction type of RFx responses for a text schema. Because of this, the bidder can ch
-
Problem installing Flash v10.1
Hi everyone, I am new to this forum and am doing this because I have been trying to install flashplayer10_1r102_64_ub_mac.dmg to my (now quite old) 1.42 power pc G4. I have read a few old posts from these pages and followed instructions that have hel
-
Restricting access to Queries via Search
Does anyone have any ideas on restricting access to queries from the Bex search. We have folks that are using the search functionality of Bex and are finding queries that we have not been published to a reporting role. We instruct our query writers t
-
My new iPad3 with wifi- is taking a really long time to download,much longer than my iPhone. Does anyone know what I can do? Or is that just normal.
-
Need HELP with hooking up my X-Fi & my Minidisc. No sou
<FONT face=Verdana size=3>Hello. I am getting seriously frustrated with this. The reason I just shelled out $200+ for my new X-Fi Platinum Soundcard is so I could transfer what I have on these minidisc's to my PC. I've hooked it up exactly as the dia