Order By Vs. RowNum
Hello,
My query has an Order By statement (order by tblA.Name) .
When the query runs this is the order the records come out:
1) All records that have a space in the first byte of their Name field.
2) All records whos name begins with a special character like: #1 Italian Restuarant.
3) All records whos name begins with a numeric like: 21 Club
4) and finally all Alpha records....A - Z.
Now if I only want to select the first 300 rows, (still using the same Order By). In my Where clause I put (oracle):
and RowNum < 300.
When the query runs I get this order:
1st) Alpha records....A - Z.
Can anyone explain what to do about this?
Thanks for your time!
Hi,
In any single query, ROWNUM is assigned before ORDER BY is applied.
If you want just the opposite, do the ORDER BY in a sub-query and the ROWNUM in its super-query:
WITH ordered_rows AS
SELECT * -- or whatever
FROM tbla
ORDER BY name
SELECT *
FROM ordered_rows
WHERE ROWNUM <= 300;
Similar Messages
-
Using order by and rownum in massive tables
Hi,
I need to retreive paginated and ordered data from a big table.
I know some different tips using rownum or the RANK() function and subqueries, these tips work well for small amount of data, but I need to get the data from a table with 200.000 entries (not under my control), and with all those methods is necessary to order first the data and then select your range, so performance is extremely poor.
Anybody knows a better solution? it doesn't matter if is plain SQL(better) or PL/SQL.
Thanks in advancebut I was looking for something like the LIMIT in MySQL or TOP in msSQL where all the sorting is made internally and it's really fast If the data needs sorting, I do not think Oracle would take any longer to do that than the others mentioned, unless the other DBs mentioned, only sort the rows that are actually being returned.
As for the LIMIT clause, Oracle already has that clause available when FETCHing from a CURSOR:
SQL> DECLARE
2 CURSOR emp_cur IS
3 SELECT * FROM scott.emp;
4 TYPE emp_rec_table IS TABLE OF emp_cur%ROWTYPE INDEX BY BINARY_INTEGER;
5 emp_tbl emp_rec_table;
6 BEGIN
7 OPEN emp_cur;
8 LOOP
9 emp_tbl.DELETE;
10 FETCH emp_cur BULK COLLECT
11 INTO emp_tbl LIMIT 5;
12 EXIT WHEN emp_tbl.COUNT <= 0;
13 dbms_output.put_line(emp_tbl.COUNT || ' rows fetched using LIMIT clause.');
14 END LOOP;
15 CLOSE emp_cur;
16 END;
17 /
5 rows fetched using LIMIT clause.
5 rows fetched using LIMIT clause.
4 rows fetched using LIMIT clause.
PL/SQL procedure successfully completed.
SQL> disconnect
Disconnected from Oracle9i Enterprise Edition Release 9.2.0.3.0 - Production
With the Partitioning, OLAP and Oracle Data Mining options
JServer Release 9.2.0.3.0 - Production
SQL> -
Order BY with ROWNUM in Select List
Hi,
I have query like bellow for Oracle 11g:
create table em_c (vl_s_ec int,id_em_em int,id_empcre_ecr int, id_em_ec int);
create table em (id_em_em int)
Select e.id_em_em
, NVL(
(SELECT * FROM(SELECT a.vl_s_ec FROM em_c a WHERE a.id_em_em = ec.id_em_em
AND a.id_empcre_ecr < ec.id_em_ec order by a.id_em_ec DESC) WHERE ROWNUM <= 1) ,0) AS col2
FROM em_c ec
INNER JOIN em e on ec.id_em_em = e.id_em_em
WHERE 1 = 1;
But inner subselect doesn't see table "em_c ec" from outer FROM clause. That's why following error occurs:
SQL Error: ORA-00904: "EC"."ID_EM_EC": invalid identifier
Please help me to make it work.
Edited by: user11290901 on Dec 17, 2010 2:11 AMCorrelation names only go one level deep. It's a bit tough to decipher your query so if you want a better response please post the following:
1. Oracle version (SELECT * FROM V$VERSION)
2. Sample data in the form of CREATE / INSERT statements.
3. Expected output
4. Explanation of expected output (A.K.A. "business logic")
5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details. -
Order by, cursor, rownum
i want to select 10 database entires
from an 8i database with the selector variable and sort the entries by a date
column.
but the problem is that my sql statement
(see below) selects first the entries
and then the entries get ordered.
what i need is first the entries ordered
and then the select. otherwise it is possible
that i get on the next page with the next
10 entries that this entries may be with a date that should be on the prev. page.
has anyone an idea?
thx
SELECT *
FROM (SELECT col1,
col2
FROM table
WHERE ROWNUM < (selector + 10)
MINUS
SELECT col1,
col2
FROM table
WHERE ROWNUM < selector)
ORDER BY TO_DATE (col2, 'DD.MM.YYYY HH24:MI');In Oracle 8i, the general format for this sort of "top-n" analysis is:
SELECT column1, column2, ROWNUM
FROM (SELECT column1, column2
FROM table_name
ORDER BY top_n_column DESC)
WHERE ROWNUM <= number_of_rows;
Applying that to this situation, the query would be something like:
SELECT col1, col2, ROWNUM
FROM (SELECT col1, col2
FROM table
ORDER BY TO_DATE(col2, 'DD.MM.YYYY HH24:MI') DESC)
WHERE ROWNUM <= 10;
When you put the ORDER BY clause in a sub-query as above, the ORDER BY is applied before the numbering of the rows, so the pseudo-column ROWNUM has some meaning and usefulness.
However, for those of us who are still using versions prior to Oracle 8i, we can't have an ORDER BY clause in a sub-query; It will generate a somewhat confusing error about a missing parenthesis. Therefore, the pseudo-column ROWNUM has no meaning or usefulness. So, prior to Oracle 8i, for "top-n" analysis, the general format is something like this (It will also still work in 8i):
SELECT outer.column1, outer.column2
FROM table_name outer
WHERE number_of_rows >=
(SELECT COUNT (*) + 1
FROM table_name inner
WHERE inner.top_n_column > outer.top_n_column)
ORDER BY outer.top_n_column DESC;
Applying that to this situation, the query would be something like:
SELECT outer.col1, outer.col2
FROM table outer
WHERE 10 >=
(SELECT COUNT (*) + 1
FROM table inner
WHERE TO_DATE(inner.col2,'DD.MM.YYYY HH24:MI') > TO_DATE(outer..col2,'DD.MM.YYYY HH24:MI'))
ORDER BY TO_DATE(outer.col2,'DD.MM.YYYY HH24:MI') DESC;
A lot of people keep asking for queries to select the first few or last few rows entered in a table, without ordering by a specific column (for what purpose I am not sure). It is a common mistake to attempt to use ROWNUM for this purpose. However, ROWID is assigned an incremental value upon input, not upon ordering or retrieval, like ROWNUM. Therefore, the pseudo-column ROWID can be used as a comparison column for the same sort of "top-n" analysis like this:
For the first n rows:
SELECT outer.column1, outer.column2, ROWID
FROM table_name outer
WHERE n >=
(SELECT COUNT (*) + 1
FROM table_name inner
WHERE inner.ROWID < outer.ROWID)
ORDER BY ROWID;
For the last n rows:
SELECT outer.column1, outer.column2, ROWID
FROM table_name outer
WHERE n >=
(SELECT COUNT (*) + 1
FROM table_name inner
WHERE inner.ROWID > outer.ROWID)
ORDER BY ROWID DESC;
If you are only attempting to retrieve one row, with or without a comparison column, then you can use things like MIN, MAX, NOT IN, NOT EXISTS, and set operators to find that one row.
I have seen a lot of confusion on this topic and I hope this explanation was thorough enough to help clarify it for some.
null -
I am trying to select top 200 records from a really complex select query with order by. But Oracle does top 200 first then order by if I put rownum and order by in one select query, which will give me top 200 records redomly every time. I know a way to work around is doing following
select * from (select................ order by ......) where rownum<=200
but this will really take long time since the inner select query is big one. it joins 15 some tables to get all informations. I know in MS SQL, you can have select top(200)...... ordery by ...., it will do order by then top 200. This is making query running really fast.
Is there other ways to make this run faster in Oracle. Possiblely puting oder by and rownum<200 in one select query?
Thanks!
Edited by: user4916474 on Jan 14, 2011 8:24 AMHi,
See these threads for the information you need to post when you have a performace issue:
When your query takes too long ...
HOW TO: Post a SQL statement tuning request - template posting
If you have a complicated query involving 15 tables, the solution is likely to be complicated, too. For example, you might need to find the top 200 rows before joining all the tables, so just looking for an alternative to ROWNUM probably won't help all by itself, though it may be part of the overall solution.
One alternative to ROWNUM is the analytic ROW_NUMBER function:
SELECT *
FROM (
SELECT ...
, ROW_NUMBER () OVER (ORDER BY ...) AS r_num
FROM ...
WHERE r_num <= 200
;It might not be faster than ROWNUM, but it's probably not slower, either, and it can be adapted to other requirements (e.g., the top 200 for each department). -
Order by AND rownum in a function?
I have a table with articles sorted by an id. In the table is also a date field to tell when the article is written.
I want a query that returns the 20 latest articles, and this is what i have come up with:
SELECT * FROM (
SELECT articleid,writtendate
FROM articles
ORDER BY writtendate desc)
WHERE ROWNUM < 21;
This works alright, BUT I want it in a function! There it doesnt compile!!! Anyone got any suggestions?
I have tried to separate the stuff, like first sorting the records in a view and then selecting the top 20 after that. I could try a cursor and fetching out of that, but havent suceeded with that either.
Bye!ok, the sql statement works perfectly in an sql editor, but wont compile in a function.
FUNCTION fnc_getLatest20 (
cur IN OUT pkg_cursor.refcur
)RETURN pkg_exception.return_type IS
BEGIN
OPEN cur FOR
SELECT * FROM (
SELECT articleid,writtendate
FROM articles
ORDER BY writtendate DESC)
WHERE ROWNUM < 21;
RETURN pkg_exception.err_none;
END;
The best I have is that either the rows returned in the cursor is all rows, ordered correctly or the top twenty in some other order.
I most be on the wrong track here, there has to be some easier way of doing this...
BTW, thanks for the help so far. -
Question about order by and rownum and subqueries.
Can you explain why test 4 below results as it results- with returning no rows?
Identificator "PKG_INTRA_CUSTOMER_SEARCH.NAME" is a package function, which returns value from a variable declared in package body, the function returns value 'e%'.
Please note that tests 1-3 all returned data, but test 4 didn't. Why? My porpouse is that test 4 would also return data.
1. Query without "rownum" and with "Order by" returns 2 records:
select q.*--, rownum
,PKG_INTRA_CUSTOMER_SEARCH.NAME
from
select c.ID,
c.NAME,
c.CODE
from V_CUSTOMER c
where 1=1 and lower(c.NAME) like PKG_INTRA_CUSTOMER_SEARCH.NAME
order by c.NAME, c.ID
) q
10020 Ees Nimi 37810010237 e%
10040 ewewrwe werwerwer e%2. Query with "rownum" and without "Order by" returns 2 records:
select q.*, rownum
,PKG_INTRA_CUSTOMER_SEARCH.NAME
from
select c.ID,
c.NAME,
c.CODE
from V_CUSTOMER c
where 1=1 and lower(c.NAME) like PKG_INTRA_CUSTOMER_SEARCH.NAME
--order by c.NAME, c.ID
) q
10020 Ees Nimi 37810010237 e%
10040 ewewrwe werwerwer e%3.Query without "rownum" and with "Order by" returns 2 records:
select q.*--, rownum
,PKG_INTRA_CUSTOMER_SEARCH.NAME
from
select c.ID,
c.NAME,
c.CODE
from V_CUSTOMER c
where 1=1 and lower(c.NAME) like PKG_INTRA_CUSTOMER_SEARCH.NAME
order by c.NAME, c.ID
) q
10020 Ees Nimi 37810010237 e%
10040 ewewrwe werwerwer e% 4. Query with "rownum" and with "Order by" returns 0 records:
select q.*, rownum
,PKG_INTRA_CUSTOMER_SEARCH.NAME
from
select c.ID,
c.NAME,
c.CODE
from V_CUSTOMER c
where 1=1 and lower(c.NAME) like PKG_INTRA_CUSTOMER_SEARCH.NAME
order by c.NAME, c.ID
) qHi,
please reproduce the question in your test database with script below.
My general question is that wht Test5 below returns only 1 row, but Test5 returns 3 rows.
The difference between those two tests is only that one has "order by" clause, the other doesn't have.
I need the "order by" clause to stay, but seems like it is not allowed.
CREATE OR REPLACE
PACKAGE PACKAGE1 AS
function NAME return varchar2;
END PACKAGE1;
CREATE OR REPLACE
PACKAGE body PACKAGE1 AS
function NAME return varchar2
is
begin
return 'e%';
end NAME;
END PACKAGE1;
select PACKAGE1.name from dual--e%
create table Tbl AS
(SELECT 'e2b' Col1, 'A' Col2, 'AA' Col3 FROM dual
UNION
SELECT 'e3b', 'B','BB' FROM dual
--Test5:
select q.*, rownum pos, PACKAGE1.name f
from
select c.col1,
c.col2,
c.col3
from Tbl c
where 1=1 and lower(c.col1) like PACKAGE1.name
order by c.col2, c.col1
) q
union all
select '111' , '111' , '111' , 0 pos, PACKAGE1.name f from dual --return 1 row
--Test6
select q.*, rownum pos, PACKAGE1.name f
from
select c.col1,
c.col2,
c.col3
from Tbl c
where 1=1 and lower(c.col1) like PACKAGE1.name
--order by c.col2, c.col1
) q
union all
select '111' , '111' , '111' , 0 pos, PACKAGE1.name f from dual --return 3 rowsEdited by: CharlesRoos on Feb 17, 2010 5:30 AM -
TIPS(46) : ROWNUM(ORDERING 순으로 NUMBERING, RANGE SELECT)
제품 : SQL*PLUS
작성날짜 : 2003-07-30
TIPS(46) : ROWNUM(ORDERING 순으로 NUMBERING, RANGE SELECT)
=========================================================
PURPOSE
Explanation
SQL*PLUS에서 ORDERING 순으로 NUMBERING하기를 원하는 경우가 많으나,
ORDERING이 되기 전에 RANDOM ACCESS 시
ROWNUM이 ASSIGN되기 때문에, 다음과 같은 결과가 나타날 것이다.
SQL> select ename, rownum from emp;
ENAME ROWNUM
ALLEN 1
JONES 2
BLAKE 3
CLARK 4
KING 5
ADAMS 6
JAMES 7
FORD 8
SQL> select ename, rownum from emp order by ename;
ENAME ROWNUM
ADAMS 6
ALLEN 1
BLAKE 3
CLARK 4
FORD 8
JAMES 7
JONES 2
KING 5
Example
다음의 몇 가지 방법을 이용하여 ORDERING 순으로 NUMBERING을 나타내어 보자.
1) RECORD를 COUNT하는 방법 (DATA가 많은 경우 부적절)
SQL> select A.ename, count(*) position
2 from emp A, emp B
3 where A.ename > B.ename
4 or A.ename = B.ename and A.empno >= B.empno
5 group by A.empno, A.ename
6 order by A.ename, A.empno;
ENAME POSITION
ADAMS 1
ALLEN 2
BLAKE 3
CLARK 4
FORD 5
JAMES 6
JONES 7
KING 8
2) INDEX를 이용하는 방법
SQL> create index sort_ix on emp (ename);
Index created.
SQL> select ename, rownum from emp where ename > ' ';
ENAME ROWNUM
ADAMS 1
ALLEN 2
BLAKE 3
CLARK 4
FORD 5
JAMES 6
JONES 7
KING 8
cf) descending인 경우 아래처럼 hint 사용 바람
select /*+ index_desc(emp ename_ix) */
ename, rownum from emp
where ename > ' ' and rownum < 4;
3) OPTIMIZER를 이용하는 방법
SQL> select rownum, ename
2 from emp , dual
3 where emp.ename = dual.dummy (+);
ROWNUM ENAME
1 ADAMS
2 ALLEN
3 BLAKE
4 CLARK
5 FORD
6 JAMES
7 JONES
8 KING
위에서 언급한 내용에 더해서 rownum을 where 절에 사용함에 있어서는
rownum 1을 포함하는 range(예 : 'where rownum <= 100')에 대해서만
정상적인 조회가 가능하다.
만약 rownum 1을 포함하지 않는 range(예 : 'where rownum between 50 and 100')
에 대한 자료 조회를 원한다면 다음과 같이 in-line view를 이용하는 방법을
사용할 수 있다.
select rn, ename
from ( select rownum rn, ename
from emp)
where rn between 3 and 5 ;
RN ENAME
3 BLAKE
4 CLARK
5 KING
Execution Plan
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 VIEW
2 1 COUNT
3 2 TABLE ACCESS (FULL) OF 'EMP'
* 이 때 in-line view의 rownum에는 반드시 alias를 이용해야 한다.
in-line view에 의해서 선택되어지는 data가 많다면 performance가
떨어질 수 있다.
Reference Documents
-------------------제품 : SQL*PLUS
작성날짜 : 2003-07-30
TIPS(46) : ROWNUM(ORDERING 순으로 NUMBERING, RANGE SELECT)
=========================================================
PURPOSE
Explanation
SQL*PLUS에서 ORDERING 순으로 NUMBERING하기를 원하는 경우가 많으나,
ORDERING이 되기 전에 RANDOM ACCESS 시
ROWNUM이 ASSIGN되기 때문에, 다음과 같은 결과가 나타날 것이다.
SQL> select ename, rownum from emp;
ENAME ROWNUM
ALLEN 1
JONES 2
BLAKE 3
CLARK 4
KING 5
ADAMS 6
JAMES 7
FORD 8
SQL> select ename, rownum from emp order by ename;
ENAME ROWNUM
ADAMS 6
ALLEN 1
BLAKE 3
CLARK 4
FORD 8
JAMES 7
JONES 2
KING 5
Example
다음의 몇 가지 방법을 이용하여 ORDERING 순으로 NUMBERING을 나타내어 보자.
1) RECORD를 COUNT하는 방법 (DATA가 많은 경우 부적절)
SQL> select A.ename, count(*) position
2 from emp A, emp B
3 where A.ename > B.ename
4 or A.ename = B.ename and A.empno >= B.empno
5 group by A.empno, A.ename
6 order by A.ename, A.empno;
ENAME POSITION
ADAMS 1
ALLEN 2
BLAKE 3
CLARK 4
FORD 5
JAMES 6
JONES 7
KING 8
2) INDEX를 이용하는 방법
SQL> create index sort_ix on emp (ename);
Index created.
SQL> select ename, rownum from emp where ename > ' ';
ENAME ROWNUM
ADAMS 1
ALLEN 2
BLAKE 3
CLARK 4
FORD 5
JAMES 6
JONES 7
KING 8
cf) descending인 경우 아래처럼 hint 사용 바람
select /*+ index_desc(emp ename_ix) */
ename, rownum from emp
where ename > ' ' and rownum < 4;
3) OPTIMIZER를 이용하는 방법
SQL> select rownum, ename
2 from emp , dual
3 where emp.ename = dual.dummy (+);
ROWNUM ENAME
1 ADAMS
2 ALLEN
3 BLAKE
4 CLARK
5 FORD
6 JAMES
7 JONES
8 KING
위에서 언급한 내용에 더해서 rownum을 where 절에 사용함에 있어서는
rownum 1을 포함하는 range(예 : 'where rownum <= 100')에 대해서만
정상적인 조회가 가능하다.
만약 rownum 1을 포함하지 않는 range(예 : 'where rownum between 50 and 100')
에 대한 자료 조회를 원한다면 다음과 같이 in-line view를 이용하는 방법을
사용할 수 있다.
select rn, ename
from ( select rownum rn, ename
from emp)
where rn between 3 and 5 ;
RN ENAME
3 BLAKE
4 CLARK
5 KING
Execution Plan
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 VIEW
2 1 COUNT
3 2 TABLE ACCESS (FULL) OF 'EMP'
* 이 때 in-line view의 rownum에는 반드시 alias를 이용해야 한다.
in-line view에 의해서 선택되어지는 data가 많다면 performance가
떨어질 수 있다.
Reference Documents
------------------- -
Strange problem with results ordering
Hi!
I select some varchar2 data and order them:
SELECT rownum, xyz FROM analitika where xyz <= 'ABC' order by xyz
This is pretty straightforward, no problems expected here, right? However, the results, when read as they pour in, are not ordered. I get something like
3 abc
1 aaa
2 abb
Rownums are assigned correctly, but the data has not been sent in correct order. I feel this has something to do with connection settings, that it is set to return any results as quickly as possible.
The database is 10g XE on fedora core 4.Ok, here is the actual data from the database (copy/paste from helpdb). I have removed rownum from the query because it seems to cause confusion.
Please notice these things:
A.A.M.-MIHALINEC kd
A&B doo
A.B.A. D.O.O.
The sequence of rows beginning with "A." should not have been interrupted by the row beginning with "A&". There are more examples. BTW, shouldn't numbers come before letters?
After I have looked closer, it seems that oracle has disregarded any non-alphanumeric characters when sorting.
SELECT naziv from analitika where naziv <= 'ABC' order by naziv
NAZIV
A & B d.o.o.
A CETIRI INFO d.o.o.
A KAJ
A KONZALTING
A S I
A&A
AAG DIZAJN CENTAR d.o.o. ZAGREB
AAG DIZAJN CENTAR d.o.o. ZAGREB
A.A.M.-MIHALINEC K.D.
A.A.M.-MIHALINEC k.d.
A.A.M.-MIHALINEC kd
AAP ELEKTRONIK
AAR
AARIS
AB AUTOMATIKA
AB COLOR d.o.o.
AB COMERCE D.O.O.
AB DIZAJN - VL. MIRA BILIC
A&B doo
AB GRADNJA OBRT
AB INTELCOM
AB PETROL PROMET
AB SITOTISAK
A.B.A. D.O.O.
A.B.A. DOO
ABA VELA
ABACUS
ABACUS - OBRT
ABACUS d.o.o. VRBOVEC
ABAK INENJERING
ABAKUS
ABAK-US DOO
ABAKUS RACUNALA
ABATON
ABATON D.O.O.
ABATOURS
ABB d.o.o. KARLOVAC
ABB d.o.o. ZAGREB
ABB d.o.o. ZAGREB
ABBA D.O.O.
ABBOTT LABORATORIES S.A. Diagnostics
A.B.I.G
A.C.N. D.O.O.
A/D ELECTRONIC D.O.O.
A/D ELECTRONIC d.o.o.
A.D. VINJAN
A.D.C. d.o.o.
A-DESIGN
A!DESIGN OBRT
A.D.INFORMATICKI SUSTAVI d.o.o.
A.D.-PROMET d.o.o.
A.D.Z.SARON
A.H. - ZAGREB d.o.o.
A.H.TRGOVINA d.o.o.
A.K.S. d.o.o.
A-KUD
A.M. ELEKTRONIK - OBRT, VL. ANIC M.
A-MAR d.o.o.
A.M.E.C.
A.M.E.C. d.o.o.
A.M.H. d.o.o.
A.M.-HIDRAULIKA
A.M.-HIDRAULIKA
A.M.I. LOVREKOVIC d.o.o.
A.M.S. CONTO D.O.O.
A.M.T. PETRAVIC
A.N.A.B.A.R. TOURS
A.P. FRIGO
A-PROMA
A.R.M.A.C.O.M. d.o.o.
A.R.Z.
A.S. REVIZOR D.O.O.
A.S.B.
A.S.D.
A.S.I. d.o.o.
A.S.TEKS D.O.O.
A.S.T.-PROM d.o.o.
A.. HAJDUK
A..-GAZELA D.O.O.
A-TEL
A.T.O.S. ELECTRONIC d.o.o.
A.V.V.I.S.
A.Z. PROMET
A.Z.I.L.
A1 CENTAR D.O.O.
/popuniti sa drugim kupcem
007 MILETIC k.d.
2. A.M. D.O.O.
2 A.M. doo
2. GARDIJSKA BRIGADA MORH
2 I d.o.o.
2 N
2D IMPULS d.o.o.
2M COMPUTERS d.o.o. BLOKADA!
2M D.O.O.
3 C CONING
3 DK d.o.o.
3 Ka
3 M
3 M PORT
3. MAJ BRODOGRADILITE d.d.
3. MAJ MOTORI I DIZALICE d.d.
3. MAJ OEK
3. MAJ TIBO d.d.
3 P-T
3 R
3 V
3 Z
3D STUDIO LEON
3K d.o.o.
3M DOO
3T.CABLE d.o.o.
312 ARHIT. RADIONICA
32 BITA d.o.o.
36 d.o.o.
4 - MATE D.O.O.
4 D
4 IPO SOBE
40-BOX
5 F
5. KRUNA
5 M
5 M d.o.o.
5DO12 d.o.o.
5DO12 d.o.o.
5V-LAB
7 INVENT
128 rows returned in 0.01 seconds -
Different order in the results
I have a problem with order consistency in the data set on the screen vs. the sequence of records being selected one by one behind the screen.
Say, in the first form I select certain "where clause" and several "order by". I pass parameters to the second form, compile query in runtime and start bringing records into the form for update, one by one. That's when the original first screen order is being messed up.
Say, we have a group of records sorted by type, received_date. The set on the screen (user can only 2,3 and 4th columns) and in SQL*Plus would display:
Rownum Unique # Type Date
11 100 E 10/10/2005
13 103 E 10/10/2005
12 102 E 10/10/2005
14 104 E 10/10/2005
15 105 E 10/10/2005
Records retrieved by the second screen via cursor, one by one, would appear in the following order:
Rownum Unique # Type Date
11 100 E 10/10/2005
12 102 E 10/10/2005
13 103 E 10/10/2005
14 104 E 10/10/2005
15 105 E 10/10/2005
Basically, Oracle adds rownum as a last Order by to the customized Order By. Has anyone run into the similar problem and what did you do to fix it?And Rownum is an internal number that is applied AFTER the rows are sorted, so no matter how you order your records, Rownum will always start with 1.
Does my result have something to do with subquery?
SELECT rownum, unique#, report_type, received_date
FROM table x
WHERE condition blah-blah-blah
AND unique# IN (subquery from table y)
ORDER BY report_type ASC, received_date DESC
My query above gives the result as follows:
rownum unique# report_type received_date
1 4630093 E 4/8/2005
2 4630095 E 4/8/2005
3 4630096 E 4/8/2005
11 4629916 E 4/8/2005
4 4630099 E 4/8/2005
62 4631257 E 4/8/2005
64 4631286 E 4/8/2005
66 4631288 E 4/8/2005
68 4631290 E 4/8/2005
218 4630693 E 4/8/2005
196 4630163 E 4/8/2005
195 4630599 E 4/8/2005
194 4630580 E 4/8/2005
193 4631309 E 4/8/2005
192 4631308 E 4/8/2005
191 4631307 E 4/8/2005
167 4630012 E 4/8/2005
166 4630011 E 4/8/2005
165 4629997 E 4/8/2005
164 4629996 E 4/8/2005
163 4629989 E 4/8/2005
162 4630574 E 4/8/2005
67 4631289 E 4/8/2005
65 4631287 E 4/8/2005
63 4631259 E 4/8/2005
And then when retrieving one by one sorts by rownum (or unique #) -
SELECT ROWNUM and ORDEY BY DATE
I want to select the most recent row from a table where one column is null and have the following query.
'select * from table_name where rownum < 2 and column1 is null order by date_stamp desc'
Date_stamp column holds the system date when each row was inserted int this table. So whenever a row is insered into this table the date_stamp column always gets the curent sysem date.
This is always returning me the oldest row not the most recent row. I tried to use
GREATEST(select date_stamp from table_name)
but it did not work as GREATEST expects dats seprated by commas.
If there is a function which can convert the date_stamp to a numerical value(milliseconds from 1970 or something like what java has) I can order by that number and the most recent date should have the highest numerical value and thus should work.
Is there a way to do this without having to write a procedure or function? I'm using 8i(8.1.7).
ThanksNote that ORDER BY and ROWNUM cannot be combined the way you have in your query. Try this:
SELECT *
FROM (SELECT *
FROM table_name
WHERE column1 IS NULL
ORDER BY date_stamp DESC)
WHERE rownum = 1 -
Oracle - SQL - update sequential number based on order by clause
I have a procedure that inserts records in to a temporary table. After procedure execution, I want to update a field in the temp table (recno) with sequential number ordered by a field audit date which is a time stamp field
For example, after updating the recno field, if I give a query like below,
Select recno,audit_timestamp,<other fields> from audit_details
order by audit_timestamp
the output should display recno in the sequential order. Can any one guide me on how to achieve this using a SQL query?The audittime field is a timestamp field.
If I give the below query, rownum is not in the sequential order, see below few records..
SELECT rownum,to_char(audit_time_stamp,'dd-mon-yyyy HH24:MI:SS.FF') from audit_details ORDER BY audit_time_stamp
ROWNUM to_char(audit_time_stamp,'dd-mon-yyyy HH24:MI:SS.FF')
16 18-apr-2007 14:30:52.551010
17 18-apr-2007 16:33:21.900305
18 18-apr-2007 17:49:44.061420
19 18-apr-2007 17:49:44.134804
20 19-apr-2007 16:40:15.775235
21 22-apr-2007 23:31:01.818784
ROWNUM To_char(audit_time_stamp,'dd-mon-yyyy HH24:MI:SS.FF')
1 01-may-2007 19:17:46.880342
2 01-may-2007 19:24:04.952571
3 01-may-2007 19:24:32.182110
4 01-may-2007 19:25:49.464260
5 01-may-2007 19:25:52.127018
6 01-may-2007 19:27:34.099095
7 01-may-2007 19:30:34.763481
8 01-may-2007 19:31:06.226955
9 01-may-2007 19:32:36.727196
10 01-may-2007 19:40:44.061941 -
hi everybody,
I am at present using oracle 8i Release 2. According to my knowledge and "Oracle 8 complete reference", when we use ROWNUM, the rownum is decided when the data is selected from the database. So when we use "order by" clause actually the rownum gets jumbled up.
But to my surprise when i did something like this on my SQl prompt row num is acting very "innocent" :)
<Code>
1* select rownum, empno from emp
SQL> /
ROWNUM EMPNO
1 7369
2 7499
3 7521
4 7566
5 7654
6 7698
7 7782
8 7788
9 7839
10 7844
11 7876
12 7900
13 7902
14 7934
15 1
15 rows selected.
SQL> select rownum, empno from emp order by empno;
ROWNUM EMPNO
1 1
2 7369
3 7499
4 7521
5 7566
6 7654
7 7698
8 7782
9 7788
10 7839
11 7844
12 7876
13 7900
14 7902
15 7934
15 rows selected.
</Code>
As you can see rownum is ordered again .. m i missing something.
B)
Is it possible to get a row that was inserted last. Does oracle guarantee that data retrieval will be according to the time of inssertion !!
Thanx in advance
ChetanRownum is decided afeter the complete execution of ur SQL statment (it includes ordey by, group by, where etc.).
you can get the last inserted row using:
select * from emp where rowid=
(select max(rowid) from emp);
Regards
Riaz -
select /*+ ORDERED */
a,
b,
rownum
from
A
where
<condition>
order by a desc; Giving the output of rownum as unsorted manner.
I thought that rownum should start with 1 only.(concluded false by the above example)
In what cases the rownum should come in unsorted way.
Thanks
Praven"If an ORDER BY clause follows ROWNUM in the same query, then the rows will be reordered by the ORDER BY clause."
http://download.oracle.com/docs/cd/E11882_01/server.112/e26088/pseudocolumns009.htm#SQLRF00255
In other words: rownum is assigned before the order by:
SQL> create table t as
2 select 2 a from dual union all
3 select 5 a from dual union all
4 select 1 a from dual union all
5 select 4 a from dual union all
6 select 3 a from dual;
Table created.
SQL> select a
2 , rownum
3 from t;
A ROWNUM
2 1
5 2
1 3
4 4
3 5
SQL> select a
2 , rownum
3 from t
4 order by a;
A ROWNUM
1 3
2 1
3 5
4 4
5 2 -
Temporary table within a package
I'm not sure this is the best way to achieve it, but I'm trying to use a temporary table within my package, but I failed!
In my package, my procedure do receive 5 different phone numbers (vTel1 to vTel5) and I need to order them, using data from a table. Also, if 2 of them are the same, I need only the one with the highest rank.
Let say my TelOrder table look likes:
Reason
Tel1
Tel2
Tel3
Tel4
Tel5
Reason1
2
3
1
5
4
Reason2
1
2
null
3
4
And I receive those variable
vTel1='5141111111'
vTel2=null
vTel3='5143333333'
vTel4='5141111111'
vTel5='5145555555'
vReason='Reason1'
Using the Reason1, I need to be able to get the result looking like:
RowNum
Phone
Order
1
5143333333
1
2
5141111111
2
3
5145555555
4
And I need this code to be apart from the procedure, cause many procedures will use the same code, and I don't want to abuse the ctrl+c, ctrl+v at each update.
I've come close by using something like:
EXECUTE IMMEDIATE '
INSERT INTO Table
SELECT Rownum as RN, Ordre, contact_info, Contact_info_type
FROM
(SELECT a.contact_info, a.ordre, contact_info_type FROM
(SELECT contact_info,min(ordre) as Ordre FROM
(SELECT Tel1 as Ordre, ''' || vTel1 || ''' as contact_info, 1 as contact_info_type FROM TelOrder WHERE Reason=''' || vReason || '''
UNION ALL
SELECT Tel2 as Ordre, ''' || vTel2 || ''' as contact_info, 2 as contact_info_type FROM TelOrder WHERE Reason=''' || vReason || '''
UNION ALL
SELECT Tel3 as Ordre, ''' || vTel3 || ''' as contact_info, 4 as contact_info_type FROM TelOrder WHERE Reason=''' || vReason || '''
UNION ALL
SELECT Tel4 as Ordre, ''' || vTel4 || ''' as contact_info, 4 as contact_info_type FROM TelOrder WHERE Reason=''' || vReason || '''
UNION ALL
SELECT Tel5 as Ordre, ''' || vTel5 || ''' as contact_info, 1 as contact_info_type FROM TelOrder WHERE Reason=''' || vReason || '''
WHERE Ordre is not null and contact_info is not null
GROUP BY contact_info
) a
JOIN
(SELECT Tel1 as Ordre, ''' || vTel1 || ''' as contact_info, 1 as contact_info_type FROM TelOrder WHERE Reason=''' || vReason || '''
UNION ALL
SELECT Tel2 as Ordre, ''' || vTel2 || ''' as contact_info, 2 as contact_info_type FROM TelOrder WHERE Reason=''' || vReason || '''
UNION ALL
SELECT Tel3 as Ordre, ''' || vTel3 || ''' as contact_info, 4 as contact_info_type FROM TelOrder WHERE Reason=''' || vReason || '''
UNION ALL
SELECT Tel4 as Ordre, ''' || vTel4 || ''' as contact_info, 4 as contact_info_type FROM TelOrder WHERE Reason=''' || vReason || '''
UNION ALL
SELECT Tel5 as Ordre, ''' || vTel5 || ''' as contact_info, 1 as contact_info_type FROM TelOrder WHERE Reason=''' || vReason || '''
) b ON a.contact_info=b.contact_info AND a.ordre=b.ordre
ORDER BY a.Ordre
But when I try to remove this code and send it into another procedure/function, I can't make it work.
PLEASE HELP!!!!No Database to try it. Check at your own risk if this might work for you
no version specified from your side, NOT TESTED from my side, so let's say we're even
select row_number() over (order by the_order) "RowNum",
the_val "Phone",
the_order "Order"
from (select v.the_val,t.the_order,
row_number() over (partition by v.the_val order by t.the_order) rn
from (select reason,the_order,the_phone
from (select reason,tel1,tel2,tel3,tel4,tel5
from telorder
where reason = :the_reason
unpivot include nulls (the_order for the_phone in (tel1 as 'tel1',
tel2 as 'tel2',
tel3 as 'tel3',
tel4 as 'tel4',
tel5 as 'tel5'
) t,
(select 'tel1' the_var,:v_tel1 the_val from dual union all
select 'tel2' the_var,:v_tel2 the_val from dual union all
select 'tel3' the_var,:v_tel3 the_val from dual union all
select 'tel4' the_var,:v_tel4 the_val from dual union all
select 'tel5' the_var,:v_tel5 the_val from dual
) v
where t.reason = :v_reason
and t.the_phone = v.the_var
where rn = 1
and the_val is not null
Regards
Etbin
Maybe you are looking for
-
How can I link to a jsp page from another jsp page within websphere portal?
Afternoon all, I have a websphere portlet which displays a jsp page. I want to put a hyperlink on the jsp page which when clicked will open another jsp page. Does anyone know how to do this? Thanks, Alex
-
Purchase Order E- Mail Issue for Vendor .
Dear All Gurus, User is complaining that a perticular Vendor is not getting Purchase Order throught E MAIL , i had simulated the scenario in Test Client and given an Outp
-
ITunes[260:16443]: iTunes: Backup error -30
When I try to synchronize my iPhone I always have the save message : Unable to backup the iPhone... When I look at the Console, I read the following message iTunes[260:16443]: iTunes: Backup error -30 Could someone help me ?
-
Firewire card or adapter for g7 1237dx
I have a G7-1237dx. Can I get a firewire card or adapter to allow me to run pro tools? Need a 6pin firewire solution. thanks Steve
-
How can I test that the ITS is setup right and working?.
How can I test that the ITS is setup right and working?. At present when calling a CRM transaction (BOR object) via the Nav Bar of the Webclient IC I am getting a message box with the title of 'Message from Webpage' and the content saying 'Object exp