Limit a select statement
hey everyone
i was wondering if someone could assist me and tell me how to limit a select statement to just the top 25 outputs. ie: the top 25 employees with the longest years of service.
any help, i am just learning this stuff
thanks
josh
Assuming the structure of the emp table in the scott schema, something like
SELECT *
FROM (SELECT *
FROM emp
ORDER BY hiredate desc)
WHERE rownum < 25Justin
Distributed Database Consulting, Inc.
http://www.ddbcinc.com/askDDBC
Similar Messages
-
I m trying to find if LIMIT is a part of the select statement and if works like
set rowcount 1 in sybase....if anyone can post the generic select statement with LIMIT in it that would be great!
any help or input will be greatly appreciated
Thanks!Hallo,
i don't know sybase, but it is probably rownum
select * from scott.emp
where rownum < 3
Regards
Dmytro -
How can I limit the number of rows returned by a select stat
How can I limit the number of rows returned by a select
statement. I have a query where I return the number of stores
that are located in a given area.. I only want to return the
first twenty-five stores. In some instances there may be over
200 stores in a given location.
I know is SQL 7 that I can set the pagesize to be 25....
Anything similiar in Oracle 8i?
nullDebbie (guest) wrote:
: Chad Nale (guest) wrote:
: : How can I limit the number of rows returned by a select
: : statement. I have a query where I return the number of
: stores
: : that are located in a given area.. I only want to return the
: : first twenty-five stores. In some instances there may be
: over
: : 200 stores in a given location.
: : I know is SQL 7 that I can set the pagesize to be 25....
: : Anything similiar in Oracle 8i?
: If you are in Sql*Plus, you could add the statement
: WHERE rownum <= 25
: Used together with an appropriate ORDER BY you
: could get the first 25 stores.
Watch out. ROWNUM is run before ORDER BY so this would only
order the 25 selected
null -
Limit rows in select statement
Hi,
we have the following SQL select statement in an extension in our CMS system
var newConn = new openConnection();
if(request.searchBox)
var searchBox = request.searchBox;
var keywords = searchBox.split(' ')
var sql = 'SELECT forumID, masterID, subject, message, datePosted FROM THREADS WHERE approved=1'
for(var i=0; i<keywords.length; i++)
sql += ' AND UPPER(subject) LIKE UPPER(\'%' + keywords[i] + '%\')'
sql += ' OR UPPER(message) LIKE UPPER(\'%' + keywords[i] + '%\')'
sql += ' ORDER BY datePosted DESC;';
else {
document.write("No results found");
var result = newConn.execute(sql);
var counter = 0;
while(result && (counter < 5 || request.searchBox))
ascii_nextCol(result[0]); //Datafield 0 Forum ID
ascii_nextCol(result[1]); //Datafield 1 Master ID
ascii_nextCol(result[2]); //Datafield 2 Subject
ascii_nextCol(result[3]); //Datafield 3 Message
ascii_nextCol(dateFormatter.format(result[4])); //Datafield 4 Date posted
ascii_nextRow();
result = newConn.nextRow();
counter++;
closeConnection(newConn);
ascii_update();
There are a couple of issues with it though, this bit doesn't work when no results are returned:
else {
document.write("No results found");
And I want to limit the number of rows to 50.
Someone mentioned that "ROWCOUNT" could be the answer to both problems but I have no idea where it should go or how to write it into this code. I've tried Googling for an answer without much luck as I don't know a great deal about this coding.
Can anyone help?Aga wrote:
Try adding
sql += ' AND rownum < 51'
before
sql += ' ORDER BY datePosted DESC;';
It will limit the number of rows to 50.If you limit by rownum and order in the same query you are ordering 50 random rows of the query.
you should order in a subquery before using rownum to get only the top results.
Processing ...
with t as (
select 120 as val from dual
union all
select -5 as val from dual
union all
select 45 as val from dual
union all
select 3 as val from dual
union all
select 1258 as val from dual
union all
select 874552 as val from dual
union all
select -1452 as val from dual
union all
select 0 as val from dual
select *
from t
where rownum <= 3
order by val
Query finished, retrieving results...
VAL
-5
45
120
3 row(s) retrieved
Processing ...
with t as (
select 120 as val from dual
union all
select -5 as val from dual
union all
select 45 as val from dual
union all
select 3 as val from dual
union all
select 1258 as val from dual
union all
select 874552 as val from dual
union all
select -1452 as val from dual
union all
select 0 as val from dual
select *
from (
select *
from t
order by val
where rownum <= 3
Query finished, retrieving results...
VAL
-1452
-5
0
3 row(s) retrievedBye Alessandro -
Logical limit on Select clause
I am working on Oracle 10g 10.2.0.3 and I cannot select more than 1000 columns using SQL.
But I could select more than 1000 columns in Oracle 11g R2.
What is the limit on number of columns that can be selected in a select query on Oracle 11g R2?
Also, can i get Oracle documentation which specifies this limit for select query?
Edited by: 844063 on Apr 26, 2011 10:53 PMWell, then, on a related note, I have at least some tables that do not show all the columns in the column or data views in SQL Developer. I get the first 76 columns for one table that I have in mind. The index build utility also does not show all the available columns in the table.
"Select *" does show all the columns, and so does the DESCRIBE statement. Is there a setting in preferences (I couldn't find it) that controls this? -
Hi,
I have recently been asked to generate a program that reports of payroll postings to FI. This involves creating a giant select statement from the ppoix table to gather all the postings. My select statement is as follows:
SELECT pernr "EE Number
seqno "Sequential number
actsign "Indicator: Status of record
runid "Number of posting run
postnum "Number
tslin "Line number of data transfer
lgart "Wage Type
betrg "Amount
waers "Currency
anzhl "Number
meins "Base unit of measure
spprc "Special processing of posting items
momag "Transfer to FI/CO:EE grouping for acct determi
komok "Transfer to FI/CO: Symbolic account
mcode "Matchcode search term
koart "Account assignment type
auart "Expenditure type
nofin "Indicator: Expenditure type is not funded
INTO CORRESPONDING FIELDS OF TABLE i_ppoix
FROM ppoix
FOR ALL ENTRIES IN run_doc_xref
WHERE runid = run_doc_xref-runid
AND tslin = run_doc_xref-linum
AND spprc <> 'A'
AND lgart IN s_lgart
AND pernr in s_pernr.
where s_pernr is a select option that holds personnel nummbers and s_lgart is a select option that holds wagetypes. This statement works fine for a certain amount of personnel numbers and a certain amount of wagetypes, but once you exceed a certain limit the Database does not allow you to perform a select statement this large. Is there a better way to perform such a large select such as this one) ie: FM, or some other method I am not aware of. This select statement comes from the standard SAP delivered cost center admin report and this report dumps as well when too much data is passed to it.
any ideas would be much appreciated.
thanks.The problem here is with the select-options.
For a select statement, you cannot have more that certain amount of data.
The problem with your select becomes complex because of the FOR ALL ENTRIES in and the huge s_pernr and the 40 million records :(.
I am guessing that the s_lgart will be small.
How many entries do you have in internal table "run_doc_xref"?
If there are not that many, then I would suggest this:
TYPES:
BEGIN OF ty_temp_ppoix,
pernr TYPE ppoix-pernr,
lgart TYPE ppoix-lgart,
seqno TYPE ppoix-seqno,
actsign TYPE ppoix-actsign,
runid TYPE ppoix-runid,
postnum TYPE ppoix-postnum,
tslin TYPE ppoix-tslin,
betrg TYPE ppoix-betrg,
spprc TYPE ppoix-spprc,
END OF ty_temp_ppoix.
DATA:
i_temp_ppoix TYPE SORTED TABLE OF ty_temp_ppoix
WITH NON-UNIQUE KEY pernr lgart
INITIAL SIZE 0
WITH HEADER LINE.
DATA:
v_pernr_lines TYPE sy-tabix,
v_lgart_lines TYPE sy-tabix.
IF NOT run_doc_xref[] IS INITIAL.
DESCRIBE TABLE s_pernr LINES v_pernr_lines.
DESCRIBE TABLE s_lgart LINES v_lgart_lines.
IF v_pernr_lines GT 800 OR
v_lgart_lines GT 800.
* There is an index on runid and tslin. This should be ok
* ( still bad because of the huge table :( )
SELECT pernr lgart seqno actsign runid postnum tslin betrg spprc
* Selecting into sorted TEMP table here
INTO TABLE i_temp_ppoix
FROM ppoix
FOR ALL ENTRIES IN run_doc_xref
WHERE runid = run_doc_xref-runid
AND tslin = run_doc_xref-linum
AND spprc <> 'A'.
* The sorted table should make the delete faster
DELETE i_temp_ppoix WHERE NOT pernr IN s_pernr
AND NOT lgart IN s_lgart.
* Now populate the actual target
LOOP AT i_temp_ppoix.
MOVE: i_temp_ppoix-pernr TO i_ppoix-pernr.
* and the rest of the fields
APPEND i_ppoix.
DELETE i_temp_ppoix.
ENDLOOP.
ELSE.
SELECT pernr seqno actsign runid postnum tslin lgart betrg spprc
* Selecting into your ACTUAL target here
INTO TABLE i_ppoix
FROM ppoix
FOR ALL ENTRIES IN run_doc_xref
WHERE runid = run_doc_xref-runid
AND tslin = run_doc_xref-linum
AND spprc <> 'A'
AND pernr IN s_pernr
AND lgart IN s_lgart.
ENDIF.
ELSE.
* Error message because of no entries in run_doc_xref?
* Please answer this so a new solution can be implemented here
* if it is NOT an error
ENDIF.
Hope this helps.
Regards,
-Ramesh -
Limitations in using a function within a select statement
I have a function which retrieves various data elements from the
database and formats it accordingly. The data (varchar2)
returned could be in excess of 2,000 characters length.
I need to use the returned data as part of a view. I am able to
use the function in a "select" statement, but when I use it with
returned data in excess of 2,000 chars, I get the following
error:
ORA-06502: PL/SQL: numeric or value error
This error is occurring whenever the returned data is in excess
of 2,000 characters.
Is there an alternative method to what I am proposing, I have
tried alternative data types but if I am able to use it in a
"select" statement, I get the above error when the returned
length exceeds 2,000 chars.
Thanks
Peterare u using oracle 7. varchar2 limit in 8 is 4000.
-
TDE Issue with UPDATE/SELECT statement
We just implemented TDE on a table and now our import script is getting errors. The import script has not changed and has been running fine for over a year. The script failed right after applying TDE on the table.
Oracle 10g Release 2 on Solaris.
Here are the encrypted colums:
COLUMN_NAME ENCRYPTION_ALG SALT
PERSON_ID AES 192 bits key NO
PERSON_KEY AES 192 bits key NO
USERNAME AES 192 bits key NO
FIRST_NAME AES 192 bits key NO
MIDDLE_NAME AES 192 bits key NO
LAST_NAME AES 192 bits key NO
NICKNAME AES 192 bits key NO
EMAIL_ADDRESS AES 192 bits key NO
AKO_EMAIL AES 192 bits key NO
CREATION_DATE AES 192 bits key NO
Here is the UPDATE/SELECT statement that is failing:
UPDATE cslmo_framework.users a
SET ( person_id
, username
, first_name
, middle_name
, last_name
, suffix
, user_status_seq
= (
SELECT person_id
, username
, first_name
, middle_name
, last_name
, suffix
, user_status_seq
FROM cslmo.vw_import_employee i
WHERE i.person_key = a.person_key
WHERE EXISTS
SELECT 1
FROM cslmo.vw_import_employee i
WHERE i.person_key = a.person_key
AND ( NVL(a.person_id,0) <> NVL(i.person_id,0)
OR NVL(a.username,' ') <> NVL(i.username,' ')
OR NVL(a.first_name,' ') <> NVL(i.first_name,' ')
OR NVL(a.middle_name,' ') <> NVL(i.middle_name,' ')
OR NVL(a.last_name,' ') <> NVL(i.last_name,' ')
OR NVL(a.suffix,' ') <> NVL(i.suffix,' ')
OR NVL(a.user_status_seq,99) <> NVL(i.user_status_seq,99)
cslmo@awpswebj-dev> exec cslmo.pkg_acpers_import.p_users
Error importing USERS table.START p_users UPDATE
Error Message: ORA-01483: invalid length for DATE or NUMBER bind variableI rewrote the procedure using BULK COLLECT and a FORALL statement and that seems to work fine. Here is the new code:
declare
bulk_errors EXCEPTION ;
PRAGMA EXCEPTION_INIT(bulk_errors,-24381) ;
l_idx NUMBER ;
l_err_msg VARCHAR2(2000) ;
l_err_code NUMBER ;
l_update NUMBER := 0 ;
l_count NUMBER := 0 ;
TYPE person_key_tt
IS
TABLE OF cslmo_framework.users.person_key%TYPE
INDEX BY BINARY_INTEGER ;
arr_person_key person_key_tt ;
TYPE person_id_tt
IS
TABLE OF cslmo_framework.users.person_id%TYPE
INDEX BY BINARY_INTEGER ;
arr_person_id person_id_tt ;
TYPE username_tt
IS
TABLE OF cslmo_framework.users.username%TYPE
INDEX BY BINARY_INTEGER ;
arr_username username_tt ;
TYPE first_name_tt
IS
TABLE OF cslmo_framework.users.first_name%TYPE
INDEX BY BINARY_INTEGER ;
arr_first_name first_name_tt ;
TYPE middle_name_tt
IS
TABLE OF cslmo_framework.users.middle_name%TYPE
INDEX BY BINARY_INTEGER ;
arr_middle_name middle_name_tt ;
TYPE last_name_tt
IS
TABLE OF cslmo_framework.users.last_name%TYPE
INDEX BY BINARY_INTEGER ;
arr_last_name last_name_tt ;
TYPE suffix_tt
IS
TABLE OF cslmo_framework.users.suffix%TYPE
INDEX BY BINARY_INTEGER ;
arr_suffix suffix_tt ;
TYPE user_status_seq_tt
IS
TABLE OF cslmo_framework.users.user_status_seq%TYPE
INDEX BY BINARY_INTEGER ;
arr_user_status_seq user_status_seq_tt ;
CURSOR users_upd IS
SELECT i.person_key
,i.person_id
,i.username
,i.first_name
,i.middle_name
,i.last_name
,i.suffix
,i.user_status_seq
FROM cslmo.vw_import_employee i ,
cslmo_framework.users u
WHERE i.person_key = u.person_key ;
begin
OPEN users_upd ;
LOOP
FETCH users_upd
BULK
COLLECT
INTO arr_person_key
, arr_person_id
, arr_username
, arr_first_name
, arr_middle_name
, arr_last_name
, arr_suffix
, arr_user_status_seq
LIMIT 100 ;
FORALL idx IN 1 .. arr_person_key.COUNT
SAVE EXCEPTIONS
UPDATE cslmo_framework.users u
SET
person_id = arr_person_id(idx)
, username = arr_username(idx)
, first_name = arr_first_name(idx)
, middle_name = arr_middle_name(idx)
, last_name = arr_last_name(idx)
, suffix = arr_suffix(idx)
, user_status_seq = arr_user_status_seq(idx)
WHERE u.person_key = arr_person_key(idx)
AND
( NVL(u.person_id,0) != NVL(arr_person_id(idx),0)
OR
NVL(u.username,' ') != NVL(arr_username(idx),' ')
OR
NVL(u.first_name,' ') != NVL(arr_first_name(idx),' ')
OR
NVL(u.middle_name, ' ') != NVL(arr_middle_name(idx), ' ')
OR
NVL(u.last_name,' ') != NVL(arr_last_name(idx),' ')
OR
NVL(u.suffix,' ') != NVL(arr_suffix(idx),' ')
OR
NVL(u.user_status_seq,99) != NVL(arr_user_status_seq(idx),99)
l_count := arr_person_key.COUNT ;
l_update := l_update + l_count ;
EXIT WHEN users_upd%NOTFOUND ;
END LOOP ;
CLOSE users_upd ;
COMMIT ;
dbms_output.put_line('updated records: ' || l_update);
EXCEPTION
WHEN bulk_errors THEN
FOR i IN 1 .. sql%BULK_EXCEPTIONS.COUNT
LOOP
l_err_code := sql%BULK_EXCEPTIONS(i).error_code ;
l_err_msg := sqlerrm(-l_err_code) ;
l_idx := sql%BULK_EXCEPTIONS(i).error_index;
dbms_output.put_line('error code: ' || l_err_code);
dbms_output.put_line('error msg: ' || l_err_msg);
dbms_output.put_line('at index: ' || l_idx);
END LOOP ;
ROLLBACK;
RAISE;
end ;
cslmo@awpswebj-dev> @cslmo_users_update
updated records: 1274There are about 20 or so other procedure in the import script. I don't want to rewrite them.
Does anyone know why the UPDATE/SELECT is failing? I checked Metalink and could not find anything about this problem.This is now an Oracle bug, #9182070 on Metalink.
TDE (transparent data encryption) does not work when an update/select statement references a remote database. -
Slow query results for simple select statement on Exadata
I have a table with 30+ million rows in it which I'm trying to develop a cube around. When the cube processes (sql analysis), it queries back 10k rows every 6 seconds or so. I ran the same query SQL Analysis runs to grab the data in toad and exported results, and the timing is the same, 10k every 6 seconds or so. r
I ran an execution plan it returns just this:
Plan
SELECT STATEMENT ALL_ROWSCost: 136,019 Bytes: 4,954,594,096 Cardinality: 33,935,576
1 TABLE ACCESS STORAGE FULL TABLE DMSN.DS3R_FH_1XRTT_FA_LVL_KPI Cost: 136,019 Bytes: 4,954,594,096 Cardinality: 33,935,576 I'm not sure if there is a setting in oracle (new to the oracle environment) which can limit performance by connection or user, but if there is, what should I look for and how can I check it.
The Oracle version I'm using is 11.2.0.3.0 and the server is quite large as well (exadata platform). I'm curious because I've seen SQL Server return 100k rows ever 10 seconds before, I would assume an exadata system should return rows a lot quicker. How can I check where the bottle neck is?
Edited by: k1ng87 on Apr 24, 2013 7:58 AMk1ng87 wrote:
I've notice the same querying speed using Toad (export to CSV)That's not really a good way to test performance. Doing that through Toad, you are getting the database to read the data from it's disks (you don't have a choice in that) shifting bulk amounts of data over your network (that could be a considerable bottleneck) and then letting Toad format the data into CSV format (process the data adding a little bottleneck) and then write the data to another hard disk (more disk I/O = more bottleneck).
I don't know exedata but I imagine it doesn't quite incorporate all those bottlenecks.
and during cube processing via SQL Analysis. How can I check to see if its my network speed thats effecting it?Speak to your technical/networking team, who should be able to trace network activity/packets and see what's happening in that respect.
Is that even possible as our system resides off site, so the traffic is going through multiple networks.Ouch... yes, that could certainly be responsible.
I don't think its the network though because when I run both at the same time, they both are still querying at about 10k rows every 6 seconds.I don't think your performance measuring is accurate. What happens if you actually do the cube in exedata rather than using Toad or SQL Analysis (which I assume is on your client machine?) -
Performance Tuning 'Runtime Error' on Select statement
Hi Experts,
Good Day!
I would like to ask some help regarding a custom program that will encounter 'Runtime Error' on the below codes on how to perform performance tunning especially number 1.
1.
SELECT A~VBELN A~ERDAT A~AUART A~VKORG A~VTWEG A~SPART A~VDATU
A~KUNNR B~POSNR B~MATNR B~ARKTX B~ABGRU B~KWMENG B~VRKME
B~WERKS B~VSTEL B~ROUTE
FROM VBAK AS A INNER JOIN VBAP AS B ON A~VBELN EQ B~VBELN
INNER JOIN VBEP AS C ON A~VBELN EQ C~VBELN
AND B~POSNR EQ C~POSNR
INTO CORRESPONDING FIELDS OF TABLE I_DATA_TAB
WHERE A~VBELN IN S_VBELN
AND A~VKORG IN S_VKORG
AND A~AUART IN S_AUART
AND A~VTWEG IN S_VTWEG
AND A~SPART IN S_SPART
AND A~VDATU IN S_VDATU
AND A~KUNNR IN S_KUNNRD
AND B~MATNR IN S_MATNR
AND B~KWMENG IN S_KWMENG
AND B~VRKME IN S_VRKME
AND B~WERKS IN S_WERKS
AND C~EDATU IN S_VDATU.
2.
SELECT VBELN FROM LIKP INTO LIKP-VBELN
WHERE LFDAT IN S_VDATU
AND VKORG IN S_VKORG
AND LFART EQ 'YSTD'
AND KUNNR IN S_KUNNRP
AND KUNAG IN S_KUNNRD
SELECT VBELN POSNR LFIMG MATNR WERKS
FROM LIPS INTO (LIPS-VBELN, LIPS-POSNR, DISPLAY_TAB-DEL_QTY,
LIPS-MATNR, LIPS-WERKS)
WHERE VBELN EQ LIKP-VBELN
AND MATNR IN S_MATNR
AND VTWEG IN S_VTWEG
AND SPART IN S_SPART
AND WERKS IN S_WERKS.
ENDSELECT.
ENDSELECT.
4.
SELECT DELIVERY POSNR MATNR PODLFIMG FROM T9YPODI INTO
(T9YPODI-DELIVERY, T9YPODI-POSNR, T9YPODI-MATNR, T9YPODI-PODLFIMG)
WHERE MATNR IN S_MATNR
AND PODDATE IN S_VDATU.
Answer's will be a great help.
~Thank You,
Lourd
Edited by: Lourd06 on Oct 23, 2009 10:32 AM
Moderator message - Welcome to SCN.
Moderator message - Please see Please Read before Posting in the Performance and Tuning Forum before posting. You're in the driver's seat here. It's up to you to do some analysis before expecting that people can halp you. - post locked
And please use code tags.
Edited by: Rob Burbank on Oct 23, 2009 9:13 AMHi All,
We've checked the transaction ST22 it is TIME OUT. I really need your help on this the program will dump in number 1 Select statement. Can you help me perform a performance tunning.
In transaction ST22
Runtime Errors TIME_OUT
Date and Time 21.10.2009 08:51:33
Short text
Time limit exceeded.
What happened?
The program "ZV0PSR10" has exceeded the maximum permitted runtime without
interruption and has therefore been terminated.
What can you do?
Note down which actions and inputs caused the error.
To process the problem further, contact you SAP system
administrator.
Using Transaction ST22 for ABAP Dump Analysis, you can look
at and manage termination messages, and you can also
keep them for a long time.
Error analysis
After a specific time, the program is terminated to make the work area
available to other users who may be waiting.
This is to prevent a work area being blocked unnecessarily long by, for
example:
- Endless loops (DO, WHILE, ...),
- Database accesses with a large result set
- Database accesses without a suitable index (full table scan)
The maximum runtime of a program is limited by the system profile
parameter "rdisp/max_wprun_time". The current setting is 1200 seconds. If this
time limit is
exceeded, the system attempts to cancel any running SQL statement or
signals the ABAP processor to stop the running program. Then the system
waits another 60 seconds maximum. If the program is then still active,
the work process is restarted.
~Thank you
Lourd
Edited by: Lourd06 on Oct 23, 2009 11:22 AM
Edited by: Lourd06 on Oct 23, 2009 11:33 AM -
Joins And For all Enteries in Select Statement
Could you please tell me when there is a high amount of data which is being handled in the table, does the use of INNER JOINS and FOR ALL ENTERIES in SELECT Statement decreases the system performance? ?
Can you also let me know where can i get some tips regarding do's and dont's for ABAP Programming, I want to increase my system performance.
Currently the programs which are being used are taking a lot of time for execution...
Its very URGENT!Hai Jyotsna
Go through the following Tips for improving Performence
For all entries
The for all entries creates a where clause, where all the entries in the driver table are combined with OR. If the number of entries in the driver table is larger than rsdb/max_blocking_factor, several similar SQL statements are executed to limit the length of the WHERE clause.
The plus
Large amount of data
Mixing processing and reading of data
Fast internal reprocessing of data
Fast
The Minus
Difficult to program/understand
Memory could be critical (use FREE or PACKAGE size)
Some steps that might make FOR ALL ENTRIES more efficient:
Removing duplicates from the driver table
Sorting the driver table
If possible, convert the data in the driver table to ranges so a BETWEEN statement is used instead of and OR statement:
FOR ALL ENTRIES IN i_tab
WHERE mykey >= i_tab-low and
mykey <= i_tab-high.
Nested selects
The plus:
Small amount of data
Mixing processing and reading of data
Easy to code - and understand
The minus:
Large amount of data
when mixed processing isnt needed
Performance killer no. 1
Select using JOINS
The plus
Very large amount of data
Similar to Nested selects - when the accesses are planned by the programmer
In some cases the fastest
Not so memory critical
The minus
Very difficult to program/understand
Mixing processing and reading of data not possible
Use the selection criteria
SELECT * FROM SBOOK.
CHECK: SBOOK-CARRID = 'LH' AND
SBOOK-CONNID = '0400'.
ENDSELECT.
SELECT * FROM SBOOK
WHERE CARRID = 'LH' AND
CONNID = '0400'.
ENDSELECT.
Use the aggregated functions
C4A = '000'.
SELECT * FROM T100
WHERE SPRSL = 'D' AND
ARBGB = '00'.
CHECK: T100-MSGNR > C4A.
C4A = T100-MSGNR.
ENDSELECT.
SELECT MAX( MSGNR ) FROM T100 INTO C4A
WHERE SPRSL = 'D' AND
ARBGB = '00'.
Select with view
SELECT * FROM DD01L
WHERE DOMNAME LIKE 'CHAR%'
AND AS4LOCAL = 'A'.
SELECT SINGLE * FROM DD01T
WHERE DOMNAME = DD01L-DOMNAME
AND AS4LOCAL = 'A'
AND AS4VERS = DD01L-AS4VERS
AND DDLANGUAGE = SY-LANGU.
ENDSELECT.
SELECT * FROM DD01V
WHERE DOMNAME LIKE 'CHAR%'
AND DDLANGUAGE = SY-LANGU.
ENDSELECT.
Select with index support
SELECT * FROM T100
WHERE ARBGB = '00'
AND MSGNR = '999'.
ENDSELECT.
SELECT * FROM T002.
SELECT * FROM T100
WHERE SPRSL = T002-SPRAS
AND ARBGB = '00'
AND MSGNR = '999'.
ENDSELECT.
ENDSELECT.
Select Into table
REFRESH X006.
SELECT * FROM T006 INTO X006.
APPEND X006.
ENDSELECT
SELECT * FROM T006 INTO TABLE X006.
Select with selection list
SELECT * FROM DD01L
WHERE DOMNAME LIKE 'CHAR%'
AND AS4LOCAL = 'A'.
ENDSELECT
SELECT DOMNAME FROM DD01L
INTO DD01L-DOMNAME
WHERE DOMNAME LIKE 'CHAR%'
AND AS4LOCAL = 'A'.
ENDSELECT
Key access to multiple lines
LOOP AT TAB.
CHECK TAB-K = KVAL.
ENDLOOP.
LOOP AT TAB WHERE K = KVAL.
ENDLOOP.
Copying internal tables
REFRESH TAB_DEST.
LOOP AT TAB_SRC INTO TAB_DEST.
APPEND TAB_DEST.
ENDLOOP.
TAB_DEST[] = TAB_SRC[].
Modifying a set of lines
LOOP AT TAB.
IF TAB-FLAG IS INITIAL.
TAB-FLAG = 'X'.
ENDIF.
MODIFY TAB.
ENDLOOP.
TAB-FLAG = 'X'.
MODIFY TAB TRANSPORTING FLAG
WHERE FLAG IS INITIAL.
Deleting a sequence of lines
DO 101 TIMES.
DELETE TAB_DEST INDEX 450.
ENDDO.
DELETE TAB_DEST FROM 450 TO 550.
Linear search vs. binary
READ TABLE TAB WITH KEY K = 'X'.
READ TABLE TAB WITH KEY K = 'X' BINARY SEARCH.
Comparison of internal tables
DESCRIBE TABLE: TAB1 LINES L1,
TAB2 LINES L2.
IF L1 <> L2.
TAB_DIFFERENT = 'X'.
ELSE.
TAB_DIFFERENT = SPACE.
LOOP
AT TAB1.
READ TABLE TAB2 INDEX SY-TABIX.
IF TAB1 <> TAB2.
TAB_DIFFERENT = 'X'. EXIT.
ENDIF.
ENDLOOP.
ENDIF.
IF TAB_DIFFERENT = SPACE.
ENDIF.
IF TAB1[] = TAB2[].
ENDIF.
Modify selected components
LOOP AT TAB.
TAB-DATE = SY-DATUM.
MODIFY TAB.
ENDLOOP.
WA-DATE = SY-DATUM.
LOOP AT TAB.
MODIFY TAB FROM WA TRANSPORTING DATE.
ENDLOOP.
Appending two internal tables
LOOP AT TAB_SRC.
APPEND TAB_SRC TO TAB_DEST.
ENDLOOP
APPEND LINES OF TAB_SRC TO TAB_DEST.
Deleting a set of lines
LOOP AT TAB_DEST WHERE K = KVAL.
DELETE TAB_DEST.
ENDLOOP
DELETE TAB_DEST WHERE K = KVAL.
Tools available in SAP to pin-point a performance problem
· The runtime analysis (SE30)
· SQL Trace (ST05)
· Tips and Tricks tool
· The performance database
Optimizing the load of the database
Using table buffering
Using buffered tables improves the performance considerably. Note that in some cases a statement can not be used with a buffered table, so when using these statements the buffer will be bypassed. These statements are:
Select DISTINCT
ORDER BY / GROUP BY / HAVING clause
Any WHERE clause that contains a sub query or IS NULL expression
JOIN s
A SELECT... FOR UPDATE
If you wan t to explicitly bypass the buffer, use the BYPASS BUFFER addition to the SELECT clause.
Use the ABAP SORT Clause Instead of ORDER BY
The ORDER BY clause is executed on the database server while the ABAP SORT statement is executed on the application server. The database server will usually be the bottleneck, so sometimes it is better to move the sort from the database server to the application server.
If you are not sorting by the primary key ( E.g. using the ORDER BY PRIMARY key statement) but are sorting by another key, it could be better to use the ABAP SORT statement to sort the data in an internal table. Note however that for very large result sets it might not be a feasible solution and you would want to let the database server sort it.
Avoid the SELECT DISTINCT Statement
As with the ORDER BY clause it could be better to avoid using SELECT DISTINCT, if some of the fields are not part of an index. Instead use ABAP SORT + DELETE ADJACENT DUPLICATES on an internal table, to delete duplicate rows.
Thanks & regards
Sreenivasulu P -
ABAP Joins or Separate select statements?
Hi,
I am working on a simulation of an implementation project as part of my in-house training programme. I am a rookie to ABAP and am now doing a print program that requires master data selection from tables ANLZ, LFA1, MSEG and CSKT, and also related line items from ANLA.
As a former Java/.NET programmer I used to play with database joins. Now since ABAP joins are much simpler to use, I take the best advantage of them. For instance, in this particular program, I fetched related data from ANLZ, ANLA, LFA1 and CSKT into one internal table using a single select statement with ABAP joins.
Now I happen to hear (in bits and pieces) that one should limit the use of nested joins to a certain extend. Instead, for the above program, I was advised to use 4 internal tables and to select data separately using FOR ALL ENTRIES. But in this case, we need to use 4 select statements, which means 4 database operations in place of just one.
From ABAP documentation, I read that we can link upto 24 tables in a single select statement using ABAP joins.
Can anyone clarify more about this? Which is high on performance?
Using a single select statement using joins
or
Using multiple selects -- FOR ALL ENTRIES?
Thanks and regards,
ArunHi Arun,
you keep reading in these forums that FOR ALL ENTRIES is more performant, but this is simply not true.
In your example, joining four tables for one DB operation is better than storing a lot of redundant data in internal tables just to perform four separate DB operations using FOR ALL ENTRIES.
Make sure you join the tables correctly, i.e. link dependent tables giving their full primary key.
FOR ALL ENTRIES can be used where effective join statements are not possible, e.g. when cluster tables are involved (like BSEG).
Cheers
Thomas
Edit: check this out too: Inner Join or For All Entries -
SELECT statement (urgent!)
Could you please help me with the following statement?
The FROM clause is incorrect but i don't know what i should write.
Thank you in advance.
Maria.
DECLARE
A NUMBER;
CURSOR C1 IS
SELECT TABLE_NAME, COLUMN_NAME
FROM USER_TAB_COLUMNS
WHERE NULLABLE='N' AND TABLE_NAME LIKE 'P_%';
BEGIN
FOR i IN C1
LOOP
SELECT COUNT(*) INTO A
FROM i.TABLE_NAME
WHERE i.COLUMN_NAME IS NOT NULL;
END LOOP;
END;
/FOR-LOOP
Whereas the number of iterations through a WHILE loop is unknown until the loop completes, the number of iterations through a FOR loop is known before the loop is entered. FOR loops iterate over a specified range of integers. The range is part of an iteration scheme, which is enclosed by the keywords FOR and LOOP. A double dot (..) serves as the range operator. The syntax follows:
FOR counter IN [REVERSE] lower_bound..higher_bound LOOP
sequence_of_statements
END LOOP;
The range is evaluated when the FOR loop is first entered and is never re-evaluated.
As the next example shows, the sequence of statements is executed once for each integer in the range. After each iteration, the loop counter is incremented.
FOR i IN 1..3 LOOP -- assign the values 1,2,3 to i
sequence_of_statements -- executes three times
END LOOP;
The following example shows that if the lower bound equals the higher bound, the sequence of statements is executed once:
FOR i IN 3..3 LOOP -- assign the value 3 to i
sequence_of_statements -- executes one time
END LOOP;
By default, iteration proceeds upward from the lower bound to the higher bound. However, as the example below shows, if you use the keyword REVERSE, iteration proceeds downward from the higher bound to the lower bound. After each iteration, the loop counter is decremented. Nevertheless, you write the range bounds in ascending (not descending) order.
FOR i IN REVERSE 1..3 LOOP -- assign the values 3,2,1 to i
sequence_of_statements -- executes three times
END LOOP;
Inside a FOR loop, the loop counter can be referenced like a constant but cannot be assigned values, as the following example shows:
FOR ctr IN 1..10 LOOP
IF NOT finished THEN
INSERT INTO ... VALUES (ctr, ...); -- legal
factor := ctr * 2; -- legal
ELSE
ctr := 10; -- not allowed
END IF;
END LOOP;
Iteration Schemes
The bounds of a loop range can be literals, variables, or expressions but must evaluate to numbers. Otherwise, PL/SQL raises the predefined exception VALUE_ERROR. The lower bound need not be 1, as the examples below show. However, the loop counter increment (or decrement) must be 1.
j IN -5..5
k IN REVERSE first..last
step IN 0..TRUNC(high/low) * 2
Internally, PL/SQL assigns the values of the bounds to temporary PLS_INTEGER variables, and, if necessary, rounds the values to the nearest integer. The magnitude range of a PLS_INTEGER is -2**31 .. 2**31. So, if a bound evaluates to a number outside that range, you get a numeric overflow error when PL/SQL attempts the assignment, as the following example shows:
DECLARE
hi NUMBER := 2**32;
BEGIN
FOR j IN 1..hi LOOP -- causes a 'numeric overflow' error
END LOOP;
END;
Some languages provide a STEP clause, which lets you specify a different increment (5 instead of 1 for example). PL/SQL has no such structure, but you can easily build one. Inside the FOR loop, simply multiply each reference to the loop counter by the new increment. In the following example, you assign today's date to elements 5, 10, and 15 of an index-by table:
DECLARE
TYPE DateList IS TABLE OF DATE INDEX BY BINARY_INTEGER;
dates DateList;
k CONSTANT INTEGER := 5; -- set new increment
BEGIN
FOR j IN 1..3 LOOP
dates(j*k) := SYSDATE; -- multiply loop counter by increment
END LOOP;
END;
Dynamic Ranges
PL/SQL lets you determine the loop range dynamically at run time, as the following example shows:
SELECT COUNT(empno) INTO emp_count FROM emp;
FOR i IN 1..emp_count LOOP
END LOOP;
The value of emp_count is unknown at compile time; the SELECT statement returns the value at run time.
What happens if the lower bound of a loop range evaluates to a larger integer than the upper bound? As the next example shows, the sequence of statements within the loop is not executed and control passes to the next statement:
-- limit becomes 1
FOR i IN 2..limit LOOP
sequence_of_statements -- executes zero times
END LOOP;
-- control passes here
Scope Rules
The loop counter is defined only within the loop. You cannot reference it outside the loop. After the loop is exited, the loop counter is undefined, as the following example shows:
FOR ctr IN 1..10 LOOP
END LOOP;
sum := ctr - 1; -- not allowed
You need not explicitly declare the loop counter because it is implicitly declared as a local variable of type INTEGER. The next example shows that the local declaration hides any global declaration:
DECLARE
ctr INTEGER;
BEGIN
FOR ctr IN 1..25 LOOP
IF ctr > 10 THEN ... -- refers to loop counter
END LOOP;
END;
To reference the global variable in this example, you must use a label and dot notation, as follows:
<<main>>
DECLARE
ctr INTEGER;
BEGIN
FOR ctr IN 1..25 LOOP
IF main.ctr > 10 THEN -- refers to global variable
END IF;
END LOOP;
END main;
The same scope rules apply to nested FOR loops. Consider the example below. Both loop counters have the same name. So, to reference the outer loop counter from the inner loop, you must use a label and dot notation, as follows:
<<outer>>
FOR step IN 1..25 LOOP
FOR step IN 1..10 LOOP
IF outer.step > 15 THEN ...
END LOOP;
END LOOP outer;
Using the EXIT Statement
The EXIT statement lets a FOR loop complete prematurely. For example, the following loop normally executes ten times, but as soon as the FETCH statement fails to return a row, the loop completes no matter how many times it has executed:
FOR j IN 1..10 LOOP
FETCH c1 INTO emp_rec;
EXIT WHEN c1%NOTFOUND;
END LOOP;
Suppose you must exit from a nested FOR loop prematurely. You can complete not only the current loop, but any enclosing loop. Simply label the enclosing loop that you want to complete. Then, use the label in an EXIT statement to specify which FOR loop to exit, as follows:
<<outer>>
FOR i IN 1..5 LOOP
FOR j IN 1..10 LOOP
FETCH c1 INTO emp_rec;
EXIT outer WHEN c1%NOTFOUND; -- exit both FOR loops
END LOOP;
END LOOP outer;
-- control passes here
Joel P�rez -
Hey,
Is there a limit on the number of characters in a select statement? I have a select statement that's nearly 2500 characters. I wonder if it is going to run.
TIAYes.
CREATE TABLE your_lookups AS
SELECT MAX(code) AS code,
MAX(value) AS value
FROM (
SELECT count(code) over (order by rnum) AS code_num,
v.*
FROM (
SELECT rownum AS rnum,
DECODE (MOD (ROWNUM, 2), 1, column_value) AS code,
DECODE (MOD (ROWNUM, 2), 0, column_value) AS VALUE
FROM TABLE (varchar2_array ('01', '01/19', '02', '02/20', '03', '03/21', '04', '04/22', '05', '05/23', '06', '06/24', '07', '07/25', '08', '08/26', '09', '09/27', '10', '10/28', '11', '11/29', '12', '12/30', '13', '13/31', '14', '14/32', '15', '15/33', '16', '16/34', '17', '17/35', '18', '18/36', '19', '19/01', '20', '20/02', '21', '21/03', '22', '22/04', '23', '23/05', '24', '24/06', '25', '25/07', '26', '26/08', '27', '27/09', '28', '28/10', '29', '29/11', '30', '30/12', '31', '31/13', '32', '32/14', '33', '33/15', '34', '34/16', '35', '35/17', '36', '36/18','01L', '01L/19R', '02L', '02L/20R', '03L', '03L/21R', '04L', '04L/22R', '05L', '05L/23R', '06L', '06L/24R', '07L', '07L/25R', '08L', '08L/26R', '09L', '09L/27R', '10L', '10L/28R', '11L', '11L/29R', '12L', '12L/30R', '13L', '13L/31R', '14L', '14L/32R', '15L', '15L/33R', '16L', '16L/34R', '17L', '17L/35R', '18L', '18L/36R', '19L', '19L/01R', '20L', '20L/02R', '21L', '21L/03R', '22L', '22L/04R', '23L', '23L/05R', '24L', '24L/06R', '25L', '25L/07R', '26L', '26L/08R', '27L', '27L/09R', '28L', '28L/10R', '29L', '29L/11R', '30L', '30L/12R', '31L', '31L/13R', '32L', '32L/14R', '33L', '33L/15R', '34L', '34L/16R', '35L', '35L/17R', '36L', '36L/18R','01R', '01R/19L', '02R', '02R/20L', '03R', '03R/21L', '04R', '04R/22L', '05R', '05R/23L', '06R', '06R/24L', '07R', '07R/25L', '08R', '08R/26L', '09R', '09R/27L', '10R', '10R/28L', '11R', '11R/29L', '12R', '12R/30L', '13R', '13R/31L', '14R', '14R/32L', '15R', '15R/33L', '16R', '16R/34L', '17R', '17R/35L', '18R', '18R/36L', '19R', '19R/01L', '20R', '20R/02L', '21R', '21R/03L', '22R', '22R/04L', '23R', '23R/05L', '24R', '24R/06L', '25R', '25R/07L', '26R', '26R/08L', '27R', '27R/09L', '28R', '28R/10L', '29R', '29R/11L', '30R', '30R/12L', '31R', '31R/13L', '32R', '32R/14L', '33R', '33R/15L', '34R', '34R/16L', '35R', '35R/17L', '36R', '36R/18L'))
) v
GROUP BY code_num;Message was edited by:
scott.swank -
Embedded select statements 8.04
this is a tricky one to explain, I have sql statements that were written in oracle 8i and works, unfortunately it is now being run on oracle 8.04 and fails, we have tested out that field names are correct, and that all the functions like decode, avg, stddev etc all existed in version 7.0 (the oldest manual we have).
The only message we are get using sql worksheet and having the sql statement in a text file, is missing expression after the third embedded sql statement (there is then another) so my first questions is does this older version of oracle have a limit on statement sizes, no of times sql select statements can be embedded. Any help would be greatly appreciated as though I know SQL i know little about Oracle.the code is roughly as follows(cut down a bit) , we cant use procedures, so have to send whole code through vb to oracle, using an account with read only access , where it says Select Sum (( sql worksheet reports an error of missing expression on this select:
SELECT 0 AS Record_Type_Id,
'INCLUDE' AS EXCLUDE_STATUS,
Chrt.Chart_Number,
Cpsl.scale,
Othv.Chart_Version,
Chrt.W_Dimension
FROM
Chart Chrt,
Other_Version Othv,
(( SELECT chart_number, scale
FROM chart_panel
WHERE UPPER(panel_main_title) = 'MAIN PANEL'
UNION
SELECT chart_number,
(SELECT SUM((
SELECT Decode(STDDEV(CpnI.SCALE),0, AVG(CpnI.scale) / count(CpnI.scale),0)
FROM Chart_Panel CpnI
WHERE CpnI.Chart_Number = CpnO.Chart_Number
GROUP BY CpnI.Chart_Number))/count(cpno.chart_number) as AVGScale
FROM Chart_panel CpnO
WHERE Cpno.chart_number = Cpn2.Chart_number
GROUP BY CpnO.chart_number) AS Scale
FROM chart_panel Cpn2
WHERE UPPER(panel_main_title) <> 'MAIN PANEL'
AND Cpn2.chart_number NOT IN (SELECT Chart_number
FROM Chart_panel
WHERE UPPER(Panel_main_title) = 'MAIN PANEL'))
UNION
SELECT
CHART_NUMBER AS Chart_Number, 0
FROM
CH[i]Long postings are being truncated to ~1 kB at this time.
Maybe you are looking for
-
Is there a version of iTunes that's compatible with XP Pro x64?
At this time I don't want to upgrade to Win 7 or go back to 32-bit XP, since iTunes is the only application I'm having trouble with and I like XP Pro x64 in all other ways. Is there either a version of iTunes that's compatible with XP Pro x64, or can
-
Dump while executing Standard FM VIEW_GET_DATA
hI , I want to execute standard function module VIEW_GET_DATA where i am passing view name as V_CURX after that we get around 63 records,but it comes in Hex format so i want to convert this data ... I have used FM HR_RU_CONVERT_HEX_TO_CP .. i have pu
-
Special GL indicator for customer vendor
HI SAP Experts, What is the T/code to create special GL indicator ( for advances ) I know obyr and obxr one more t/code is there that i forgotten , please help me. 2. My user created the GL accounts with out line item and he posted the line items int
-
11gR2 Error when installing a database and schema
I have install 11gR2 on my laptop with window 7 4gb ram 500gb hard drive I getting this error ORA-01503: CREATE Controlfile / Failed and ORA-01158: Database already mounted i need to set up a database a 3 different schema because i am doing a install
-
Hi, I have a Creative Nomad Jukebox Zen NX 30gb version .0.02. Is it possible to connect the player to any PC and automatically get the new hardware detected in the explorer eventhough the PC does not have Creative Mediasource installed? I now that w