10-15-2007 12:30 PM
Hai Senior's,
I'm in a beginning stage,can any one send me some select statements with explanation.
10-15-2007 12:36 PM
Basic format is:
SELECT select clause [INTO clause] FROM from clause [WHERE cond1] [GROUP BY fields1] [HAVING cond2] [ORDER BY fields2].
Note
The SELECT COUNT( * ) FROM ... statement returns a result table containing a single line with the result 0 if there are no records in the database table that meet the selection criteria.
<b>Example</b>
Displaying the passenger list for Lufthansa flight 0400 on 2/28/1995:
DATA: WA_SBOOK TYPE SBOOK.
SELECT * FROM SBOOK INTO WA_SBOOK
WHERE
CARRID = 'LH ' AND
CONNID = '0400' AND
FLDATE = '19950228'
ORDER BY PRIMARY KEY.
WRITE: / WA_SBOOK-BOOKID, WA_SBOOK-CUSTOMID,
WA_SBOOK-CUSTTYPE, WA_SBOOK-SMOKER,
WA_SBOOK-LUGGWEIGHT, WA_SBOOK-WUNIT,
WA_SBOOK-INVOICE.
ENDSELECT.
Hope this helps
Reward if helpful
10-15-2007 12:36 PM
Basic format is:
SELECT select clause [INTO clause] FROM from clause [WHERE cond1] [GROUP BY fields1] [HAVING cond2] [ORDER BY fields2].
Note
The SELECT COUNT( * ) FROM ... statement returns a result table containing a single line with the result 0 if there are no records in the database table that meet the selection criteria.
<b>Example</b>
Displaying the passenger list for Lufthansa flight 0400 on 2/28/1995:
DATA: WA_SBOOK TYPE SBOOK.
SELECT * FROM SBOOK INTO WA_SBOOK
WHERE
CARRID = 'LH ' AND
CONNID = '0400' AND
FLDATE = '19950228'
ORDER BY PRIMARY KEY.
WRITE: / WA_SBOOK-BOOKID, WA_SBOOK-CUSTOMID,
WA_SBOOK-CUSTTYPE, WA_SBOOK-SMOKER,
WA_SBOOK-LUGGWEIGHT, WA_SBOOK-WUNIT,
WA_SBOOK-INVOICE.
ENDSELECT.
Hope this helps
Reward if helpful
10-15-2007 12:38 PM
The best way to get it started in this is
IN SE38 write SELECT and place cursor on it and press F1..u ll get detailed help
10-15-2007 12:39 PM
Hi Saravana,
Some Variants of the SELECT statament.
. SELECT [SINGLE [FOR UPDATE] | DISTINCT] *
2. SELECT [SINGLE [FOR UPDATE] | DISTINCT] s1 ... sn
3. SELECT [SINGLE [FOR UPDATE] | DISTINCT] (source_text)
Effect
The result of a SELECT statement is itself a table. The SELECT clause, along with the database tables and/or viewsin the FROM clause, specifies the sequence, name, database type, and length of the columns of the result table.
You can also use the optional additions SINGLE or DISTINCT to indicate that only certain lines in the result set should be visible to the program:
SINGLE
The result of the selection should be a single entry. If it is not possible to identify a unique entry, the system uses the first line of the selection. If you use the FOR UPDATE addition, the selected entry is protected against parallel updates from other transactions until the next database commit (see LUW and database lock mechanism). If the database system identifies a deadlock, a runtime error occurs.
DISTINCT
Duplicate entries in the result set are automatically deleted.
Note
To ensure that an entry can be uniquely identified, you can specify all of the fields in the primary key using AND expressions in the WHERE condition.
Note
Performance:
The additions SINGLE FOR UPDATE and DISTINCT bypass the SAP buffering.
The addition DISTINCT forces a sort on the database server. You should therefore only use it if you are really expecting duplicates in the result set.
Variant 1
SELECT [SINGLE [FOR UPDATE] | DISTINCT] *
Effect
The columns of the result set will have exactly the same sequence, names, database type, and length as the fields of the database table or view specified in the FROM clause.
Examples
Example to display all flights from Frankfurt to New York:
DATA wa TYPE spfli.
SELECT * FROM spfli INTO wa
WHERE
cityfrom = 'FRANKFURT' AND
cityto = 'NEW YORK'.
WRITE: / wa-carrid, wa-connid.
ENDSELECT.
Example to display the free seats on Lufthansa flight 0400 on 02/28/2001:
DATA wa TYPE sflight.
DATA seatsfree TYPE I.
SELECT SINGLE * FROM sflight INTO wa
WHERE
carrid = 'LH ' AND
connid = '0400' AND
fldate = '20010228'.
FLDATE = '19950228'.
seatsfree = wa-seatsmax - wa-seatsocc.
WRITE: / wa-carrid, wa-connid, wa-fldate, seatsfree.
Note
If you specify more than one table in the FROM clause and the INTO clause contains an internal table or work area instead of a field list, the fields are placed into the target area from left to right in the order in which they occur in the tables in the FROM clause. Gaps may occur between the table work areas for the sake of alignment. For this reason, you should define the target work area by referring to the types of database tables instead of simply listing the fields. For an example, refer to the documentation of the FROM clause.
If the database table or the join specified in the FROM clause contain columns of the type STRING or RAWSTRING, you must not use the addition DISTINCT.
Variant 2
SELECT [SINGLE [FOR UPDATE] | DISTINCT] s1 ... sn
Effect
The columns of the result table will have the same format as the column references s1 ... sn.
If si stands for a field f, MAX( f ), MIN( f ), or SUM( f ), the corresponding column in the result set will have the same ABAP Dictionary format as f. For COUNT( DISTINCT f ) or COUNT( * ) the column has the type INT4. For AVG( f ) it has the type FLTP.
If you use aggregate functions with one or more database fields in the SELECT clause, you must include all of the database fields that are not used in the aggregate function in the GROUP BY clause. The result of the selection in this case is a table.
If the SELECT clause only contains aggregate functions, the result of the selection will be a single entry. In this case, SELECT does not have a corresponding ENDSELECT statement.
Examples
Example to display all destinations served by Lufthansa from Frankfurt:
DATA: target TYPE spfli-cityto.
SELECT DISTINCT cityto
INTO target FROM spfli
WHERE
carrid = 'LH ' AND
cityfrom = 'FRANKFURT'.
WRITE: / target.
ENDSELECT.
Example to display the number of airlines that fly to New York:
DATA count TYPE I.
SELECT COUNT( DISTINCT carrid )
INTO count
FROM spfli
WHERE
cityto = 'NEW YORK'.
WRITE: / count.
Example to find the number of passengers, the total luggage weight, and the average weight of the luggage for all Lufthansa flights on 02/28/2001:
DATA: count TYPE I, sum TYPE P DECIMALS 2, avg TYPE F,
connid LIKE sbook-connid.
SELECT connid COUNT( * ) SUM( luggweight ) AVG( luggweight )
INTO (connid, count, sum, avg)
FROM sbook
WHERE
carrid = 'LH ' AND
fldate = '20010228'
GROUP BY connid.
WRITE: / connid, count, sum, avg.
ENDSELECT.
Notes
This variant is only available for pool and cluster tables if the SELECT clause does not contain any other aggregate functions except COUNT( * ).
The addition FOR ALL ENTRIES excludes all aggregate functions in the SELECT clause. One exception is if COUNT( * ) is the only element of the SELECT clause.
If a database field of the type LCHAR or LRAW is specified in the SELECT clause, you must specify the associated length field directly before it in the SELECT clause.
If one of the database columns f1, ..., fn has the type STRING or RAWSTRING, you must not use the addition DISTINCT.
Notes
Performance:
If you use aggregate functions, the SAP buffering is bypassed.
Since certain database systems do not manage the number of lines in a table in their catalog and therefore must retrieve this number, the function COUNT( * ) is not suited to check whether a table contains lines at all. You should better use SELECT f ... FROM tab UP TO 1 ROWS for any table field f.
If you only want to select specific columns of a database table, you should specify a list of fields in the SELECT clause or use a view.
Variant 3
SELECT [SINGLE [FOR UPDATE] | DISTINCT] (source_text)
Effect
Works like SELECT [SINGLE [FOR UPDATE] | DISTINCT] s1 ... sn if the variable source_text contains the list s1 ... sn as source code (see Dynamic Source Code in Open SQL). If source_text is empty, the statement works like SELECT [SINGLE [FOR UPDATE] | DISTINCT] *.
Example
Example to display all Lufthansa routes:
DATA: wa TYPE spfli,
ftab TYPE TABLE OF STRING.
APPEND 'CITYFROM' TO ftab.
APPEND 'CITYTO' TO ftab.
SELECT DISTINCT (ftab)
FROM spfli
INTO CORRESPONDING FIELDS OF wa
WHERE
carrid = 'LH'.
WRITE: / wa-cityfrom, wa-cityto.
ENDSELECT.
Note
This variant is subject to the same restrictions as SELECT [SINGLE [FOR UPDATE] | DISTINCT] s1 ... sn.
Reward if Useful.
Regards,
Chitra
10-15-2007 1:10 PM
Hi
<b>Ways of Performance Tuning</b>
1. Selection Criteria
2. Select Statements
Select Queries
SQL Interface
Aggregate Functions
For all Entries
Select Over more than one Internal table
<b>
Selection Criteria</b>
1. Restrict the data to the selection criteria itself, rather than filtering it out using the ABAP code using CHECK statement.
2. Select with selection list.
<b>Points # 1/2</b>
SELECT * FROM SBOOK INTO SBOOK_WA.
CHECK: SBOOK_WA-CARRID = 'LH' AND
SBOOK_WA-CONNID = '0400'.
ENDSELECT.
The above code can be much more optimized by the code written below which avoids CHECK, selects with selection list
SELECT CARRID CONNID FLDATE BOOKID FROM SBOOK INTO TABLE T_SBOOK
WHERE SBOOK_WA-CARRID = 'LH' AND
SBOOK_WA-CONNID = '0400'.
<b>Select Statements Select Queries</b>
1. Avoid nested selects
2. Select all the records in a single shot using into table clause of select statement rather than to use Append statements.
3. When a base table has multiple indices, the where clause should be in the order of the index, either a primary or a secondary index.
4. For testing existence , use Select.. Up to 1 rows statement instead of a Select-Endselect-loop with an Exit.
5. Use Select Single if all primary key fields are supplied in the Where condition .
<b>Point # 1</b>
SELECT * FROM EKKO INTO EKKO_WA.
SELECT * FROM EKAN INTO EKAN_WA
WHERE EBELN = EKKO_WA-EBELN.
ENDSELECT.
ENDSELECT.
The above code can be much more optimized by the code written below.
SELECT PF1 PF2 FF3 FF4 INTO TABLE ITAB
FROM EKKO AS P INNER JOIN EKAN AS F
ON PEBELN = FEBELN.
Note: A simple SELECT loop is a single database access whose result is passed to the ABAP program line by line. Nested SELECT loops mean that the number of accesses in the inner loop is multiplied by the number of accesses in the outer loop. One should therefore use nested SELECT loops only if the selection in the outer loop contains very few lines or the outer loop is a SELECT SINGLE statement.
<b>Point # 2</b>
SELECT * FROM SBOOK INTO SBOOK_WA.
CHECK: SBOOK_WA-CARRID = 'LH' AND
SBOOK_WA-CONNID = '0400'.
ENDSELECT.
The above code can be much more optimized by the code written below which avoids CHECK, selects with selection list and puts the data in one shot using into table
SELECT CARRID CONNID FLDATE BOOKID FROM SBOOK INTO TABLE T_SBOOK
WHERE SBOOK_WA-CARRID = 'LH' AND
SBOOK_WA-CONNID = '0400'.
<b>Point # 3</b>
To choose an index, the optimizer checks the field names specified in the where clause and then uses an index that has the same order of the fields . In certain scenarios, it is advisable to check whether a new index can speed up the performance of a program. This will come handy in programs that access data from the finance tables.
<b>
Point # 4</b>
SELECT * FROM SBOOK INTO SBOOK_WA
UP TO 1 ROWS
WHERE CARRID = 'LH'.
ENDSELECT.
The above code is more optimized as compared to the code mentioned below for testing existence of a record.
SELECT * FROM SBOOK INTO SBOOK_WA
WHERE CARRID = 'LH'.
EXIT.
ENDSELECT.
<b>
Point # 5</b>
If all primary key fields are supplied in the Where condition you can even use Select Single.
Select Single requires one communication with the database system, whereas Select-Endselect needs two.
<b>Select Statements contd.. SQL Interface</b>
1. Use column updates instead of single-row updates
to update your database tables.
2. For all frequently used Select statements, try to use an index.
3. Using buffered tables improves the performance considerably.
<b>Point # 1</b>
SELECT * FROM SFLIGHT INTO SFLIGHT_WA.
SFLIGHT_WA-SEATSOCC =
SFLIGHT_WA-SEATSOCC - 1.
UPDATE SFLIGHT FROM SFLIGHT_WA.
ENDSELECT.
The above mentioned code can be more optimized by using the following code
UPDATE SFLIGHT
SET SEATSOCC = SEATSOCC - 1.
<b>Point # 2</b>
SELECT * FROM SBOOK CLIENT SPECIFIED INTO SBOOK_WA
WHERE CARRID = 'LH'
AND CONNID = '0400'.
ENDSELECT.
The above mentioned code can be more optimized by using the following code
SELECT * FROM SBOOK CLIENT SPECIFIED INTO SBOOK_WA
WHERE MANDT IN ( SELECT MANDT FROM T000 )
AND CARRID = 'LH'
AND CONNID = '0400'.
ENDSELECT.
<b>Point # 3</b>
Bypassing the buffer increases the network considerably
SELECT SINGLE * FROM T100 INTO T100_WA
BYPASSING BUFFER
WHERE SPRSL = 'D'
AND ARBGB = '00'
AND MSGNR = '999'.
The above mentioned code can be more optimized by using the following code
SELECT SINGLE * FROM T100 INTO T100_WA
WHERE SPRSL = 'D'
AND ARBGB = '00'
AND MSGNR = '999'.
<b>Select Statements contd Aggregate Functions</b>
If you want to find the maximum, minimum, sum and average value or the count of a database column, use a select list with aggregate functions instead of computing the aggregates yourself.
Some of the Aggregate functions allowed in SAP are MAX, MIN, AVG, SUM, COUNT, COUNT( * )
Consider the following extract.
Maxno = 0.
Select * from zflight where airln = LF and cntry = IN.
Check zflight-fligh > maxno.
Maxno = zflight-fligh.
Endselect.
The above mentioned code can be much more optimized by using the following code.
Select max( fligh ) from zflight into maxno where airln = LF and cntry = IN.
<b>
Select Statements contd For All Entries</b>
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)
<u>Points to be must considered FOR ALL ENTRIES</u>
Check that data is present in the driver table
Sorting the driver table
Removing duplicates from the driver table
Consider the following piece of extract
Loop at int_cntry.
Select single * from zfligh into int_fligh
where cntry = int_cntry-cntry.
Append int_fligh.
Endloop.
The above mentioned can be more optimized by using the following code.
Sort int_cntry by cntry.
Delete adjacent duplicates from int_cntry.
If NOT int_cntry[] is INITIAL.
Select * from zfligh appending table int_fligh
For all entries in int_cntry
Where cntry = int_cntry-cntry.
Endif.
<b>Select Statements contd Select Over more than one Internal table</b>
1. Its better to use a views instead of nested Select statements.
2. To read data from several logically connected tables use a join instead of nested Select statements. Joins are preferred only if all the primary key are available in WHERE clause for the tables that are joined. If the primary keys are not provided in join the Joining of tables itself takes time.
3. Instead of using nested Select loops it is often better to use subqueries.
<b>Point # 1</b>
SELECT * FROM DD01L INTO DD01L_WA
WHERE DOMNAME LIKE 'CHAR%'
AND AS4LOCAL = 'A'.
SELECT SINGLE * FROM DD01T INTO DD01T_WA
WHERE DOMNAME = DD01L_WA-DOMNAME
AND AS4LOCAL = 'A'
AND AS4VERS = DD01L_WA-AS4VERS
AND DDLANGUAGE = SY-LANGU.
ENDSELECT.
The above code can be more optimized by extracting all the data from view DD01V_WA
SELECT * FROM DD01V INTO DD01V_WA
WHERE DOMNAME LIKE 'CHAR%'
AND DDLANGUAGE = SY-LANGU.
ENDSELECT
<b>Point # 2</b>
SELECT * FROM EKKO INTO EKKO_WA.
SELECT * FROM EKAN INTO EKAN_WA
WHERE EBELN = EKKO_WA-EBELN.
ENDSELECT.
ENDSELECT.
The above code can be much more optimized by the code written below.
SELECT PF1 PF2 FF3 FF4 INTO TABLE ITAB
FROM EKKO AS P INNER JOIN EKAN AS F
ON PEBELN = FEBELN.
<b>Point # 3</b>
SELECT * FROM SPFLI
INTO TABLE T_SPFLI
WHERE CITYFROM = 'FRANKFURT'
AND CITYTO = 'NEW YORK'.
SELECT * FROM SFLIGHT AS F
INTO SFLIGHT_WA
FOR ALL ENTRIES IN T_SPFLI
WHERE SEATSOCC < F~SEATSMAX
AND CARRID = T_SPFLI-CARRID
AND CONNID = T_SPFLI-CONNID
AND FLDATE BETWEEN '19990101' AND '19990331'.
ENDSELECT.
The above mentioned code can be even more optimized by using subqueries instead of for all entries.
SELECT * FROM SFLIGHT AS F INTO SFLIGHT_WA
WHERE SEATSOCC < F~SEATSMAX
AND EXISTS ( SELECT * FROM SPFLI
WHERE CARRID = F~CARRID
AND CONNID = F~CONNID
AND CITYFROM = 'FRANKFURT'
AND CITYTO = 'NEW YORK' )
AND FLDATE BETWEEN '19990101' AND '19990331'.
ENDSELECT.
1. Table operations should be done using explicit work areas rather than via header lines.
2. Always try to use binary search instead of linear search. But dont forget to sort your internal table before that.
3. A dynamic key access is slower than a static one, since the key specification must be evaluated at runtime.
4. A binary search using secondary index takes considerably less time.
5. LOOP ... WHERE is faster than LOOP/CHECK because LOOP ... WHERE evaluates the specified condition internally.
6. Modifying selected components using MODIFY itab TRANSPORTING f1 f2.. accelerates the task of updating a line of an internal table.
<b>Point # 2</b>
READ TABLE ITAB INTO WA WITH KEY K = 'X BINARY SEARCH.
IS MUCH FASTER THAN USING
READ TABLE ITAB INTO WA WITH KEY K = 'X'.
If TAB has n entries, linear search runs in O( n ) time, whereas binary search takes only O( log2( n ) ).
<b>Point # 3</b>
READ TABLE ITAB INTO WA WITH KEY K = 'X'. IS FASTER THAN USING
READ TABLE ITAB INTO WA WITH KEY (NAME) = 'X'.
<b>Point # 5</b>
LOOP AT ITAB INTO WA WHERE K = 'X'.
" ...
ENDLOOP.
The above code is much faster than using
LOOP AT ITAB INTO WA.
CHECK WA-K = 'X'.
" ...
ENDLOOP.
<b>Point # 6</b>
WA-DATE = SY-DATUM.
MODIFY ITAB FROM WA INDEX 1 TRANSPORTING DATE.
The above code is more optimized as compared to
WA-DATE = SY-DATUM.
MODIFY ITAB FROM WA INDEX 1.
7. Accessing the table entries directly in a "LOOP ... ASSIGNING ..." accelerates the task of updating a set of lines of an internal table considerably
8. If collect semantics is required, it is always better to use to COLLECT rather than READ BINARY and then ADD.
9. "APPEND LINES OF itab1 TO itab2" accelerates the task of appending a table to another table considerably as compared to LOOP-APPEND-ENDLOOP.
10. DELETE ADJACENT DUPLICATES accelerates the task of deleting duplicate entries considerably as compared to READ-LOOP-DELETE-ENDLOOP.
11. "DELETE itab FROM ... TO ..." accelerates the task of deleting a sequence of lines considerably as compared to DO -DELETE-ENDDO.
<b>Point # 7</b>
Modifying selected components only makes the program faster as compared to Modifying all lines completely.
e.g,
LOOP AT ITAB ASSIGNING <WA>.
I = SY-TABIX MOD 2.
IF I = 0.
<WA>-FLAG = 'X'.
ENDIF.
ENDLOOP.
The above code works faster as compared to
LOOP AT ITAB INTO WA.
I = SY-TABIX MOD 2.
IF I = 0.
WA-FLAG = 'X'.
MODIFY ITAB FROM WA.
ENDIF.
ENDLOOP.
<b>Point # 8</b>
LOOP AT ITAB1 INTO WA1.
READ TABLE ITAB2 INTO WA2 WITH KEY K = WA1-K BINARY SEARCH.
IF SY-SUBRC = 0.
ADD: WA1-VAL1 TO WA2-VAL1,
WA1-VAL2 TO WA2-VAL2.
MODIFY ITAB2 FROM WA2 INDEX SY-TABIX TRANSPORTING VAL1 VAL2.
ELSE.
INSERT WA1 INTO ITAB2 INDEX SY-TABIX.
ENDIF.
ENDLOOP.
The above code uses BINARY SEARCH for collect semantics. READ BINARY runs in O( log2(n) ) time. The above piece of code can be more optimized by
LOOP AT ITAB1 INTO WA.
COLLECT WA INTO ITAB2.
ENDLOOP.
SORT ITAB2 BY K.
COLLECT, however, uses a hash algorithm and is therefore independent
of the number of entries (i.e. O(1)) .
<b>Point # 9</b>
APPEND LINES OF ITAB1 TO ITAB2.
This is more optimized as compared to
LOOP AT ITAB1 INTO WA.
APPEND WA TO ITAB2.
ENDLOOP.
<b>Point # 10</b>
DELETE ADJACENT DUPLICATES FROM ITAB COMPARING K.
This is much more optimized as compared to
READ TABLE ITAB INDEX 1 INTO PREV_LINE.
LOOP AT ITAB FROM 2 INTO WA.
IF WA = PREV_LINE.
DELETE ITAB.
ELSE.
PREV_LINE = WA.
ENDIF.
ENDLOOP.
<b>Point # 11</b>
DELETE ITAB FROM 450 TO 550.
This is much more optimized as compared to
DO 101 TIMES.
DELETE ITAB INDEX 450.
ENDDO.
12. Copying internal tables by using ITAB2[ ] = ITAB1[ ] as compared to LOOP-APPEND-ENDLOOP.
13. Specify the sort key as restrictively as possible to run the program faster.
<b>Point # 12</b>
ITAB2[] = ITAB1[].
This is much more optimized as compared to
REFRESH ITAB2.
LOOP AT ITAB1 INTO WA.
APPEND WA TO ITAB2.
ENDLOOP.
<b>Point # 13</b>
SORT ITAB BY K. makes the program runs faster as compared to SORT ITAB.
<b>Internal Tables contd
Hashed and Sorted tables</b>
1. For single read access hashed tables are more optimized as compared to sorted tables.
2. For partial sequential access sorted tables are more optimized as compared to hashed tables
Hashed And Sorted Tables
<b>Point # 1</b>
Consider the following example where HTAB is a hashed table and STAB is a sorted table
DO 250 TIMES.
N = 4 * SY-INDEX.
READ TABLE HTAB INTO WA WITH TABLE KEY K = N.
IF SY-SUBRC = 0.
" ...
ENDIF.
ENDDO.
This runs faster for single read access as compared to the following same code for sorted table
DO 250 TIMES.
N = 4 * SY-INDEX.
READ TABLE STAB INTO WA WITH TABLE KEY K = N.
IF SY-SUBRC = 0.
" ...
ENDIF.
ENDDO.
<b>Point # 2</b>
Similarly for Partial Sequential access the STAB runs faster as compared to HTAB
LOOP AT STAB INTO WA WHERE K = SUBKEY.
" ...
ENDLOOP.
This runs faster as compared to
LOOP AT HTAB INTO WA WHERE K = SUBKEY.
" ...
ENDLOOP.
<b>Reward if usefull</b>