ABAP SQL: Reading Data
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Business data lives in database tables, and nearly every ABAP program starts by reading some of it. ABAP SQL is the part
of the ABAP language that does this: you describe which columns and which rows you want, and the system fetches them from
the database and puts them into variables of your program. This page teaches the reading statement, SELECT. After it you
can read a list of rows into an internal table, filter and sort them in the database, read a single row, count and add up
values, and avoid the habits that make programs slow.
It is written against Standard ABAP release 8.16 and ABAP for Cloud Development release 9.20 (2608). SELECT and its
additions work in ABAP Cloud and in classic, Standard ABAP (on premise and in the Public Edition). Two differences are
called out where they matter: in ABAP Cloud you may read only released objects, and you can read only the data of your own
client.
Before you read
-
Data Types and Data Objects: variables, structures, internal tables and inline declarations.
-
Internal Tables: the result of most reads is an internal table.
Key terms
-
ABAP SQL: the ABAP statements that read and change database tables.
-
Host variable: an ABAP variable used inside an ABAP SQL statement, always written with a leading
@. -
ABAP Dictionary: the repository that defines database tables, their columns and their types.
-
Internal table: a list of rows that lives in the memory of the running program and receives the result of a read.
-
Inline declaration: a variable declared at the place where it is first filled, such as
@DATA(claims). -
Client: a self-contained unit of business data inside one SAP system; ABAP SQL reads only the client you are logged on to.
-
System field: a read-only variable filled by the runtime, such as
sy-subrc.
The running example
The examples read from a table named ZEXP_CLAIM, one row per expense claim. In the playground of this documentation the
table has three columns: CLAIM_ID (the key, ten characters), STATUS (one character: A approved, S submitted, R
rejected) and AMOUNT (a whole number). A real claim table has many more columns, and a client column, which ABAP SQL
hides from you (see Client handling below). The five rows used on this page are:
| CLAIM_ID | STATUS | AMOUNT |
|---|---|---|
C000000001 |
A |
120 |
C000000002 |
S |
35 |
C000000003 |
A |
80 |
C000000004 |
R |
10 |
C000000005 |
S |
64 |
Listings marked as running in the local playground were run on the lab of this documentation set (Node.js, an in-memory
SQLite database) with those five rows inserted first. The playground prints the fields of a line without spaces between
them, so claim 1 appears as C000000001A120. The lab lacks some statements (SQL aggregates other than COUNT, the
GROUP BY clause, sy-dbcnt); those listings are labelled "requires an SAP system; not run here".
How a SELECT works
host variables with @] --> B[ABAP SQL interface] B -->|adds the client condition,
translates to database SQL| C[(Database table)] C -->|rows that match the WHERE condition| B B -->|result set| D[INTO target:
internal table, work area
or variables] D --> E[sy-subrc: 0 rows found, 4 nothing found]
The statement is not run by the ABAP program itself. The program passes it to the ABAP SQL interface, which turns it into
the SQL of the actual database, adds the condition for the current client, lets the database do the filtering and
sorting, and hands the rows back to the variables named in the INTO clause. Doing the work in the database means that
only the rows and columns you asked for travel to the application server; this is the main rule of the Keyword
Documentation’s performance notes.
Reading a table into an internal table
The standard form reads all matching rows in one step into an internal table. A host variable is an ABAP variable used
inside an SQL statement; the escape character @ in front of it tells the system that this name is a variable of your
program and not a column. Lists, such as the columns after SELECT, are separated by commas. This is the "strict" syntax
that ABAP Cloud requires and that new code in classic ABAP should use too.
SELECT claim_id, status, amount
FROM zexp_claim
ORDER BY claim_id
INTO TABLE @DATA(claims).
LOOP AT claims INTO DATA(claim).
WRITE: / claim-claim_id, claim-status, claim-amount.
ENDLOOP.
This listing runs in the local playground. It prints the five rows in the order of the claim number, the first one as
C000000001A120 and the last as C000000005S64.
The pieces, in the order the statement is written:
-
SELECTis followed by the columns you want (the field list). -
FROMnames the database table, or a CDS view in ABAP Cloud. -
WHERE,GROUP BY,HAVINGandORDER BYfollow, each optional. -
INTO TABLE @DATA(claims)is the target.@DATA(claims)declares the internal table at this very place with the row type of the field list. A table declared beforehand is writtenINTO TABLE @claims.INTO @DATA(row)orINTO @rowwithoutTABLEreads a work area, andINTO ( @a, @b )fills separate variables. -
The Keyword Documentation requires the
INTOclause to be the last clause of a standaloneSELECT; the optional additionsUP TO,OFFSETandOPTIONSstand behind it.
The result is an internal table, so everything on the page Internal Tables applies to it. If the result is empty the
statement sets the system field sy-subrc to 4, and to 0 when at least one row was passed; it also sets sy-dbcnt.
Older books show the same statement without @ and without commas, SELECT * FROM zexp_claim INTO CORRESPONDING FIELDS OF TABLE claims: that older form is still accepted in classic, non-strict code but is not allowed in ABAP Cloud, and
you should not copy it into new programs.
Choosing columns: field lists and SELECT *
A field list names the columns you need, SELECT claim_id, amount. The shortcut SELECT * returns every column. Use
it only when you really need the whole row, for example as the target of a work area of the table’s own type: the
performance notes in the Keyword Documentation say to keep the data volume low and restrict the columns to those
required, because every extra column is transported from the database server to the application server for every row. A
long table with dozens of columns is the usual case where SELECT * hurts.
Columns can be renamed with AS: SELECT amount AS claim_amount .... The names after AS become the component names of
the result rows. Source: ABAP Keyword Documentation: SELECT, select_clause
Filtering rows with WHERE
WHERE keeps a row only if its logical condition is true. The comparison is done in the database, before any row is
transported. Host variables supply the values, so a program can change the filter without changing the statement.
DATA(min_amount) = 50.
DATA(wanted_status) = 'A'.
SELECT claim_id, amount
FROM zexp_claim
WHERE amount >= @min_amount AND status = @wanted_status
ORDER BY amount DESCENDING
INTO TABLE @DATA(big).
This listing runs in the local playground (with the loop of the first listing to print big). It prints
C000000001120 and C00000000380: the two approved claims of at least 50, the larger first.
The condition language is the same one used elsewhere in ABAP SQL. The cheat sheet on WHERE conditions lists it:
-
comparisons
=,<>,<,>,<=,>=(the letter formsEQ,NE,LT,GT,LE,GEmean the same); -
AND,ORandNOT, with parentheses to group; -
BETWEEN a AND b(both ends are included) andIN ( 'x', 'y' )for a list of values; -
LIKEwith the wildcards%(any text) and_(one character), andESCAPEto search for a literal%or_; -
IS NULL,IS INITIAL, a subquery withINorEXISTS, andIN @rangefor a ranges table.
SELECT claim_id
FROM zexp_claim
WHERE status IN ( 'S', 'R' )
AND amount BETWEEN 10 AND 40
AND claim_id LIKE 'C00000000%'
ORDER BY claim_id
INTO TABLE @DATA(c_ids).
This listing runs in the local playground and returns C000000002 (a submitted claim of 35) and C000000004 (a rejected
claim of 10).
Two rules are worth knowing early. Columns of the types STRING and RAWSTRING cannot be used in a WHERE condition. And
the client column of a table cannot be used there either: the system adds it for you.
Sorting and limiting: ORDER BY, UP TO and OFFSET
Without ORDER BY the order of the result rows is undefined and can differ between two runs of the same statement, so
never rely on the order the database happens to return. ORDER BY col [ASCENDING|DESCENDING] sorts in the database, and
ORDER BY PRIMARY KEY sorts by the key columns. UP TO n ROWS limits the number of rows, and OFFSET skips rows, but
OFFSET works only together with ORDER BY. With INTO last, the clause is written after it.
SELECT claim_id
FROM zexp_claim
ORDER BY amount DESCENDING
INTO TABLE @DATA(top2)
UP TO 2 ROWS.
This listing runs in the local playground and returns the two largest claims, C000000001 (120) and C000000003 (80).
The Keyword Documentation says that UP TO n ROWS is preferable to a SELECT loop that you leave after n rows, because
the last package of rows passed from the database to the application server then contains superfluous rows. Note that
UP TO 0 ROWS does not mean no rows: with 0 the maximum number, 2,147,483,647 rows, is read.
Reading one row: SELECT SINGLE
SELECT SINGLE reads at most one row into a work area, so there is no internal table and no loop. Use it when the
WHERE condition names the whole primary key, such as one claim by its number. If the condition fits several rows,
which one you receive is not something to rely on.
SELECT SINGLE claim_id, amount
FROM zexp_claim
WHERE claim_id = 'C000000003'
INTO @DATA(one).
WRITE: / sy-subrc, one-claim_id, one-amount.
SELECT SINGLE claim_id
FROM zexp_claim
WHERE claim_id = 'NOPE'
INTO @DATA(none).
WRITE: / sy-subrc.
This listing runs in the local playground. The first WRITE prints 0C00000000380 (found, claim 3, amount 80) and the
second prints 4 (nothing found). Always test sy-subrc before using the result: when nothing is found the target
variable is not filled.
Counting, adding up and grouping: aggregates
An aggregate expression combines the values of many rows into one value: COUNT( * ) counts rows, and SUM, AVG, MIN
and MAX add up, average and find the smallest and largest value of a column. DISTINCT removes duplicate rows, and
GROUP BY forms one result row per group. Doing this in the database is far cheaper than reading all rows and adding
them in a loop, because only the aggregated rows travel.
SELECT COUNT( * ) FROM zexp_claim INTO @DATA(cnt).
SELECT DISTINCT status FROM zexp_claim ORDER BY status INTO TABLE @DATA(st).
This listing runs in the local playground. cnt is 5, and st holds the three values A, R and S.
A total per status needs GROUP BY. Every column in the field list that is not an aggregate must also appear after
GROUP BY, and HAVING filters the groups after they are formed:
SELECT status,
COUNT( * ) AS claims,
SUM( amount ) AS total
FROM zexp_claim
GROUP BY status
HAVING SUM( amount ) > 50
ORDER BY status
INTO TABLE @DATA(per_status).
Requires an SAP system; not run here (the playground has no GROUP BY, SUM or HAVING). On the five rows of this page
a real system returns A with 2 claims and a total of 200, and S with 2 claims and a total of 99; R is dropped by
the HAVING condition because its total is 10.
Reading with a list of keys: FOR ALL ENTRIES
Sometimes the keys you want are already in an internal table, for example the claim numbers a user ticked in a screen.
FOR ALL ENTRIES IN @itab runs the WHERE condition once for each row of that table and returns the union of the
results. Inside the condition you compare a column with a component of the table: WHERE claim_id = @wanted-claim_id.
DATA(wanted) = VALUE ty_claims( ( claim_id = 'C000000002' ) ( claim_id = 'C000000004' ) ).
DATA fae TYPE ty_claims.
SELECT claim_id, amount
FROM zexp_claim
FOR ALL ENTRIES IN @wanted
WHERE claim_id = @wanted-claim_id
INTO TABLE @fae.
This listing runs in the local playground, with the type ty_claims of ZEXP_CLAIM rows declared above it
(TYPES ty_claims TYPE STANDARD TABLE OF zexp_claim WITH EMPTY KEY). It returns claims 2 and 4 with the amounts 35 and
10. The target is a table declared beforehand: the playground does not accept an inline declaration here.
The addition has traps that the Keyword Documentation spells out:
-
An empty table returns every row. If the internal table after
FOR ALL ENTRIESis empty, the entireWHEREcondition is ignored, and the result is the whole database table. The playground shows the same: with an emptywantedtable the statement above returned all 5 rows. Always check that the table has rows before the statement, withIF wanted IS NOT INITIAL. -
Duplicate rows are removed from the result, and the whole row is compared.
-
It cannot be combined with
SINGLE, withUNION, with path expressions, or with SQL expressions other than single columns andCOUNT( * );GROUP BYhas no effect with it, andORDER BYis limited toPRIMARY KEY. -
The cheat sheet on ABAP SQL calls the addition deprecated and recommends an explicit emptiness check before the statement or, better, an inner join with the internal table. Joins and
SELECT FROM @itabare taught on the next ABAP SQL page.
Source: ABAP cheat sheet: ABAP SQL
Client handling
Many SAP tables hold the data of several clients in one table, each row marked by a client column (usually named MANDT
or CLIENT). The aim is that a logged-on user sees only the rows of the client chosen at logon. ABAP SQL does this for
you, which is called implicit client handling: the statement that goes to the database carries an extra condition on the
client column, joins between client-dependent tables add a client equality, and write statements fill the client column
with the current client. The client number is in the system field sy-mandt.
Two consequences follow. You cannot write the client column in a WHERE condition: the Keyword Documentation states that
it cannot be evaluated in the conditions of queries. And you never filter by client yourself, so the result of a
SELECT never mixes in other clients' data. In ABAP Cloud, where you are limited to your own client, there is nothing
more to do. In classic ABAP the addition USING CLIENT can switch to another client, and the old CLIENT SPECIFIED
is obsolete; the cheat sheet says only USING CLIENT should be used. Native SQL and AMDP (a later page) have no implicit
client handling, so there the client must be passed explicitly.
Why SELECT loops and SELECT * are discouraged
A SELECT into a work area without TABLE and without SINGLE opens a loop that must be closed with ENDSELECT, and the
same happens with INTO TABLE ... PACKAGE SIZE. The body runs once for each row or package. The program on the playground
below reads claim by claim.
DATA row TYPE zexp_claim.
SELECT * FROM zexp_claim ORDER BY claim_id INTO @row.
WRITE: / row-claim_id, row-status, row-amount.
ENDSELECT.
This listing runs in the local playground and prints the five claims one per line, like the first listing. The loop works but you should write the first form instead, for these reasons from the Keyword Documentation:
-
The loop keeps a database cursor open until it ends, and a program can have at most 17 cursors open at the same time; more raises the runtime error
DBSQL_TOO_MANY_OPEN_CURSOR. -
Database reads inside a loop body, for example another
SELECTper row, multiply the number of reads. The performance notes tell you to keep the number of reads low: use mass operations, joins or subqueries, and never ABAP SQL statements inside loops. -
Leaving the loop early with
EXITafter n rows wastes the rows of the last package;UP TO n ROWSis better. -
Reading all columns with
SELECT *transports data the program never uses.
A reasonable rule: read once into an internal table with only the columns you need and with the filter in WHERE, then
loop over the internal table in ABAP. A SELECT loop is acceptable when the result is too large to hold in memory and you
process it package by package with PACKAGE SIZE.
Putting it together: read claims with host variables
The program below is the whole running example: select the submitted claims of at least 20, largest first, using two host variables, and report when nothing matches.
REPORT zexp_read_claims.
DATA(wanted_status) = 'S'.
DATA(min_amount) = 20.
SELECT claim_id, status, amount
FROM zexp_claim
WHERE status = @wanted_status
AND amount >= @min_amount
ORDER BY amount DESCENDING
INTO TABLE @DATA(claims).
IF sy-subrc <> 0.
WRITE / 'No claim found'.
ELSE.
LOOP AT claims INTO DATA(claim).
WRITE: / claim-claim_id, claim-amount.
ENDLOOP.
ENDIF.
This listing runs in the local playground. It prints C00000000564 and C00000000235. After the statement is changed to
wanted_status = 'X', which no claim has, sy-subrc is 4 and the internal table is empty, so the program prints the
message.
Summary
-
SELECT ... INTO TABLE @DATA(itab)reads all matching rows in one step; host variables carry a leading@, lists use commas andINTOcomes last. -
Name the columns you need, filter with
WHERE, sort withORDER BYand limit withUP TO n ROWS: the database does the work and fewer data travel. -
SELECT SINGLEreads one row;sy-subrcis 0 when a row was found and 4 when not, and must be tested. -
Aggregates,
DISTINCTandGROUP BYsummarise in the database;FOR ALL ENTRIESwith an empty table returns the whole table, so test the table first. -
Client handling is implicit: you never write the client column, and ABAP Cloud reads only your own client.
-
Prefer one read into an internal table over
SELECT ... ENDSELECTloops andSELECT *.
Try it
To do this by hand, follow the guide ABAP SQL on a Local Database: it reads and changes data with ABAP SQL on a local database.