Order By clause in Oracle
Hello,
Sorry I am posting it for the second time
In Oracle , the order by clause does not return the expected query result, if any of the field value in the order by clause has an empty string.
Oracle treats the empty string as null value and ORDER BY gives a result with the empty string field values listed at last.
For example :
test is a sample table containing "name" field.
Query: "select name from test order by name"
In SQL Server/Access
Result (1)
NAME
(blank)
(blank)
User1
User2
User3
In Oracle
Result (2)
NAME
User1
User2
User3
(blank)
(blank)
I know some of the Work arounds for this as listed below :
1) To use NVL in Order By Clause.
i.e., the modified query
"select name from test order by nvl(name,0)"
gives the result same as Result (1).
2) To have single blank space in the field value if it is empty.
I dont want to use either of these two options b'se it would lead to a mass change in my existing code.
Is there any way i can do a
collation order settings in the Oracle databases to get the results as in MS SQL/Access.
Or Is there any other way that i can set the
option once for this and need not worry abt it afterwards?
Can Any help me out in Solving this?
Thanks
Devi
null
For fun and out of curiosity, I tried :
SQL> select /*+ leading(t) use_nl(e t) */
2 e.deptno
3 , e.empno
4 from scott.emp e
5 , table(sys.odcinumberlist(30,10,20)) t
6 where e.deptno = t.column_value
7 ;
DEPTNO EMPNO
30 7499
30 7521
30 7654
30 7698
30 7844
30 7900
10 7782
10 7839
10 7934
20 7369
20 7566
20 7902
12 rows selected
It "seems" to work but of course we can't expect a consistent behaviour, or can we? ;)
Similar Messages
-
Is parameter in ORDER BY clause possible?
I'm using a function to return a ref cursor and currently pass a parameter without any problems. I would like to change the sort on the fly by passing a parameter to the order by clause, but Oracle ignores it.
CREATE OR REPLACE PACKAGE pkg_agent_appt_status AS
TYPE rcur IS REF CURSOR;
FUNCTION f_agent_appt_status (ssn IN VARCHAR2, sort_str IN VARCHAR2) RETURN rcur;
END pkg_agent_appt_status;
CREATE OR REPLACE PACKAGE BODY pkg_agent_appt_status AS
FUNCTION f_agent_appt_status (ssn IN VARCHAR2, sort_str IN VARCHAR2)
RETURN rcur
IS
retval rcur;
BEGIN
OPEN retval FOR
SELECT agncy.CORPORATE_NAME "Agency Name",
agnt_state.APPT_STATE "State",
agnt.AGENT_STATUS "Appt Status",
TO_CHAR(agnt_state.APPT_STATE_EFF_DT,'mm/dd/yyyy') "Effective Date",
agnt.AGENT_NUMBER "Agent ID",
agnt.AGENT_STATUS "Agent Status",
STATE.STATE_NAME
FROM AGNT_APPT_STAT_PRDCR_WRK agnt,
AGNT_APPT_STAT_WRK agncy,
AGNT_APPT_STATE_STAT_PRDCR_WRK agnt_state,
STATE
WHERE agnt.AGENT_TAX_ID = ssn
AND agnt.COMPANY_CODE = agncy.COMPANY_CODE
AND agnt.PARENT_AGENT_AGENCY_ID = agncy.AGENT_NUMBER
AND agnt.COMPANY_CODE = agnt_state.COMPANY_CODE
AND agnt.AGENT_AGENCY_ID = agnt_state.AGENT_AGENCY_ID
AND agnt.AGENT_NUMBER = agnt_state.AGENT_NUMBER
AND agnt_state.APPT_STATE = STATE.STATE_CODE
ORDER BY
sort_str;
RETURN retval;
END f_agent_appt_status;
END pkg_agent_appt_status;If you want to do this, you'd have to use dynamic SQL (execute immediate or DBMS_SQL). For the easier 'execute immediate' approach, you'd do something like
create or replace someProc( someArg varchar2 )
as
strSQL varchar2(4000)
begin
strSQL := <<string containing your SQL statement up to the order by clause>>
strSQL := strSQL || 'ORDER BY ' || someArg
execute immediate strSQL;
endJustin -
Is passing parameter to ORDER BY clause possible?
I'm using a function to return a ref cursor and currently pass a parameter without any problems. I would like to change the sort on the fly by passing a parameter to the order by clause, but Oracle ignores it.
CREATE OR REPLACE PACKAGE pkg_agent_appt_status AS
TYPE rcur IS REF CURSOR;
FUNCTION f_agent_appt_status (ssn IN VARCHAR2, sort_str IN VARCHAR2) RETURN rcur;
END pkg_agent_appt_status;
CREATE OR REPLACE PACKAGE BODY pkg_agent_appt_status AS
FUNCTION f_agent_appt_status (ssn IN VARCHAR2, sort_str IN VARCHAR2)
RETURN rcur
IS
retval rcur;
BEGIN
OPEN retval FOR
SELECT agncy.CORPORATE_NAME "Agency Name",
agnt_state.APPT_STATE "State",
agnt.AGENT_STATUS "Appt Status",
TO_CHAR(agnt_state.APPT_STATE_EFF_DT,'mm/dd/yyyy') "Effective Date",
agnt.AGENT_NUMBER "Agent ID",
agnt.AGENT_STATUS "Agent Status",
STATE.STATE_NAME
FROM AGNT_APPT_STAT_PRDCR_WRK agnt,
AGNT_APPT_STAT_WRK agncy,
AGNT_APPT_STATE_STAT_PRDCR_WRK agnt_state,
STATE
WHERE agnt.AGENT_TAX_ID = ssn
AND agnt.COMPANY_CODE = agncy.COMPANY_CODE
AND agnt.PARENT_AGENT_AGENCY_ID = agncy.AGENT_NUMBER
AND agnt.COMPANY_CODE = agnt_state.COMPANY_CODE
AND agnt.AGENT_AGENCY_ID = agnt_state.AGENT_AGENCY_ID
AND agnt.AGENT_NUMBER = agnt_state.AGENT_NUMBER
AND agnt_state.APPT_STATE = STATE.STATE_CODE
ORDER BY
sort_str;
RETURN retval;
END f_agent_appt_status;
END pkg_agent_appt_status;This is quite easy, as you are already using a REF CURSOR. Instead of
OPEN retval FOR
SELECT ...
ORDER BY sort_str;we can code this:
OPEN retval FOR
'SELECT ...
ORDER BY '|| sort_str;Watch out for the single quotes in your query e.g. the date format mask: you need to wrap these in an additional set of single quotes i.e. 'mm/dd/yyyy' becomes ''mm/dd/yyyy''.
Cheers, APC -
Order by clause Dynamic in Oracle function
How can i get order by Clause Dynamic in Oracle function
My function Returns sql query with SYS_REFCURSOR . and i will pass the order by column as input parameter
create or replace
FUNCTION TEST_SSK
p_srot number
RETURN SYS_REFCURSOR
AS
C_testssk SYS_REFCURSOR;
BEGIN
OPEN C_TESTSSK FOR
SELECT LOAN_CODE,LOAN_DATE,DUE_DATE,LOAN_AMT FROM LOAN_MASTER
order by P_SROT;
return C_testssk;
end;Edited by: user10736825 on Dec 22, 2010 11:34 AMyou can go for a dynamic query ;)
create or replace
FUNCTION TEST_SSK
p_srot number
RETURN SYS_REFCURSOR
AS
C_testssk SYS_REFCURSOR;
l_str VARCHAR2(4000);
l_order VARCHAR2(100);
BEGIN
l_str := 'SELECT LOAN_CODE,LOAN_DATE,DUE_DATE,LOAN_AMT FROM LOAN_MASTER ';
IF p_sort = 'LC'
THEN
l_order := ' ORDER BY LOAN_CODE ';
ELSIF p_sort = 'LD'
THEN
l_order := ' ORDER BY LOAN_DATE ';
END IF;
l_str := l_str || l_order ;
OPEN C_TESTSSK FOR l_str;
return C_testssk;
end; -
Sorting technique used by oracle for "order by" clause.
Hi All,
it could be very help to me if you provide some information about sorting technique used by oracle engine for order by clause.
Issue i am facing :
Table : xx
Line Date
1 05-06-2013 00:00:00
2 05-06-2013 00:00:00
when we query above table using order by date, it is returning line 2 prior to line 1. we would like to know why it is returning line 2 first?
Regards,
Ram>
it could be very help to me if you provide some information about sorting technique used by oracle engine for order by clause.
>
Well ok - but be warned that many people wind up being sorry they ask that question. Hopefully Hemant's answer is what you really wanted.
See 'Linguistic Sorting and String Searching' in the Oracle® Database Globalization Support Guide
http://docs.oracle.com/cd/B28359_01/server.111/b28298/ch5lingsort.htm
Sorting will be controlled by the settings of NLS_LANGUAGE, NLS_SORT and NLS_COMP.
Here is the doc page for NLS_SORT
http://docs.oracle.com/cd/B28359_01/server.111/b28298/ch3globenv.htm#i1008393
>
NLS_SORT specifies the type of sort for character data. It overrides the default value that is derived from NLS_LANGUAGE.
NLS_SORT contains either of the following values:
NLS_SORT = BINARY | sort_name
BINARY specifies a binary sort. sort_name specifies a linguistic sort sequence.
>
And the one for NLS_COMP
http://docs.oracle.com/cd/B28359_01/server.111/b28298/ch3globenv.htm#i1008458
>
The value of NLS_COMP affects the comparison behavior of SQL operations.
You can use NLS_COMP to avoid the cumbersome process of using the NLSSORT function in SQL statements when you want to perform a linguistic comparison instead of a binary comparison. When NLS_COMP is set to LINGUISTIC, SQL operations perform a linguistic comparison based on the value of NLS_SORT. A setting of ANSI is for backward compatibility; in general, you should set NLS_COMP to LINGUISTIC when you want to perform a linguistic comparison. -
Hi,
I have a doubt regarding Order By Clause in Views.
As per my knowledge, we can't put an order by clause in the subquery that defines view. But when i created a view in Oracle 9i with the order by clause, view got created.
Please see the my view code below :
create or replace view testview
as select * from employees
order by 1,2;
Could anyone please confirm that we can have order by clause in Views in oracle 9i?
Thanks,
TandraAccording to the SQL Reference doc, there is no such restriction for a non-updatable view:
The view subquery cannot select the CURRVAL or NEXTVAL pseudocolumns.
If the view subquery selects the ROWID, ROWNUM, or LEVEL pseudocolumns, those columns must have aliases in the view subquery.
If the view subquery uses an asterisk (*) to select all columns of a table, and you later add new columns to the table, the view will not contain those columns until you re-create the view by issuing a CREATE OR REPLACE VIEW statement.
For object views, the number of elements in the view subquery select list must be the same as the number of top-level attributes for the object type. The datatype of each of the selecting elements must be the same as the corresponding top-level attribute.
You cannot specify the SAMPLE clause.
This restriction exists only for updatable views:
If you want the view to be inherently updatable, it must not contain any of the following constructs:
A set operator
A DISTINCT operator
An aggregate or analytic function
A GROUP BY, ORDER BY, CONNECT BY, or START WITH clause
A collection expression in a SELECT list
A subquery in a SELECT list
Joins (with some exceptions as described in the paragraphs that follow). -
Hi All,
I want to order my SELECT using "dynamic ORDER BY". I have a CURSOR (in my PL/SQL procedure) contains a select with ORDER BY clause. I have implemented two combobox in my form (the first contains the column name, the second contains ASC and DESC).I tried with the next:
1) Dynamic ORDER BY in CURSOR with combobox results. IT DOESN'T WORK.
2) Using a block property named "ORDER BY CLAUSE". Here I put, for example, :myBlock.comboColumnOrder. IT DOESN'T WORK.
3) Using a function: set_block_property(myBlock,order_by,:myBlock.comboColumnOrder) or set_block_property(myBlock,default_where,:myBlock.comboColumnOrder). IT DOESN'T WORK.
4) Using dynamic CURSOR: ORACLE FORMS give me an error that said: "...it can't to the CLIENT-SIDE".
I have thought my last solution, but it maybe cumbersome. I do a TEMPORARY TABLE, and my CURSOR insert in this TABLE, and then I'll fetch to my BLOCK.
Thanks a lot.
PS: My ORACLE Version is 10g.PROCEDURE CHEQUEAR_V0 IS
V_ORDEN VARCHAR2(50) := '' || :BLOCK_CHECK.ORDER_BY_NAME || ' ' || :BLOCK_CHECK.ORDER_BY_ASC_DES ;
CURSOR FILA_RESULTADO_TABLA IS
SELECT Last_name,First_name,App_user, App_role, UserDB
FROM adm_users
WHERE
((Last_name IS NULL OR Last_name LIKE '%'||:BLOCK_CHECK.Last_name||'%') AND
(First_name IS NULL OR First_name LIKE '%'||:BLOCK_CHECK.First_name||'%') AND
(App_user IS NULL OR App_user LIKE '%'||:BLOCK_CHECK.App_user||'%') AND
(App_role IS NULL OR App_role LIKE '%'||:BLOCK_CHECK.App_role||'%') AND
(UserDB IS NULL OR UserDB LIKE '%'||:BLOCK_CHECK.User_DB||'%'))
ORDER BY V_ORDEN;
V_Last_name VARCHAR2(50);
V_First_name VARCHAR2(50);
V_App_user VARCHAR2(50);
V_App_role VARCHAR2(50) ;
V_User_DB VARCHAR2(50);
CONT NUMBER ;
BEGIN
CONT := 1 ;
GO_BLOCK('BLOCK_APPS_GRANTS');
CLEAR_BLOCK;
SYNCHRONIZE;
OPEN FILA_RESULTADO_TABLA;
LOOP
FETCH FILA_RESULTADO_TABLA INTO V_Last_name,V_First_name,V_App_user,V_App_role,V_User_DB ;
EXIT WHEN FILA_RESULTADO_TABLA%NOTFOUND;
:BLOCK_APPS_GRANTS.Last_name := V_Last_name ;
:BLOCK_APPS_GRANTS.First_name := V_First_name ;
:BLOCK_APPS_GRANTS.App_user := V_App_user ;
:BLOCK_APPS_GRANTS.App_role := V_App_role ;
:BLOCK_APPS_GRANTS.User_DB := V_User_DB ;
NEXT_RECORD;
CONT := CONT+1;
END LOOP;
IF FILA_RESULTADO_TABLA%ISOPEN THEN
CLOSE FILA_RESULTADO_TABLA;
END IF;
SET_BLOCK_PROPERTY('BLOCK_APPS_GRANTS', ORDER_BY, :BLOCK_CHECK.ORDER_BY_NAME || ' ' || :BLOCK_CHECK.ORDER_BY_ASC_DES);
GO_BLOCK('BLOCK_APPS_GRANTS');
EXECUTE_QUERY;
synchronize;
exception when others then
raise;
END;
Thanks a lot.
Edited by: user11285646 on 22-jul-2009 2:30 -
ORDER BY Clause in XMLAGG is throwing errors.
Hi,
I'm getting errors when generating the XML using the ORDER BY clause in the XMLAgg function. Although, running the SQL directly in SQL Plus doesn't have any problem.
Here is the PL/SQL sample.
DECLARE
vX_XML SYS.XMLTYPE;
vCL_XML CLOB;
BEGIN
SELECT XMLElement("GROUP",
XMLAttributes(Group_Id AS "ID", Group_Name AS "NAME", Group_Description AS "DESC"),
XMLAgg(XMLElement("FIELD",
XMLAttributes(Field_Id AS "ID", Field_Description AS "DESC",
Table_Name AS "TAB_NM", Rule_Name AS "RULE_NM",
Field_Hierarchy_Depth AS "DOL_VAR_CALC")) ORDER BY Field_Description))
INTO vX_XML
FROM (SELECT g.Group_Id, g.Group_Name, g.Group_Description, f.Field_Id, f.Field_Description,
DECODE(f.Table_Name, 'ESTIMATES', 'E', 'LINE_ITEMS', 'L', NULL) Table_Name,
rt.Rule_Name,
CASE NVL(f.Field_Hierarchy_Depth, 0) WHEN 0 THEN 'N' ELSE 'Y' END Field_Hierarchy_Depth
FROM GROUPS g,
Rules r,
Rule_Types rt,
Fields f
WHERE g.Group_Id = 3087
AND r.Group_Id_Fk = g.Group_Id
AND rt.Rule_Type_Id = r.Rule_Type_Id_Fk
AND f.Field_Id = r.Field_Id_Fk) tab
GROUP BY Group_Id, Group_Name, Group_Description;
vCL_XML := vX_XML.GetCLOBVal();
END;
And, here are the errors.
ERROR at line 8:
ORA-06550: line 8, column 23:
PLS-00306: wrong number or types of arguments in call to 'XMLAGG'
ORA-06550: line 8, column 23:
PL/SQL: ORA-00904: "XMLAGG": invalid identifier
ORA-06550: line 6, column 5:
PL/SQL: SQL Statement ignored
Thanks in Advance.
BTW, we are using Oracle 9.2.0.4.This is bug 2785463 with no ETA for a fix
regards
Coby D. Adams Jr. -
Order By Clause with Empty Field values !
Hello,
In Oracle , the order by clause does not return the expected query result, if any of the field value in the order by clause has an empty string.
Oracle treats the empty string as null value and ORDER BY gives a result with the empty string field values listed at last.
For example :
test is a sample table containing "name" field.
Query: "select name from test order by name"
In SQL Server/Access
Result (1)
NAME
(blank)
(blank)
User1
User2
User3
In Oracle
Result (2)
NAME
User1
User2
User3
(blank)
(blank)
I know some of the Work arounds for this as listed below :
1) To use NVL in Order By Clause.
i.e., the modified query
"select name from test order by nvl(name,0)"
gives the result same as Result (1).
2) To have single blank space in the field value if it is empty.
I dont want to use either of these two options b'se it would lead to a mass change in my existing code.
Is there any way i can do a
collation order settings in the Oracle databases to get the results as in MS SQL/Access.
Can Any help me out in Solving this?
Thanks
Devi Shankar
nullBharath,
I am moving this question to the SQL forum.
Regards,
Geoff -
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 -
Slow SQL output when table alias is NOT used in order by clause
Hi guys,
My query is based on Oracle 9208
I have a table TAB1 with 68000 records with transaction_id as the primary key in this table (unique index).
I have another TAB2 with the same number of records again with transaction_id in this table (foreign key to above).
I have the below query that gets executed via an application:-
SELECT TO_CHAR(V1.TRANSACTION_ID), V1.POLICY_ID, V1.REQUEST_TYPE
FROM <VIEW> V1 WHERE V1.CERT_SERIAL_NUM=56192 AND
(V1.AUTH_GROUP_ID=0 OR V1.AUTH_GROUP_ID=1) AND ROWNUM <= 3 ORDER
BY TRANSACTION_ID ASC
The above view V1 is created as below:-
CREATE OR REPLACE FORCE VIEW "V1"
("TRANSACTION_ID",
"PARENT_TRANSACTION_ID",
"CA_DN_ID",
"AUTH_GROUP_ID",
"POLICY_ID",
"REQUEST_TYPE",
"REQUEST_STATUS",
"EE_DN_HASH",
"EE_DN",
"EE_EMAIL_HASH",
"EE_EMAIL",
"KEY_USAGE",
"SMART_CARD_SERIAL",
"CERT_TYPE",
"CERT_SERIAL_NUM",
"CERT_INDEX",
"RENEWAL_FLAG",
"ARCHIVE_FLAG",
"TIME_RECEIVED",
"DOWNLOADED",
"REQUEST_DATA",
"ACTION",
"STEP_NUM")
AS
SELECT
T1.transaction_id,
T1.parent_transaction_id,
T1.ca_dn_id,
V2.auth_group_id,
V2.policy_id,
T1.request_type,
T1.request_status,
T2.ee_dn_hash,
T2.ee_dn,
T2.ee_email_hash,
T2.ee_email,
T2.key_usage,
T2.smart_card_serial,
T2.cert_type,
T2.cert_serial_num,
T2.cert_index,
T2.renewal_flag,
T2.archive_flag,
T1.time_received,
T1.downloaded,
T1.request_data,
V2.action,
V2.step_num
FROM TAB1
<ANOTHER VIEW> V2,
TAB2 T1,
TAB2 T2
WHERE
T1.transaction_id = T2.transaction_id
AND
V2.policy_id = T1.policy_id
order by transaction_id;
The query at the top runs within milliseconds if the VIEW is created as :-
order by t2.transaction_id
But without the alias "t2" in the order by, the query takes about 1 1/2 minutes
Can you tell me why? I thought if you ordering by primary key (lesser number of values compared to foreign key values), the query should be faster..no?
Thanks in advanceThanks for keeping up with this issue Hemant.
Here are the plans for each case.
I would be very interested in how you'd recognize which plan is the best and what are the derivatives.
I don't much (or rather anything!) what is 'card' values, 'cost' values etc which I believe are used to decide the best plan of the lot.
Thanks again
Note TAB1 and TAB2 are from view definition posted initially
1) Execution Plan for VIEW1 <<-- With ORDER BY" clause but no table ailas (order by transaction_id)
SQL> EXPLAIN PLAN FOR SELECT TO_CHAR(QT.TRANSACTION_ID), QT.POLICY_ID, QT.REQUEST_TYPE
2 FROM <VIEW1> QT WHERE QT.CERT_SERIAL_NUM=24293 AND
3 (QT.AUTH_GROUP_ID=0 OR QT.AUTH_GROUP_ID=1) AND ROWNUM <= 3 ORDER
4 BY TRANSACTION_ID ASC
5 /
Explained.
Elapsed: 00:00:01.00
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
| Id | Operation | Name | Rows | Bytes | Cost |
| 0 | SELECT STATEMENT | | 3 | 195 | 17 |
|* 1 | COUNT STOPKEY | | | | |
| 2 | VIEW | VIEW1 | 17 | 1105 | 17 |
|* 3 | SORT ORDER BY STOPKEY | | 17 | 38573 | 17 |
| 4 | NESTED LOOPS | | 17 | 38573 | 10 |
| 5 | MERGE JOIN CARTESIAN | | 1 | 167 | 9 |
| 6 | VIEW | VIEW2 | 1 | 52 | 8 |
| 7 | SORT UNIQUE | | 1 | 156 | 8 |
| 8 | NESTED LOOPS | | 1 | 156 | 6 |
| 9 | NESTED LOOPS | | 1 | 143 | 6 |
| 10 | NESTED LOOPS OUTER | | 1 | 117 | 5 |
|* 11 | HASH JOIN | | 1 | 104 | 5 |
| 12 | NESTED LOOPS | | 1 | 52 | 2 |
|* 13 | TABLE ACCESS FULL | TAB3 | 1 | 39 | 2 |
|* 14 | INDEX UNIQUE SCAN | (PK_TAB4) | 1 | 13 | |
| 15 | TABLE ACCESS FULL | TAB5 | 82 | 4264 | 2 |
| 16 | VIEW PUSHED PREDICATE | View3 | 1 | 13 | |
| 17 | NESTED LOOPS | | 1 | 52 | 2 |
| 18 | NESTED LOOPS | | 1 | 39 | 2 |
|* 19 | INDEX UNIQUE SCAN | (PK_TAB6) | 1 | 13 | 1 |
|* 20 | INDEX RANGE SCAN | (PK_TAB7) | 1 | 26 | 1 |
|* 21 | INDEX UNIQUE SCAN | (PK_TAB8) | 1 | 13 | |
| 22 | TABLE ACCESS BY INDEX ROWID| TAB9 | 3 | 78 | 1 |
|* 23 | INDEX UNIQUE SCAN | (PK_TAB9) | 1 | | |
|* 24 | INDEX UNIQUE SCAN | (PK_TAB10)| 1 | 13 | |
| 25 | BUFFER SORT | | 1 | 115 | 9 |
| 26 | TABLE ACCESS BY INDEX ROWID | TAB2 | 1 | 115 | 1 |
|* 27 | INDEX RANGE SCAN | (TAB2_IDX2)| 1 | | |
|* 28 | TABLE ACCESS BY INDEX ROWID | TAB1 | 12 | 25224 | 1 |
|* 29 | INDEX UNIQUE SCAN | (PK_TAB1) | 1 | | |
Predicate Information (identified by operation id):
1 - filter(ROWNUM<=3)
3 - filter(ROWNUM<=3)
11 - access("TAB5"."PATH_ID"="TAB4"."PATH_ID")
13 - filter("TAB3"."AUTH_GROUP_ID"<>(-1) AND ("TAB3"."AUTH_GROUP_ID"=0 OR "TAB3"."AUTH_GROUP_ID"=1))
14 - access("TAB3"."PATH_ID"="TAB4"."PATH_ID")
19 - access("TAB5"."DOMAIN_ID"="TAB6"."DOMAIN_ID")
20 - access("TAB6"."DOMAIN_ID"="TAB7"."DOMAIN_ID")
21 - access("TAB7"."RULE_ID"="TAB8"."RULE_ID")
23 - access("TAB9"."POLICY_ID"="TAB5"."POLICY_ID")
24 - access("TAB9"."ASSOCIATED_FORM_ID"="TAB10"."FORM_ID")
27 - access("TAB2"."CERT_SERIAL_NUM"=24293)
28 - filter("View2"."POLICY_ID"="TAB1"."POLICY_ID")
29 - access("TAB1"."TRANSACTION_ID"="TAB2"."TRANSACTION_ID")
Note: cpu costing is off
54 rows selected.
Elapsed: 00:00:01.81
Execution Plan
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 COLLECTION ITERATOR (PICKLER FETCH) OF 'DISPLAY'
Statistics
39 recursive calls
0 db block gets
629 consistent gets
0 physical reads
104 redo size
5169 bytes sent via SQL*Net to client
405 bytes received via SQL*Net from client
5 SQL*Net roundtrips to/from client
31 sorts (memory)
0 sorts (disk)
54 rows processed
2) Execution Plan for VIEW1 <<-- With ORDER BY" clause and table alias (order by TAB2.transaction_id)
SQL> explain plan for SELECT TO_CHAR(QT.TRANSACTION_ID), QT.POLICY_ID, QT.REQUEST_TYPE
2 FROM <VIEW1> QT WHERE QT.CERT_SERIAL_NUM=30003 AND
3 (QT.AUTH_GROUP_ID=0 OR QT.AUTH_GROUP_ID=1) AND ROWNUM <= 3 ORDER
4 BY TRANSACTION_ID ASC
5 /
Explained.
Elapsed: 00:00:10.20
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
| Id | Operation | Name | Rows | Bytes | Cost |
| 0 | SELECT STATEMENT | | 3 | 195 | 14 |
| 1 | SORT ORDER BY | | 3 | 195 | 14 |
|* 2 | COUNT STOPKEY | | | | |
| 3 | VIEW | VIEW1 | 17 | 1105 | 13 |
| 4 | NESTED LOOPS | | 17 | 38573 | 13 |
| 5 | MERGE JOIN CARTESIAN | | 1 | 167 | 12 |
|* 6 | TABLE ACCESS BY INDEX ROWID | TAB2 | 1 | 115 | 4 |
| 7 | INDEX FULL SCAN | (TAB2_IDX) | 94 | | 1 |
| 8 | BUFFER SORT | | 1 | 52 | 8 |
| 9 | VIEW | VIEW2 | 1 | 52 | 8 |
| 10 | SORT UNIQUE | | 1 | 156 | 8 |
| 11 | NESTED LOOPS | | 1 | 156 | 6 |
| 12 | NESTED LOOPS | | 1 | 143 | 6 |
| 13 | NESTED LOOPS OUTER | | 1 | 117 | 5 |
|* 14 | HASH JOIN | | 1 | 104 | 5 |
| 15 | NESTED LOOPS | | 1 | 52 | 2 |
|* 16 | TABLE ACCESS FULL | TAB3 | 1 | 39 | 2 |
|* 17 | INDEX UNIQUE SCAN | (PK_TAB4) | 1 | 13 | |
| 18 | TABLE ACCESS FULL | TAB5 | 82 | 4264 | 2 |
| 19 | VIEW PUSHED PREDICATE | View3 | 1 | 13 | |
| 20 | NESTED LOOPS | | 1 | 52 | 2 |
| 21 | NESTED LOOPS | | 1 | 39 | 2 |
|* 22 | INDEX UNIQUE SCAN | (PK_TAB6) | 1 | 13 | 1 |
|* 23 | INDEX RANGE SCAN | (PK_TAB7) | 1 | 26 | 1 |
|* 24 | INDEX UNIQUE SCAN | (PK_TAB8) | 1 | 13 | |
| 25 | TABLE ACCESS BY INDEX ROWID| TAB9 | 3 | 78 | 1 |
|* 26 | INDEX UNIQUE SCAN | (PK_TAB9) | 1 | | |
|* 27 | INDEX UNIQUE SCAN | (PK_TAB10) | 1 | 13 | |
|* 28 | TABLE ACCESS BY INDEX ROWID | TAB1 | 12 | 25224 | 1 |
|* 29 | INDEX UNIQUE SCAN | (PK_TAB1) | 1 | | |
Predicate Information (identified by operation id):
2 - filter(ROWNUM<=3)
6 - filter("TAB2"."CERT_SERIAL_NUM"=30003)
14 - access("TAB5"."PATH_ID"="TAB4"."PATH_ID")
16 - filter("TAB3"."AUTH_GROUP_ID"<>(-1) AND ("TAB3"."AUTH_GROUP_ID"=0 OR "TAB3"."AUTH_GROUP_ID"=1))
17 - access("TAB3"."PATH_ID"="TAB4"."PATH_ID")
22 - access("TAB5"."DOMAIN_ID"="TAB6"."DOMAIN_ID")
23 - access("TAB6"."DOMAIN_ID"="TAB7"."DOMAIN_ID")
24 - access("TAB7"."RULE_ID"="TAB8"."RULE_ID")
26 - access("TAB9"."POLICY_ID"="TAB5"."POLICY_ID")
27 - access("TAB9"."ASSOCIATED_FORM_ID"="TAB10"."FORM_ID")
28 - filter("VIEW2"."POLICY_ID"="TAB1"."POLICY_ID")
29 - access("TAB1"."TRANSACTION_ID"="TAB2"."TRANSACTION_ID")
Note: cpu costing is off
53 rows selected.
Elapsed: 00:00:08.29
Execution Plan
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 COLLECTION ITERATOR (PICKLER FETCH) OF 'DISPLAY'
Statistics
1079 recursive calls
0 db block gets
597 consistent gets
21 physical reads
0 redo size
5177 bytes sent via SQL*Net to client
405 bytes received via SQL*Net from client
5 SQL*Net roundtrips to/from client
63 sorts (memory)
0 sorts (disk)
53 rows processed
3) Execution Plan for VIEW1 <<-- Without any "ORDER BY" clause
SQL> explain plan for SELECT TO_CHAR(QT.TRANSACTION_ID), QT.POLICY_ID, QT.REQUEST_TYPE
2 FROM <VIEW1> QT WHERE QT.CERT_SERIAL_NUM=30003 AND
3 (QT.AUTH_GROUP_ID=0 OR QT.AUTH_GROUP_ID=1) AND ROWNUM <= 3 ORDER
4 BY TRANSACTION_ID ASC
5 /
Explained.
Elapsed: 00:00:10.20
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
| Id | Operation | Name | Rows | Bytes | Cost |
| 0 | SELECT STATEMENT | | 3 | 213 | 11 |
| 1 | SORT ORDER BY | | 3 | 213 | 11 |
|* 2 | COUNT STOPKEY | | | | |
| 3 | NESTED LOOPS | | 17 | 1207 | 10 |
| 4 | MERGE JOIN CARTESIAN | | 1 | 32 | 9 |
| 5 | VIEW | VIEW2 | 1 | 26 | 8 |
| 6 | SORT UNIQUE | | 1 | 156 | 8 |
| 7 | NESTED LOOPS | | 1 | 156 | 6 |
| 8 | NESTED LOOPS | | 1 | 143 | 6 |
| 9 | NESTED LOOPS OUTER | | 1 | 117 | 5 |
|* 10 | HASH JOIN | | 1 | 104 | 5 |
| 11 | NESTED LOOPS | | 1 | 52 | 2 |
|* 12 | TABLE ACCESS FULL | TAB3 | 1 | 39 | 2 |
|* 13 | INDEX UNIQUE SCAN | PK_TAB4 | 1 | 13 | |
| 14 | TABLE ACCESS FULL | TAB5 | 82 | 4264 | 2 |
| 15 | VIEW PUSHED PREDICATE | VIEW3 | 1 | 13 | |
| 16 | NESTED LOOPS | | 1 | 52 | 2 |
| 17 | NESTED LOOPS | | 1 | 39 | 2 |
|* 18 | INDEX UNIQUE SCAN | PK_TAB6 | 1 | 13 | 1 |
|* 19 | INDEX RANGE SCAN | PK_TAB7 | 1 | 26 | 1 |
|* 20 | INDEX UNIQUE SCAN | PK_TAB8 | 1 | 13 | |
| 21 | TABLE ACCESS BY INDEX ROWID| TAB9 | 3 | 78 | 1 |
|* 22 | INDEX UNIQUE SCAN | PK_TAB9 | 1 | | |
|* 23 | INDEX UNIQUE SCAN | PK_TAB10 | 1 | 13 | |
| 24 | BUFFER SORT | | 1 | 6 | 9 |
| 25 | TABLE ACCESS BY INDEX ROWID | TAB2 | 1 | 6 | 1 |
|* 26 | INDEX RANGE SCAN | TAB2_IDX2 | 1 | | |
|* 27 | TABLE ACCESS BY INDEX ROWID | TAB1 | 12 | 468 | 1 |
|* 28 | INDEX UNIQUE SCAN | PK_TAB1 | 1 | | |
Predicate Information (identified by operation id):
2 - filter(ROWNUM<=3)
10 - access("TAB5"."PATH_ID"="TAB4"."PATH_ID")
12 - filter("TAB3"."AUTH_GROUP_ID"<>(-1) AND ("TAB3"."AUTH_GROUP_ID"=0 OR "TAB3"."AUTH_GROUP_ID"=1))
13 - access("TAB3"."PATH_ID"="TAB4"."PATH_ID")
18 - access("TAB5"."DOMAIN_ID"="TAB6"."DOMAIN_ID")
19 - access("TAB6"."DOMAIN_ID"="TAB7"."DOMAIN_ID")
20 - access("TAB7"."RULE_ID"="TAB8"."RULE_ID")
22 - access("TAB9"."POLICY_ID"="TAB5"."POLICY_ID")
23 - access("TAB9"."ASSOCIATED_FORM_ID"="TAB10"."FORM_ID")
26 - access("TAB2"."CERT_SERIAL_NUM"=1022)
27 - filter("VIEW2"."POLICY_ID"="TAB1"."POLICY_ID")
28 - access("TAB1"."TRANSACTION_ID"="TAB2"."TRANSACTION_ID")
Note: cpu costing is off
52 rows selected.
Elapsed: 00:00:03.37
Execution Plan
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 COLLECTION ITERATOR (PICKLER FETCH) OF 'DISPLAY'
Statistics
38 recursive calls
0 db block gets
287 consistent gets
0 physical reads
0 redo size
5006 bytes sent via SQL*Net to client
405 bytes received via SQL*Net from client
5 SQL*Net roundtrips to/from client
29 sorts (memory)
0 sorts (disk)
52 rows processed -
Exception caused by bind variables in ORDER BY clause and VO RANGE_PAGING
Hi,
I'm using a ViewObject in RANGE_PAGING mode and discovered a problem when using bind variables in the ORDER BY clause of my statement:
SELECT * FROM (SELECT /*+ FIRST_ROWS */ IQ.*, ROWNUM AS Z_R_N FROM (
SELECT * FROM T_TABLE WHERE (attr1 = :1) ORDER BY decode (attr2, :2, 1, null, 0, -1) desc, attr3 ) IQ
WHERE ROWNUM < :2) WHERE Z_R_N > :3 When a bind variable is used in the ORDER BY CLAUSE and the method VO.getEstimatedRowCount() is call then the DB issued an SQL error:
java.sql.SQLException: Ungültiger Spaltenindex (eng.: invalid column index)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:137)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:174)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:239)
at oracle.jdbc.driver.OraclePreparedStatement.setStringInternal(OraclePreparedStatement.java:4612)The numbering of the bind variables indicates that the last two bind variables have the wrong numbering (??)
When I rewrite the SQL into the following statement, the SQL error does not occur but I have not verified yet that the VO delivers the correct range of data because the numbering of the bind variables is not correct.
SELECT * FROM (SELECT /*+ FIRST_ROWS */ IQ.*, ROWNUM AS Z_R_N FROM (
SELECT *, decode (attr2, :1, 1, null, 0, -1) as ATTR_FOR_SORTING FROM T_TABLE WHERE (attr1 = :2) ORDER BY ATTR_FOR_SORTING desc, attr3 ) IQ
WHERE ROWNUM < :2) WHERE Z_R_N > :3I'm working with JDev 10.1.2 and Oracle DB 9203.
Any comments are welcome!
Thanks,
MarkusYou are using the bind variable :2 twice. Did you try
SELECT * FROM (SELECT /*+ FIRST_ROWS */ IQ.*, ROWNUM AS Z_R_N FROM (
SELECT * FROM T_TABLE WHERE (attr1 = :1) ORDER BY decode (attr2, :2, 1, null, 0, -1) desc, attr3 ) IQ
WHERE ROWNUM < :4) WHERE Z_R_N > :3
setWhereClauseParm(0, "a"); // :1
setWhereClauseParm(1, "b"); // :2
setWhereClauseParm(2, "c"); // :3
setWhereClauseParm(3, "b"); // :2setting the fourth parameter the same as the second one?
I remeber reading something about using bind variables twice causing problems, but I#m not sure about it. -
JPQL - No UPPER() in ORDER BY clause??
I have created a NamedQuery and am attempting to order my returned collection using the ORDER BY clause, however, the specification asks for string ordering to be case insensitive. It seems that I cannot do that with the Java Persistence Query Language - or at least the implementation that we are using. I am using Glassfish v2ur2 with uses Oracle TopLink Essentials - 2.0.1, Build b04-fcs (found in my Exception message).
I suspect that the only way to do what I want is to create a Comparator for the ResultList and run a sort after I get the result list from my EntityManager. Is that correct or is my syntax wrong in my JPQL?
Here is my named query (cut from a larger list of named queries), pretty simple:
@NamedQuery(name = "MyObject.findAll", query = "SELECT a FROM MyObject a ORDER BY UPPER(a.myString), a.Id")Here is a summary exception report that I receive:
===========================================================================
Exception: javax.ejb.EJBException
Description: nested exception is: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.RemoteException: null; nested exception is:
Exception [TOPLINK-8024] (Oracle TopLink Essentials - 2.0.1 (Build b04-fcs (04/11/2008))): oracle.toplink.essentials.excepti
ons.EJBQLException
Exception Description: Syntax error parsing the query [MyObject.findAll: SELECT a FROM MyObject a WHERE ORDER BY UPPER(a.myString), a.Id], line 1, column 81: syntax error at [UPPER].
Internal Exception: line 1:81: expecting IDENT, found 'UPPER'
(Stack-Trace Included)
===========================================================================Post Author: krypton
CA Forum: Data Connectivity and SQL
Thanks Lynn
I tried your suggestion. But there is one probelm.
When i sort the data in descending order using the count(calls) field, the data is returned but the customer's name appears multiple times along with their calls raised.
E.g, if customer Mark raised multiple calls i.e. 2, 5, and 10 calls, then the report will show
Mark 2
Mark 5
Mark 10
But is there a way to aggregate all the calls for mark and show them only once:
such as Mark 17
Thanks -
[JPA/TOPLINK] is the function "lower" supported in "order by" clause?
In EJB-QL
I can use lower() or upper() in where clause.
But there is always a parse exception thrown when i tried to use it in main clause or order by clause.
works:
select s from Student s where lower(s.name) like 'm%'
exception thrown:
select s from Student s where s.name like 'm%' order by lower(s.name)
OR --------------
Why i am asking this is that the resultset returned from database is not alphabetical sorted but ascii sorted, which means any characters with upper case is always prior to the ones with lower case.
If EJB-QL doesn't support using lower() in order by clause, do I have any other options to avoid this problem?
BTW, it is the Oracle 10g we are using as DB
many thanks,
Xuphey
Edited by: Xuphey on Nov 29, 2007 1:33 AMIf you want to do this, you'd have to use dynamic SQL (execute immediate or DBMS_SQL). For the easier 'execute immediate' approach, you'd do something like
create or replace someProc( someArg varchar2 )
as
strSQL varchar2(4000)
begin
strSQL := <<string containing your SQL statement up to the order by clause>>
strSQL := strSQL || 'ORDER BY ' || someArg
execute immediate strSQL;
endJustin -
Can I use an expression in order by clause
SELECT
PERIOD_NUM, period_num *12,
period_name,
--TO_DATE(SUBSTR(PERIOD_NAME,1,3)| |SUBSTR(PERIOD_NAME,INSTR(PERIOD_NAME,'-'),3),'MON-RR'),
TO_NUMBER(TO_CHAR(TO_DATE((SUBSTR(PERIOD_NAME,1,3)| |SUBSTR(PERIOD_NAME,INSTR(PERIOD_NAME,'-')+1,2)),'MONRR'),'RRRRMM'))
FROM GL.GL_PERIODS
order by 2--TO_NUMBER(TO_CHAR(TO_DATE(SUBSTR(PERIOD_NAME,1,3)| |SUBSTR(PERIOD_NAME,INSTR(PERIOD_NAME,'-')+1,2),'MONRR'),'RRRRMM'))
desc
gl_periods is a table, period_name consists of values like oct-01_fy-01 etc and oct01_01_fy-01
I want to sort on this column based on period_name, so I am trying to convert into number like for oct-01_fy-01, the query gives
200110 and so on. the recent period comes first, But my question is I can't use the same to_number(.....) in the order by clause. oracle gives an error
ORA-01843: not a valid month.
Let me know whether anyone come across with this kind of situationIf you are sure the expression is correct, since you are using it in the select clause, give an alias and use the alias in the order by clause.
null
Maybe you are looking for
-
Disabling Ultranav TouchPad keeping TrackPoint
I have a Ultranav keyboard and I want to disable the Touchpad but keep the Trackpoint. I'm using the latest driver (noted below), but it doesn't have an Ultranav tab in the Control Panel. I've searched the net and can't find any real solution. Has
-
AP Distribution line, PO, and Inv Info Needed
Is this the place to ask for accounts payble help? Having a hard time getting po line and inv data to appear in my code since one of the tables needs to be outer joined twice so that if an inv isn't tied to a PO then it still appears, and that table
-
Editing a movie that was already cut together without transcoding .h264 footage to proresslt. I want to transcode full clips that are used in the edit, but not any of the leftovers. Is there an efficient way to this? I'm thinking I can convert the fi
-
Can I use a old dot matrix printer with my mac
I want to add a old Panasonic KX-P2023 and use it as my printer. I have a mac osx 10.7.5 is this possible??
-
Hello The download to excel and PDF documents now includes images. I have inlcuded images in my web templates to execute commands eg: Download to Excel, Bookmake etc. See below: img onclick="executeJS_EXPORT_XSLT120();" alt="Download to Excel" src="