ABAP SQL: Joins, CTEs, Window Functions and Path Expressions
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A simple SELECT reads rows from one table. Real questions need more: "which items belong to which claim", "which claims
have no items at all", "what is the biggest claim of each cost centre". ABAP SQL answers these inside the database, so
that only the finished result travels to the program. This page explains four tools for that: joins, which put the rows
of two data sources side by side; common table expressions, which name an intermediate result so a query can build on
it; window expressions, which add a ranking or a running figure to every row without collapsing the rows; and path
expressions, which follow a link that a CDS view declares instead of writing the join by hand. It ends with a short
look at hierarchies such as a tree of cost centres. The statements are written against Standard ABAP release 8.16 and
ABAP for Cloud Development release 9.20 (2608). They belong to ABAP SQL, so they are the same in classic Standard ABAP,
on premise, in the Public Edition and in ABAP Cloud, with two limits: a path expression needs a CDS association, and
hierarchy data is, according to the Keyword Documentation, not supported by all databases (on SAP HANA it is).
Most listings below need an SAP system with the ABAP Dictionary or CDS and are labelled that way; only the join listing
runs in the local playground.
Before you read
-
Data Types and Data Objects: inline declarations such as
DATA(rows)and the types of result columns. -
Internal Tables: every query below puts its result into an internal table.
-
Constructor Expressions:
VALUEfills tables in the join listing. -
The basic
SELECTstatement (field list,WHERE,ORDER BY, host variables with@, aggregates) is covered by the ABAP SQL page on reading data that comes before this one in the section; this page assumes you have seen it.
Key terms
-
Join: a query that combines the rows of two data sources whose columns match a condition.
-
Outer join: a join that keeps the rows of one side even when nothing on the other side matches.
-
Common table expression: a named intermediate result, defined with
WITH, that exists only during one statement. -
Window expression: a function followed by
OVERthat computes a value for each row from a group of related rows, without merging the rows. -
CDS association: a named link from one CDS entity to another, declared once in the CDS view.
-
Path expression: a way to reach columns of an associated entity by naming the association, which ABAP turns into a join.
-
Hierarchy: data where each row can have one parent row, such as a tree of cost centres.
The running example
The examples use the Expense claims data of this section. A claim has a claim number, a cost centre, a status and an
amount; its items (travel, meals, …) are rows of a second table with the claim number, an item number, a category and
an amount. In the listings the Dictionary tables are called zexp_claim and zexp_item. Their field names are in
lower case in ABAP and in upper case in the database.
Joins: rows from two tables side by side
A join answers "give me, for each claim, its items". You name the first data source after FROM, add a join to the
second one and say with ON which columns must match. The result has one row for every pair of rows that match.
-
An inner join (
INNER JOIN) keeps only the pairs that match. A claim without items does not appear. -
A left outer join (
LEFT OUTER JOIN) keeps every row of the left source. Where the right side has no match, the columns of the right side are filled with the null value.RIGHT OUTER JOINis the mirror image.
In the result, ABAP converts the null value to the initial value of the target column when it is passed to the
internal table, so a missing item shows as 0 or an empty string. If you must tell "no item" from "item with amount
0", test the right-hand column with IS NULL in the query.
The following report writes three claims and three items into the local tables, then runs one inner and one left outer join. It runs in the local playground (the lab of this section), because inner and left outer joins on two tables are among the statements the lab supports. Claim C-1003 has no item, so the two joins differ in exactly that row. The output shown is the real output of the lab.
REPORT zjoin.
TYPES ty_claims TYPE STANDARD TABLE OF zexp_claim WITH EMPTY KEY.
TYPES ty_items TYPE STANDARD TABLE OF zexp_item WITH EMPTY KEY.
INSERT zexp_claim FROM TABLE @( VALUE ty_claims( ( claim_id = 'C-1001' status = 'S' amount = 155 )
( claim_id = 'C-1002' status = 'A' amount = 80 )
( claim_id = 'C-1003' status = 'S' amount = 20 ) ) ).
INSERT zexp_item FROM TABLE @( VALUE ty_items( ( claim_id = 'C-1001' item_no = 1 category = 'TRAVEL' amount = 120 )
( claim_id = 'C-1001' item_no = 2 category = 'MEALS' amount = 35 )
( claim_id = 'C-1002' item_no = 1 category = 'TRAVEL' amount = 80 ) ) ).
WRITE / 'inner join'.
SELECT c~claim_id, i~item_no, i~category
FROM zexp_claim AS c
INNER JOIN zexp_item AS i ON i~claim_id = c~claim_id
ORDER BY c~claim_id, i~item_no
INTO TABLE @DATA(inner_rows).
LOOP AT inner_rows INTO DATA(r1).
WRITE / |{ r1-claim_id } { r1-item_no } { r1-category }|.
ENDLOOP.
WRITE / 'left outer join'.
SELECT c~claim_id, i~item_no, i~category
FROM zexp_claim AS c
LEFT OUTER JOIN zexp_item AS i ON i~claim_id = c~claim_id
ORDER BY c~claim_id, i~item_no
INTO TABLE @DATA(outer_rows).
LOOP AT outer_rows INTO DATA(r2).
WRITE / |{ r2-claim_id } [{ r2-item_no }] [{ r2-category }]|.
ENDLOOP.
Output of the lab:
inner join C-1001 1 TRAVEL C-1001 2 MEALS C-1002 1 TRAVEL left outer join C-1001 [1] [TRAVEL] C-1001 [2] [MEALS] C-1002 [1] [TRAVEL] C-1003 [0] []
Source: ABAP Keyword Documentation: SELECT, FROM JOIN; the null behaviour is described in the ABAP cheat sheet: ABAP SQL
Write the column list with commas and host variables with @, as above. Older ABAP code lists fields without commas and
host variables without @; classic programs still run that way, but the strict form shown here is the one new code
uses and the one ABAP Cloud requires. Books and tutorials written for ABAP 7.4 show the older form and do not cover the
window expressions, path expressions and hierarchies below, so check the release of your system before copying from
them.
UNION: stacking result sets
A join puts columns side by side. UNION stacks rows: the rows of the second query are added to the result of the
first, and duplicates are removed (the default is DISTINCT; UNION ALL keeps them). Both queries must produce columns of matching types, and a single INTO after the
last query receives the combined result. INTERSECT keeps only the rows both queries produce, and EXCEPT keeps the
rows of the first query that the second does not produce. All three also work between common table expressions, below.
This example lists the claim numbers that are submitted or above 50 in amount, each claim once. It requires an SAP system; not run here.
SELECT FROM zexp_claim
FIELDS claim_id
WHERE status = 'S'
UNION
SELECT FROM zexp_claim
FIELDS claim_id
WHERE amount > 50
INTO TABLE @DATA(claim_ids).
Common table expressions with WITH
Some questions need an intermediate result: first the total per cost centre, then a ranking of those totals. ABAP SQL does not let you select from a subquery directly. A common table expression (CTE) fills that gap. You give a subquery a name, and later queries of the same statement use the name like a table. A CTE is a temporary view: it exists only while the statement runs.
The rules of the WITH statement, as the Keyword Documentation states them:
-
WITHstarts the statement. After it come one or more CTE definitions separated by commas, then one closing main query withSELECT. -
The name of a CTE starts with a plus sign, for example
+totals; it has at most 30 characters. -
An optional list of column names in parentheses after the name gives the result columns their names.
-
A CTE can use CTEs defined before it, but not itself and not later ones. Every CTE must be used at least once, and the main query must use at least one.
-
A CTE result has no client column, even when its source table has one.
-
When the main query writes into a work area and so opens a loop,
ENDWITH.closes it, likeENDSELECT.
The example below first sums the claims per cost centre in the CTE and then ranks the cost centres by that total in the main query. It requires an SAP system; not run here.
WITH
+totals( cost_center, total ) AS (
SELECT cost_center, SUM( amount )
FROM zexp_claim
GROUP BY cost_center )
SELECT cost_center,
total,
RANK( ) OVER( ORDER BY total DESCENDING ) AS position
FROM +totals
ORDER BY position
INTO TABLE @DATA(cost_center_ranking).
Source: ABAP Keyword Documentation: WITH; background in ABAP Keyword Documentation: common table expression
Window expressions
An aggregate such as SUM with GROUP BY collapses many rows into one. A window expression keeps all the rows and adds
a value computed from a group of related rows, the window. The pattern is a window function followed by OVER( ... );
the parentheses define the window:
-
PARTITION BYsplits the result into windows, one per distinct value of the expressions you list. Without it there is one window with all rows. -
ORDER BYinsideOVERorders the rows within each window and is required by the ranking functionsRANKandDENSE_RANK. It is independent of theORDER BYclause of theSELECTstatement, which has no influence on the window result. InsideOVERyou name columns directly, not aliases. -
ROWS BETWEENdefines a frame, a part of the window relative to the current row, with the boundariesUNBOUNDED PRECEDING,CURRENT ROW,n PRECEDINGandn FOLLOWING. If you give no frame, it runs from the first row of the window to the current row, so aggregates become running totals.
The window functions are of three kinds:
-
Aggregate functions such as
AVG,MAX,MIN,SUMandCOUNT, which are also usable without a window. -
Ranking functions:
ROW_NUMBER( )numbers the rows of a window from 1;RANK( )gives rows that tie the same rank and then skips numbers;DENSE_RANK( )gives tied rows the same rank without skipping;NTILE( n )divides a window intonbuckets as equal as possible. -
Value functions:
LEADandLAGread the value of a following or preceding row,FIRST_VALUEandLAST_VALUEthe value of the first or last row.
A window expression can appear only in the SELECT list, not in WHERE, GROUP BY or HAVING. The calculation runs in
the database.
Take claims with these sample rows (worked out by hand to explain ties, not program output): in cost centre CC1000, claims C-1 and C-4 have 120 and C-3 has 80; in CC2000, C-2 has 35 and C-5 has 20. Ranking each claim inside its cost centre by amount, highest first, gives:
| Claim | Cost centre | Amount | RANK |
DENSE_RANK |
|---|---|---|---|---|
C-1 |
CC1000 |
120 |
1 |
1 |
C-4 |
CC1000 |
120 |
1 |
1 |
C-3 |
CC1000 |
80 |
3 |
2 |
C-2 |
CC2000 |
35 |
1 |
1 |
C-5 |
CC2000 |
20 |
2 |
2 |
The tie of C-1 and C-4 gives both rank 1, and RANK then skips to 3 while DENSE_RANK continues with 2. The listing
below asks for exactly these columns, plus a running total per cost centre. It requires an SAP system; not run here
(the local playground does not support window expressions).
SELECT claim_id,
cost_center,
amount,
RANK( ) OVER( PARTITION BY cost_center ORDER BY amount DESCENDING ) AS rank_in_cost_center,
DENSE_RANK( ) OVER( PARTITION BY cost_center ORDER BY amount DESCENDING ) AS dense_rank_in_cost_center,
SUM( amount ) OVER( PARTITION BY cost_center ORDER BY claim_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS running_total
FROM zexp_claim
ORDER BY cost_center, rank_in_cost_center, claim_id
INTO TABLE @DATA(ranked_claims).
Source: ABAP Keyword Documentation: window expressions and ABAP Keyword Documentation: window functions
The ORDER BY of the statement can sort by the alias of a window expression, as the last line does; the same alias is
not allowed inside OVER. To keep only the best claim of each cost centre, select the ranked rows in a CTE and filter
rank_in_cost_center = 1 in the main query, because a window expression cannot be used in WHERE.
Path expressions over CDS associations
A CDS view entity can declare an association, a named link to another entity with a join condition and a cardinality. Declared once, the link can be used by every query on the view. In ABAP SQL you follow it with a path expression: a backslash, the association name, a minus sign and the column of the target. ABAP SQL turns the path into a join for you.
-
A path in the
SELECTlist becomes a left outer join by default. -
A path used as a data source after
FROMbecomes an inner join by default. -
Between the association name and the minus sign you can give attributes in square brackets, such as the join type
INNERand the cardinalityMANY TO ONE, as the documentation example does. -
Paths that share the association and the same attributes produce only one join.
The example extends the table ZEXP_CLAIM of the Dictionary pages with a column cost_center and assumes a table zexp_cost_center with a column name. It declares a view entity of claims with a link to the cost centre, and then reads the cost-centre name through
the path instead of writing the join. It requires an SAP system; not run here (it needs CDS, which the local
playground lacks). The first listing is CDS source code for ADT, the second is ABAP.
@AccessControl.authorizationCheck: #NOT_REQUIRED
define view entity ZI_ExpClaimWithCostCenter
as select from zexp_claim
association [1..1] to zexp_cost_center as _CostCenter
on $projection.CostCenter = _CostCenter.cost_center
{
key claim_id as ClaimId,
cost_center as CostCenter,
amount as Amount,
_CostCenter
}
SELECT ClaimId,
Amount,
\_CostCenter[ INNER MANY TO ONE ]-name AS cost_center_name
FROM zi_expclaimwithcostcenter
INTO TABLE @FINAL(claims_with_names).
Source: ABAP Keyword Documentation: ABAP SQL, SQL path expressions; definition in ABAP Keyword Documentation: SQL path expression
If the association’s cardinality does not fit the way you use the path, the compiler reports a warning or an error. A path expression needs the CDS entity; to link plain Dictionary tables you write the join yourself.
Hierarchies in ABAP SQL
Data such as a cost-centre tree, an organisation chart or a bill of materials has rows that point to a parent row. ABAP
SQL can build a SQL hierarchy from such a table: a result in which every row also has hierarchy columns, for example
hierarchy_level (depth in the tree), hierarchy_rank (position in tree order) and hierarchy_tree_size (size of the
subtree). It does this on the database, which is why hierarchy data is not supported on every database. A statement that
reads hierarchy data bypasses the table buffer.
Two things are needed. The first is a hierarchy source: a CDS view entity that exposes a self-association which says
which column is the parent of which. The second is the hierarchy itself, defined either as a CDS hierarchy
(DEFINE HIERARCHY in CDS, reusable) or directly in the query with the hierarchy generator HIERARCHY( ... ) after
FROM. A common table expression can also serve as the source. The generator takes the source, the association, the
start condition that picks the root rows and the order of siblings, as in this example for a tree of cost centres. It
requires an SAP system; not run here.
@AccessControl.authorizationCheck: #NOT_REQUIRED
define view entity ZR_ExpCostCenterTree
as select from zexp_cc_tree
association [1..1] to ZR_ExpCostCenterTree as _tree
on $projection.parent = _tree.id
{
_tree,
key id,
parent_id as parent,
name
}
DATA root_id TYPE zr_expcostcentertree-id VALUE 'CC0000'.
SELECT FROM HIERARCHY( SOURCE zr_expcostcentertree
CHILD TO PARENT ASSOCIATION _tree
START WHERE id = @root_id
SIBLINGS ORDER BY id
MULTIPLE PARENTS NOT ALLOWED )
FIELDS id,
name,
hierarchy_level,
hierarchy_rank,
hierarchy_tree_size
INTO TABLE @FINAL(tree_rows).
Source: ABAP cheat sheet: ABAP SQL, Working with Hierarchies and ABAP Keyword Documentation: SELECT, FROM hierarchy_data
On top of a hierarchy, hierarchy navigators answer common questions directly: HIERARCHY_DESCENDANTS returns the nodes
below a given node, HIERARCHY_ANCESTORS the nodes above it, and HIERARCHY_SIBLINGS the nodes that share its parent.
They are used after FROM like any other data source and can be joined to other sources.
Choosing the right tool
-
Use a join when you need columns of two sources in one row, an outer join when the rows of one side must survive.
-
Use
UNION,INTERSECTorEXCEPTto combine or compare result sets of the same shape. -
Use a CTE when a result is needed twice, or when you need to select from an intermediate result.
-
Use a window expression when each row needs a rank, a running total or a neighbour value and the rows must stay.
-
Use a path expression when a CDS view already declares the link; write the join yourself otherwise.
-
Reach for a hierarchy only when the data really is a tree, and on a database that supports it.
Summary
-
A join combines columns of two data sources; an inner join keeps only matching rows, a left outer join keeps every row of the left side and fills the right side with null values.
-
UNIONstacks and de-duplicates results,INTERSECTandEXCEPTcompare them. -
A common table expression, written with
WITHand a name that starts with a plus sign, names an intermediate result for use in the main query of the same statement. -
A window expression, a function followed by
OVER( PARTITION BY ... ORDER BY ... ), adds a rank or running figure to each row without merging rows;RANKleaves gaps after ties,DENSE_RANKdoes not. -
A path expression names a CDS association and ABAP SQL generates the join; in the select list it is a left outer join, after
FROMan inner join. -
Hierarchy data is built from a self-association, either in a CDS hierarchy or with the
HIERARCHYgenerator, and is not supported by all databases.