Beyond ABAPdesigned by@Tejoram97
Beyond ABAP / ABAP on HANA / ABAP SQL, ADBC & ALV IDA

ABAP SQL, ADBC & ALV IDA

ABAP on HANA · ABAP Development ·

Open the interactive lesson →
  1. How ABAP talks to the database
  2. ABAP SQL: the new syntax rules
  3. SQL expressions in the field list
  4. WHERE clause features
  5. Aggregates, GROUP BY, HAVING
  6. Joins, FOR ALL ENTRIES, UNION, CTE, SELECT FROM @itab
  7. Window expressions (7.54+)
  8. More ABAP SQL features (quick reference)
  9. Performance rules for ABAP SQL
  10. Native SQL and ADBC
  11. ALV with IDA (Integrated Data Access)
  12. ABAP SQL vs CDS vs AMDP vs ADBC: which one when?
  13. Interview questions

How ABAP programs read and write the database: the architecture (DB interface, table buffer), ABAP SQL (called Open SQL until 7.53) with all its modern features, native SQL / ADBC, the ALV with IDA and a guide for choosing ABAP SQL, CDS, AMDP or ADBC. Pushing work into SQL is the first and easiest step of code push-down on HANA. CDS views and AMDP have their own pages.

Part 1 – How ABAP talks to the database

ABAP SQL, native SQL and AMDP paths through the DB interface and DBSL to the database

ABAP SQL

Native SQL (EXEC SQL / ADBC)

AMDP

Language

ABAP statements

SQL of the database, as text

SQLScript in an ABAP method

Database-independent

Yes

No

No (HANA)

Checked at compile time

Yes

No – errors at runtime

Yes (by the DB at activation)

Client handling

Automatic

Manual (WHERE mandt = …)

Manual (or AMDP OPTIONS CDS SESSION CLIENT)

Table buffer

Used

Bypassed

Bypassed

Objects

DDIC tables, views, CDS

Any DB object, also non-DDIC

DDIC tables, CDS (USING)

ABAP Cloud

Yes

No

Yes

SQL (Structured Query Language) is the declarative language of relational databases: you say WHAT data you want, and the database decides HOW to get it. ABAP has two forms of it: ABAP SQL (Open SQL), part of the ABAP language, and native SQL (EXEC SQL / ADBC), passed to the database unchanged.

SQL statement categories – and who does them in ABAP

Category

Statements

In the ABAP world

DDL – definition

CREATE, ALTER, DROP

ABAP Dictionary (SE11) and CDS DDL – not from ABAP SQL

DQL – query

SELECT

ABAP SQL SELECT

DML – manipulation

INSERT, UPDATE, DELETE, UPSERT

ABAP SQL INSERT, UPDATE, MODIFY, DELETE

DCL – control

GRANT, REVOKE

None: the DB knows one technical user. ABAP uses AUTHORITY-CHECK and CDS access control (DCL roles)

TCL – transaction

COMMIT, ROLLBACK

COMMIT WORK / ROLLBACK WORK; an implicit DB commit after every dialog step

ABAP SQL statement

Purpose

SELECT

Read rows

INSERT

Add rows (single or array: INSERT dbtab FROM TABLE @itab)

UPDATE

Change existing rows

MODIFY

Insert or update (upsert)

DELETE

Delete rows

OPEN CURSOR / FETCH / CLOSE CURSOR

Read big results in packages

Classic Open SQL supported only the common subset of SQL that every database understands (the "lowest common denominator"): no expressions, no outer joins beyond LEFT, no UNION. Since 7.40 SP05 it has grown step by step – this is the "enhanced / advanced Open SQL" of the HANA era.

Part 2 – ABAP SQL: the new syntax rules

Open SQL was renamed ABAP SQL in 7.53 (S/4HANA 1809). Same thing, new name – say "ABAP SQL" in interviews.

Anatomy of a modern ABAP SQL SELECT statement
" Old syntax – still compiles, but no new features can be used in it
SELECT so_id currency_code gross_amount delivery_status
FROM snwd_so
INTO TABLE lt_so_amount
UP TO 10 ROWS
WHERE currency_code = 'EUR'.

" New syntax (strict mode)
SELECT so_id, currency_code, gross_amount, delivery_status
FROM snwd_so
WHERE currency_code = 'EUR'
INTO TABLE @DATA(lt_so_amount2)
UP TO 10 ROWS.

Rule / feature

Syntax

Since

Comma-separated field list

SELECT carrid, connid, fldate

7.40 SP05

Host variables escaped with @

WHERE carrid IN @s_carrid

7.40 SP05

INTO at the end, inline declaration

INTO TABLE @DATA(lt_result)

7.40 SP08

FROM first + FIELDS

SELECT FROM sflight FIELDS carrid, connid …

7.50

Column alias

carrid AS carrier

always; needed for expressions

Literal as a column

'Extra column' AS new_column

7.40 SP08

All columns of one table in a join

FIELDS spfli~*, sflight~fldate

7.40 SP08

Host expression

WHERE carrid = @( to_upper( lv_carrid ) )

7.50

Options after INTO

INTO … UP TO 10 ROWS OFFSET 20

OFFSET 7.51

  • Strict mode: once a statement uses any new feature, all new rules apply to that statement (commas, @, INTO position). Mixing old and new in one statement is a syntax error.

Build a range table directly from the database (literals as columns)

DATA lr_matnr TYPE RANGE OF matnr.
SELECT 'I' AS sign, 'EQ' AS option, matnr AS low
FROM mara
WHERE matnr IN @s_matnr
AND matnr LIKE 'SFDC%'
INTO CORRESPONDING FIELDS OF TABLE @lr_matnr
UP TO 10 ROWS.
" lr_matnr can now be used in another WHERE: … WHERE matnr IN @lr_matnr

" A range can also hold a pattern: option CP with * and + (LIKE uses % and _)
DATA lr_pattern TYPE RANGE OF matnr.
lr_pattern = VALUE #( ( sign = 'I' option = 'CP' low = 'SFDC*' ) ).
" Select-options and own ranges combine in one WHERE:
"   WHERE matnr IN @s_matnr AND matnr IN @lr_pattern

Part 3 – SQL expressions in the field list

Calculations now run in the database – only the result travels to the application server.

3.1 Arithmetic and numeric functions

DATA lv_discount TYPE p LENGTH 3 DECIMALS 2 VALUE '0.90'.
SELECT FROM vbak AS so
INNER JOIN vbap AS item ON so~vbeln = item~vbeln
INNER JOIN kna1 AS cust ON so~kunnr = cust~kunnr
FIELDS so~vbeln                              AS sales_order,
cust~name1                            AS customer,
item~posnr                            AS sales_item,
item~netpr                            AS net_price,
item~netpr * @lv_discount             AS net_discounted,
ceil( item~netpr )                    AS ceil,
floor( item~netpr )                   AS floor,
abs( item~netpr )                     AS abs,
round( item~netpr, 1 )                AS round,
div( CAST( item~netpr AS INT8 ), 10 ) AS div,
mod( CAST( item~netpr AS INT8 ), 10 ) AS mod,
division( item~netpr, 3, 2 )          AS third
WHERE so~erdat >= @lv_from
INTO TABLE @DATA(lt_result).

Function

Meaning

+ - *

Normal arithmetic

/

Only in floating-point expressions (FLTP or decimal floating point) – for integers and decimals use the functions below

div( a, b ), mod( a, b )

Integer division and remainder

division( a, b, dec )

Decimal division rounded to dec places

ceil( ), floor( ), abs( ), round( a, n )

Round up, round down, absolute value, round to n places

CAST( x AS type )

Convert, e.g. CAST( netpr AS INT8 ), CAST( '00000000' AS DATS )

3.2 String functions

DELETE FROM demo_expressions.
INSERT demo_expressions FROM TABLE @( VALUE #( ( id = 1 char1 = ' 0123' char2 = 'aAaA' ) ) ).
SELECT FROM demo_expressions
FIELDS concat( char1, char2 )               AS concat,
concat_with_space( char1, char2, 1 ) AS concat_with_space,
length( char1 )                      AS length,
instr( char1, '12' )                 AS instr,
left( char1, 3 )                     AS left,
right( char1, 3 )                    AS right,
lpad( char1, 10, 'X' )               AS lpad,
rpad( char1, 10, 'X' )               AS rpad,
ltrim( char1, ' ' )                  AS ltrim,
rtrim( char1, '3' )                  AS rtrim,
replace( char2, 'Aa', '--' )         AS replace,
lower( char2 )                       AS lower,
upper( char2 )                       AS upper,
substring( char2, 2, 2 )             AS subst
INTO TABLE @DATA(lt_strings).

Function

Result for char1 = ' 0123', char2 = 'aAaA'

concat( char1, char2 ) / concat_with_space( char1, char2, 1 )

' 0123aAaA' / ' 0123 aAaA'

length( char1 ) – trailing blanks ignored

5

instr( char1, '12' ) – position of the substring

3

left( char1, 3 ) / right( char1, 3 )

' 01' / '123'

lpad( char1, 10, 'X' ) / rpad( char1, 10, 'X' )

'XXXXX 0123' / ' 0123XXXXX'

ltrim( char1, ' ' ) / rtrim( char1, '3' )

'0123' / ' 012'

replace( char2, 'Aa', '--' )

'a--A'

lower( char2 ) / upper( char2 )

'aaaa' / 'AAAA'

substring( char2, 2, 2 ) – from position 2, length 2

'Aa'

3.3 Date functions (7.50)

Function

Result

dats_is_valid( dats1 )

1 if the date is valid, else 0

dats_days_between( dats1, dats2 )

Number of days between two dates

dats_add_days( dats1, 100 )

Date + 100 days

dats_add_months( dats1, -1 )

Date one month earlier

3.4 CASE – simple and searched

SELECT FROM vbak
FIELDS vbeln AS sales_order,
CASE vbtyp  " simple CASE: one operand, = only
WHEN 'C' THEN 'Order'
WHEN 'B' THEN 'Quotation'
WHEN 'H' THEN 'Returns'
ELSE 'Other documents'
END AS document_category,
netwr AS net_amount,
CASE        " searched CASE: any condition
WHEN netwr >= 1000 THEN 'High amount'
WHEN netwr >= 500  THEN 'Medium amount'  " first match wins – no gaps at 500/1000
ELSE 'Low amount'
END AS amount_category
WHERE erdat >= @lv_from
INTO TABLE @DATA(lt_docs).
  • In S/4HANA VBAK-VBTYP is longer (data element VBTYPL, CHAR 4) – the old one-letter values still work.

3.5 NULL and COALESCE

NULL means "no value" – it is not the initial value. NULL appears e.g. in the right-hand columns of a LEFT OUTER JOIN when no partner row exists. ABAP has no NULL: when the row arrives in ABAP, NULL becomes the initial value of the type, so you can no longer see the difference. Handle NULL in SQL with IS [NOT] NULL and coalesce( ).

" Sales orders with their invoice amount – or the order amount if not invoiced yet
SELECT FROM vbak AS so
LEFT OUTER JOIN vbfa AS flow ON  flow~vbelv   = so~vbeln
AND flow~vbtyp_v = 'C'
AND flow~vbtyp_n = 'M'
LEFT OUTER JOIN vbrk AS inv  ON  inv~vbeln    = flow~vbeln
FIELDS so~vbeln  AS sales_order,
so~netwr  AS so_amount,
inv~netwr AS inv_amount,                            " NULL if no invoice
CASE WHEN inv~netwr IS NOT NULL THEN inv~netwr
ELSE so~netwr
END AS amount_case,
coalesce( inv~netwr, so~netwr ) AS amount_coalesce  " same result, shorter
WHERE so~erdat >= @lv_from
INTO TABLE @DATA(lt_amounts).
  • coalesce( a1, a2, …, an ) returns the first argument that is not NULL = CASE WHEN a1 IS NOT NULL THEN a1 WHEN a2 IS NOT NULL THEN a2 … ELSE an END.
  • Default for a missing outer-join partner: coalesce( p~connid, '9999' ) AS connid.

3.6 Case-insensitive search

DATA(lv_search) = '%' && to_upper( 'IRon' ) && '%'.  " old way: read all, TRANSLATE, CS
SELECT movie FROM zmovie
WHERE upper( movie ) LIKE @lv_search
INTO TABLE @DATA(lt_movies).

Part 4 – WHERE clause features

Feature

Example

Since

Range / select-option

WHERE carrid IN @s_carrid

always

Host expression

WHERE carrid = @( to_upper( lv_carrid ) )

7.50

Method call as host expression

WHERE movie = @( get_hulk_movie( ) )

7.50

Arithmetic

WHERE ( grosscol - openingcol ) > 10000000

7.50

Initial check

WHERE grosscol IS NOT INITIAL

7.53 (S/4HANA 1809)

NULL check

WHERE inv~netwr IS NULL

always

Pattern

WHERE name1 LIKE 'SAP%' (% any text, _ one character)

always

Subquery

WHERE EXISTS ( SELECT … ), WHERE carrid IN ( SELECT … )

always (expressions later)

" Host expression: look up the carrier ID in an internal table, inside the WHERE
SELECT FROM spfli
FIELDS carrid, cityfrom, cityto
WHERE carrid = @( VALUE spfli-carrid(
lt_scarr[ carrname = lv_carrname ]-carrid OPTIONAL ) )
INTO TABLE @DATA(lt_connections).

" Subquery: carriers that fly from Frankfurt
SELECT FROM scarr AS c
FIELDS c~carrid, c~carrname
WHERE EXISTS ( SELECT carrid FROM spfli
WHERE carrid = c~carrid AND cityfrom = 'FRANKFURT' )
INTO TABLE @DATA(lt_fra_carriers).
  • Host expressions @( method( ) ) / @( expr ) are allowed not only in WHERE but also in the field list and in ON conditions (7.50).

Part 5 – Aggregates, GROUP BY, HAVING

Aggregate function

Returns

SUM( col )

Total

AVG( col )

Average (FLTP by default; AVG( col AS DEC( 15, 2 ) ) for a decimal result)

MIN( col ), MAX( col )

Smallest / largest value

COUNT( * ), COUNT( DISTINCT col )

Number of rows / of different values

string_agg( col, ', ' )

Values of the group joined into one string (7.54)

  • Every column in the field list that is not inside an aggregate must be in GROUP BY.
  • WHERE filters rows before grouping; HAVING filters groups after grouping (can use aggregates).
" Simple aggregate
SELECT carrid, SUM( price ) AS total_price
FROM sflight
GROUP BY carrid
INTO TABLE @DATA(lt_per_carrier).

" Per customer and currency – all common aggregates
SELECT FROM vbak AS so
INNER JOIN kna1 AS cust ON so~kunnr = cust~kunnr
FIELDS so~kunnr          AS cust_id,
cust~name1        AS customer,
so~waerk          AS currency,
SUM( so~netwr )   AS total_net,
AVG( so~netwr AS DEC( 15, 2 ) ) AS avg_net,
MAX( so~netwr )   AS max_net,
MIN( so~netwr )   AS min_net,
COUNT( * )        AS orders
GROUP BY so~kunnr, cust~name1, so~waerk
HAVING SUM( so~netwr ) > 10000
ORDER BY total_net DESCENDING
INTO TABLE @DATA(lt_customers).

" SQL expression in GROUP BY (7.51) – repeat the same expression in the field list
SELECT num1 + num2 AS total, COUNT( * ) AS cnt
FROM demo_expressions
GROUP BY num1 + num2
HAVING COUNT( * ) > 10
ORDER BY total
INTO TABLE @DATA(lt_groups).

Part 6 – Joins, FOR ALL ENTRIES, UNION, CTE, SELECT FROM @itab

6.1 Joins

On old databases developers avoided joins and used FOR ALL ENTRIES. On HANA, joins are fast and are the preferred way – one statement, the database does the work.

Join

Result

Since

INNER JOIN

Only rows that have a partner on both sides

always

LEFT OUTER JOIN

All left rows; right columns NULL (→ initial in ABAP) when no partner

always

RIGHT OUTER JOIN

All right rows; left columns NULL when no partner

7.40 SP05

CROSS JOIN

Every left row with every right row (no ON condition)

7.51

DATA(lv_city_from) = CONV spfli-cityfrom( 'BERLIN' ).
SELECT c~carrname, p~connid
FROM scarr AS c
INNER JOIN spfli AS p ON  p~carrid   = c~carrid
AND p~cityfrom = @lv_city_from
INTO TABLE @DATA(lt_inner).  " only carriers with a Berlin flight

SELECT c~carrname, coalesce( p~connid, '9999' ) AS connid
FROM scarr AS c
LEFT OUTER JOIN spfli AS p ON  p~carrid   = c~carrid
AND p~cityfrom = @lv_city_from
INTO TABLE @DATA(lt_left).  " all carriers, 9999 = no Berlin flight

SELECT FROM sflight
INNER JOIN spfli ON  sflight~carrid = spfli~carrid
AND sflight~connid = spfli~connid
FIELDS spfli~*, sflight~fldate  " all columns of SPFLI + one of SFLIGHT
INTO TABLE @DATA(lt_all).

6.2 FOR ALL ENTRIES – rules and the modern alternative

  • Empty driver table = the WHERE condition on it is ignored → ALL rows are read. Always check IF lt_driver IS NOT INITIAL first.
  • Duplicate result rows are removed (like SELECT DISTINCT) – select all key fields or rows get lost.
  • No aggregates (except COUNT( * )), and you cannot see detail rows next to the aggregate.

Modern alternative (7.52): join the internal table directly as @itab with an alias – one statement, aggregates allowed:

DATA lr_carriers TYPE RANGE OF /dmo/carrier-carrier_id.
SELECT * FROM /dmo/carrier WHERE carrier_id IN @lr_carriers INTO TABLE @DATA(lt_carrier).
IF lt_carrier IS NOT INITIAL.
SELECT dtab~carrier_id, dtab~connection_id, SUM( dtab~seats_occupied ) AS travellers
FROM /dmo/flight AS dtab
INNER JOIN @lt_carrier AS itab ON dtab~carrier_id = itab~carrier_id
GROUP BY dtab~carrier_id, dtab~connection_id
ORDER BY dtab~carrier_id, dtab~connection_id
INTO TABLE @DATA(lt_travels_by_connection).
ENDIF.

6.3 UNION (7.50)

Adds the rows of a second SELECT to the first – replaces several SELECTs with APPENDING TABLE.

  • All SELECTs need the same number of columns with compatible types; column names come from the first SELECT.
  • UNION = UNION DISTINCT (duplicates removed, extra work). Use UNION ALL when duplicates are impossible or wanted – it is faster.
  • ORDER BY and INTO come once, at the very end. FOR ALL ENTRIES is not allowed; aggregates are.
SELECT FROM vbak AS so
INNER JOIN kna1 AS cust ON so~kunnr = cust~kunnr
FIELDS so~kunnr AS cust_id, cust~name1 AS customer, so~waerk AS currency,
SUM( so~netwr ) AS total_net, 'Important customer' AS category
GROUP BY so~kunnr, cust~name1, so~waerk
HAVING SUM( so~netwr ) >= 10000
UNION ALL
SELECT FROM vbak AS so
INNER JOIN kna1 AS cust ON so~kunnr = cust~kunnr
FIELDS so~kunnr AS cust_id, cust~name1 AS customer, so~waerk AS currency,
SUM( so~netwr ) AS total_net, 'Other customer' AS category
GROUP BY so~kunnr, cust~name1, so~waerk
HAVING SUM( so~netwr ) < 10000  " >= and < – no customer falls in a gap
ORDER BY total_net DESCENDING
INTO TABLE @DATA(lt_categories).

6.4 Common table expressions – WITH (7.51)

A CTE is a named subquery that exists only while the statement runs – like a temporary view. Names start with +, the column list is optional, a later CTE and the main query can read earlier CTEs. Use it instead of several statements or a global temporary table, e.g. for subtotals.

WITH
+cte1[ ( name1, name2, … ) ] AS ( SELECT … [UNION …] ),
+cte2[ ( name1, name2, … ) ] AS ( SELECT … FROM +cte1 … )
SELECT … FROM +cte2 …
[UNION …]
INTO|APPENDING target
[UP TO … ROWS] [OFFSET …]
[abap_options].
[ENDWITH.]  " only when the main query opens a loop (no INTO TABLE), like ENDSELECT
" 1) Cities served by Lufthansa (departure or arrival)
WITH +cities AS ( SELECT cityfrom AS city FROM spfli WHERE carrid = 'LH'
UNION DISTINCT
SELECT cityto   AS city FROM spfli WHERE carrid = 'LH' )
SELECT * FROM sgeocity
WHERE city IN ( SELECT city FROM +cities )
INTO TABLE @DATA(lt_cities).

" 2) Detail rows + one subtotal row per connection (adapted from the SAP keyword docu)
WITH +agg AS ( SELECT carrid, connid,
CAST( '00000000' AS DATS ) AS fldate,
SUM( seatsocc ) AS seatsocc
FROM sflight
WHERE carrid = @( to_upper( lv_carrid ) )
GROUP BY carrid, connid )
SELECT ' ' AS mark, carrid, connid, fldate, seatsocc
FROM sflight
WHERE carrid = @( to_upper( lv_carrid ) )
UNION ALL
SELECT 'X' AS mark, carrid, connid, fldate, seatsocc
FROM +agg
ORDER BY carrid, connid, mark, fldate
INTO TABLE @DATA(lt_with_subtotals).

" 3) Two CTEs + CROSS JOIN: every LH connection with the total number of connections
WITH +conns AS ( SELECT carrname, connid, cityfrom, cityto
FROM spfli JOIN scarr ON spfli~carrid = scarr~carrid
WHERE spfli~carrid = 'LH' ),
+cnts  AS ( SELECT COUNT( * ) AS cnt FROM +conns )
SELECT * FROM +cnts CROSS JOIN +conns
ORDER BY carrname, connid
INTO TABLE @DATA(lt_conns).

6.5 SELECT FROM an internal table (7.52)

An internal table can be a data source with @itab AS alias. If the statement reads only internal tables the ABAP SQL engine runs it on the application server if possible (otherwise it is passed to the database); joined with DB tables the itab is sent to the database – keep it small.

SELECT carrier_id, connection_id, flight_date
FROM @lt_flights AS flights
WHERE city_from = 'FRANKFURT'
INTO TABLE @DATA(lt_fra_flights).

SELECT SINGLE FROM @lt_flights AS flights
FIELDS carrier_id, connection_id
WHERE flight_date = @sy-datum AND city_from = 'FRANKFURT'
INTO @DATA(ls_todays_flight).

Part 7 – Window expressions (7.54+)

A window expression function OVER( … ) calculates over a set of rows (the window) but keeps every row – unlike GROUP BY, which collapses them. PARTITION BY splits the result into windows, ORDER BY sorts inside the window, a frame (ROWS BETWEEN …) limits it to a moving range. Window expressions came with 7.54; frames and some functions in later releases – they are not part of a "7.4/7.5" system.

GROUP BY versus window expressions with PARTITION BY and a frame
win_function OVER( [PARTITION BY col1, col2 …]
[ORDER BY col [ASCENDING|DESCENDING] …]
[ROWS BETWEEN frame_start AND frame_end] )

Kind

Functions

Notes

Aggregate

SUM, AVG, MIN, MAX, COUNT, MEDIAN, STDDEV, VAR, CORR

Over the window or the frame

Ranking (need ORDER BY)

ROW_NUMBER( ), RANK( ), DENSE_RANK( ), NTILE( n )

ROW_NUMBER 1,2,3,4 · RANK with gaps 1,1,3 · DENSE_RANK no gaps 1,1,2 · NTILE splits into n groups (negative n → runtime error CX_SY_OPEN_SQL_DB)

Value (need ORDER BY)

FIRST_VALUE, LAST_VALUE, LEAD, LAG

First / last value in the window order; LEAD = next row, LAG = previous row

Frame boundary

Meaning

UNBOUNDED PRECEDING

First row of the window (start only)

n PRECEDING / n FOLLOWING

n rows before / after the current row

CURRENT ROW

The current row

UNBOUNDED FOLLOWING

Last row of the window (end only)

  • LAST_VALUE trap: with ORDER BY the default frame ends at the CURRENT ROW, so LAST_VALUE returns the current row. Add ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.
" Statistics per carrier and per connection, every flight row kept
SELECT FROM /dmo/flight
FIELDS carrier_id AS carrier, connection_id AS connection, flight_date AS date, price,
COUNT( * )   OVER( PARTITION BY carrier_id )                AS cnt_carrier,
COUNT( * )   OVER( PARTITION BY carrier_id, connection_id ) AS cnt_connection,
AVG( price ) OVER( PARTITION BY carrier_id, connection_id ) AS avg_price,
MIN( price ) OVER( PARTITION BY carrier_id, connection_id ) AS min_price,
MAX( price ) OVER( PARTITION BY carrier_id, connection_id ) AS max_price,
SUM( price ) OVER( PARTITION BY carrier_id, connection_id ) AS total_price,
division( 100 * price,
SUM( price ) OVER( PARTITION BY carrier_id, connection_id ),
2 ) AS percentage
ORDER BY carrier_id, connection_id, flight_date
INTO TABLE @DATA(lt_window).

" Ranking and previous value
SELECT FROM sflight
FIELDS carrid, connid, fldate, seatsocc,
ROW_NUMBER( ) OVER( PARTITION BY carrid ORDER BY seatsocc DESCENDING ) AS row_no,
RANK( )       OVER( PARTITION BY carrid ORDER BY seatsocc DESCENDING ) AS rank_no,
DENSE_RANK( ) OVER( PARTITION BY carrid ORDER BY seatsocc DESCENDING ) AS dense_no,
LAG( seatsocc ) OVER( PARTITION BY carrid ORDER BY fldate )           AS prev_seats
INTO TABLE @DATA(lt_rank).

" 3-row moving average per carrier
SELECT FROM /dmo/flight
FIELDS carrier_id, flight_date, seats_occupied,
AVG( seats_occupied ) OVER( PARTITION BY carrier_id ORDER BY flight_date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW ) AS avg_3
INTO TABLE @DATA(lt_moving).

" ORDER BY without PARTITION BY: the whole result is one window -> running average
SELECT FROM /dmo/flight
FIELDS carrier_id, flight_date, seats_occupied,
AVG( seats_occupied ) OVER( ORDER BY seats_occupied
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS avg_running
INTO TABLE @DATA(lt_running).
  • NTILE use case: NTILE( 4 ) OVER( ORDER BY month ) over twelve monthly totals assigns each month its quarter 1–4.
Result of the moving average: windows per carrier and a sliding three-row frame

Above: each carrier is one window; for the third UA row the frame holds rows 1–3, so the average is (231 + 237 + 75) / 3 = 181 (shown as 1.81E2 because AVG returns a float).

Real-life example: order value, customer value and item counter per sales-order item

SELECT FROM vbap AS so_item
INNER JOIN vbak AS so_header      ON so_header~vbeln = so_item~vbeln
LEFT OUTER JOIN kna1 AS cust_data ON cust_data~kunnr = so_header~kunnr
FIELDS so_header~erdat, so_header~vbeln, so_item~posnr, so_header~kunnr,
cust_data~name1, cust_data~regio,
CASE so_header~vbtyp WHEN 'C' THEN 'Order'   WHEN 'B' THEN 'Quotation'
WHEN 'A' THEN 'Inquiry' WHEN 'H' THEN 'Returns'
ELSE 'Others' END                     AS document_category,
so_item~matnr, so_item~werks,
so_item~netwr                                              AS item_value,
SUM( so_item~netwr ) OVER( PARTITION BY so_header~vbeln )  AS order_value,
SUM( so_item~netwr ) OVER( PARTITION BY so_header~kunnr )  AS customer_value,
COUNT( * ) OVER( PARTITION BY so_header~vbeln ORDER BY so_item~posnr
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS item_counter
WHERE so_header~vbeln IN @s_vbeln
AND so_header~kunnr IN @s_kunnr
INTO TABLE @DATA(lt_fin).

Part 8 – More ABAP SQL features (quick reference)

Feature

Example

Since

Other client

SELECT * FROM sflight USING CLIENT '100' WHERE … INTO TABLE @DATA(lt) (replaces the obsolete CLIENT SPECIFIED; USING CLIENT since 7.40 SP05)

7.40 SP05

Paging

… ORDER BY carrid, connid INTO TABLE @lt UP TO 20 ROWS OFFSET 40

7.51

Sort by key

ORDER BY PRIMARY KEY

always

Fill by name

INTO CORRESPONDING FIELDS OF TABLE @lt_target

always

Array insert

INSERT zorders FROM TABLE @lt_orders. – one DB call for many rows

always

Insert from a subquery

INSERT ztarget FROM ( SELECT … FROM zsource WHERE … ).

7.50

Update with an expression

UPDATE zstock SET quantity = quantity - @lv_qty WHERE matnr = @lv_matnr.

always

Skip the table buffer

SELECT … FROM t001 BYPASSING BUFFER …

always

Read big data in packages

SELECT … INTO TABLE @lt PACKAGE SIZE 10000. … ENDSELECT.

always

Part 9 – Performance rules for ABAP SQL

Rule

How

Keep the result set small

Good WHERE conditions; SELECT SINGLE / UP TO 1 ROWS for one row; HAVING for groups

Transfer little data

Only the columns you need (no SELECT *); aggregates in the DB (SUM, COUNT, GROUP BY)

Few round trips

No SELECT inside LOOP; joins, subqueries, CTEs, @itab joins instead of nested SELECTs; array INSERT / UPDATE FROM TABLE

Search efficiently

Use index / key fields in WHERE (on HANA column store most secondary indexes are not needed)

Avoid repeated reads

Table buffer for small, rarely changed tables; read once into an internal table (sorted / hashed) and reuse it

Push logic down

Calculations, CASE, string functions in SQL; reusable logic in CDS; complex logic in AMDP

Logical databases (LDB) from old guidelines are obsolete – do not use them. Performance tools (ST05, SAT, SQLM, SWLT, ATC) are on the migration and performance page.

Part 10 – Native SQL and ADBC

Native SQL is SQL written in the database's own dialect and passed through unchanged. Use it only when ABAP SQL, CDS and AMDP cannot do the job: a secondary database connection (DBCO), DB objects that are not in the ABAP Dictionary, or DB-specific DDL. Two ways: the old static EXEC SQL … ENDEXEC and the class-based ADBC (ABAP Database Connectivity). The ADBC API is database-independent, but the SQL text you pass is database-specific.

Legacy – EXEC SQL (know it for interviews)

EXEC SQL PERFORMING print_schedule.  " FORM called once per row
SELECT carrid, connid, cityfrom, cityto
FROM spfli
INTO :ls_schedule
WHERE mandt = :sy-mandt AND carrid = :p_carrid
ENDEXEC.
" Replaced by ADBC: no syntax check, FORM routines, hard to handle errors.
ADBC steps from connection to close

Class

Role

CL_SQL_CONNECTION

Connection: get_abap_connection( 'DEFAULT' ) = standard DB connection, get_connection( 'DBCON_NAME' ) = own exclusive connection (e.g. secondary DB)

CL_SQL_STATEMENT

Executes SQL: execute_query (SELECT), execute_update (INSERT/UPDATE/DELETE), execute_ddl (CREATE/ALTER/DROP), execute_procedure (DB procedure)

CL_SQL_PREPARED_STATEMENT

Statement parsed once, executed many times with different bound values

CL_SQL_RESULT_SET

Result of a query: set_param_table, set_param_struct, set_param, next_package( ), next( ), close( )

CX_SQL_EXCEPTION

Error from the DB (SQL code and message); also CX_PARAMETER_INVALID(_TYPE) for bad bindings

Example 1 – SELECT with bound parameters and client handling

TYPES: BEGIN OF ty_cust,
kunnr TYPE kna1-kunnr,
land1 TYPE kna1-land1,
name1 TYPE kna1-name1,
END OF ty_cust.
DATA lt_cust TYPE STANDARD TABLE OF ty_cust WITH EMPTY KEY.
PARAMETERS p_land TYPE kna1-land1 DEFAULT 'DE'.

START-OF-SELECTION.
TRY.
DATA(lo_stmt) = NEW cl_sql_statement( ).
lo_stmt->set_param( REF #( sy-mandt ) ).         " 1st ? – native SQL has NO auto client
lo_stmt->set_param( REF #( p_land ) ).           " 2nd ? – bound, never concatenated
DATA(lo_result) = lo_stmt->execute_query(
`SELECT kunnr, land1, name1 FROM kna1 WHERE mandt = ? AND land1 = ?` ).
lo_result->set_param_table( REF #( lt_cust ) ).  " target: columns by position
lo_result->next_package( ).                      " fetch all rows (or n per call)
lo_result->close( ).
CATCH cx_sql_exception cx_parameter_invalid INTO DATA(lx_error).
MESSAGE lx_error->get_text( ) TYPE 'I'.  " short text; get_longtext( ) = DB error details
ENDTRY.
" Single row instead: set_param_struct( REF #( ls_cust ) ) + next( ) (returns 1 or 0)

Example 2 – DML and a DB procedure with IN / OUT parameters

" INSERT with placeholders (zemp_demo is a DDIC table with MANDT, EMPNO, ENAME)
DATA(lo_ins) = NEW cl_sql_statement( ).
lo_ins->set_param( REF #( sy-mandt ) ).
lo_ins->set_param( REF #( ls_emp-empno ) ).
lo_ins->set_param( REF #( ls_emp-ename ) ).
DATA(lv_rows) = lo_ins->execute_update(
`INSERT INTO ZEMP_DEMO ( MANDT, EMPNO, ENAME ) VALUES ( ?, ?, ? )` ).
COMMIT WORK.  " default connection = normal SAP LUW

" Procedure ZADDITION( IN x INTEGER, IN y INTEGER, OUT z INTEGER )
DATA(lo_proc) = NEW cl_sql_statement( ).
lo_proc->set_param( REF #( lv_x ) ).
lo_proc->set_param( REF #( lv_y ) ).
lo_proc->set_param( data_ref = REF #( lv_sum )
inout    = cl_sql_statement=>c_param_out ).
lo_proc->execute_procedure( proc_name = 'ZADDITION' ).
WRITE: / 'Sum is', lv_sum.
  • SQL injection: never build the SQL string by concatenating user input into it. Bind values with ? + set_param. Table or column names cannot be bound – check them against an allow-list (cl_abap_dyn_prg methods) before use.
  • Client: native SQL reads all clients unless you add mandt = ? bound to sy-mandt.
  • close( ) on the connection matters for secondary connections; the default connection stays open.
  • Creating tables or procedures directly in the ABAP schema with native DDL bypasses the ABAP Dictionary and transports – demo only. Use DDIC / CDS for tables and AMDP for procedures.

Disadvantages of ADBC

  • No syntax check by the ABAP compiler – errors only at runtime; SQL inside the string cannot be debugged and shows no intermediate results, so errors are hard to analyse. Long SQL strings are hard to read.
  • No automatic client handling, no table buffer, database-specific SQL.
  • Not released for ABAP Cloud / clean core – use ABAP SQL, CDS or AMDP there.

Legacy – know it for interviews: before CDS and AMDP (7.40 < SP05, HANA as side-car), ADBC was used to call HANA repository procedures (CALL "_SYS_BIC"."pkg/proc"( null ) WITH OVERVIEW, which returns the name of a temporary result table) and to read HANA views. Replaced by AMDP and CDS (see the AMDP page).

Part 11 – ALV with IDA (Integrated Data Access)

CL_SALV_GUI_TABLE_IDA (7.40 SP05) shows a database table, DDIC view or CDS view in an SAP GUI ALV without reading the data into an internal table. The ALV asks the database only for the visible rows; sorting, filtering and totals become new SQL queries. Optimised for HANA, but works on any database.

Classic ALV compared with ALV with IDA

Classic ALV

ALV with IDA

Data retrieval

Program SELECTs everything into an internal table

Only the table / view name is passed; IDA reads

Rows read

All rows

Only the visible rows (paging)

Scroll, sort, filter, totals

In the application server, on the internal table

New SQL query each time, in the DB

Memory

Size of the whole internal table

Size of the visible area

Speed with millions of rows

Slow start, may dump (memory)

Fast

" Minimal: create, fullscreen, display (SAP sample: SALV_IDA_DISPLAY_DATA_SIMPLE)
cl_salv_gui_table_ida=>create( iv_table_name = 'SFLIGHT' )->fullscreen( )->display( ).

" CDS view
cl_salv_gui_table_ida=>create_for_cds_view( iv_cds_view_name = 'ZI_SALESORDER'
)->fullscreen( )->display( ).

" CDS view with parameters
DATA(lo_cds) = cl_salv_gui_table_ida=>create_for_cds_view( 'ZC_CUSTOMERORDERS' ).
lo_cds->set_view_parameters( VALUE #( ( name = 'P_CUSTNO' value = lv_kunnr ) ) ).
lo_cds->fullscreen( )->display( ).

Full example – selection conditions, field catalog, toolbar, double click

REPORT zr_alv_ida_demo.
TABLES kna1.
SELECT-OPTIONS so_kunnr FOR kna1-kunnr.

CLASS lcl_handler DEFINITION.
PUBLIC SECTION.
METHODS on_double_click FOR EVENT double_click OF if_salv_gui_table_display_opt
IMPORTING ev_field_name eo_row_data.
ENDCLASS.

CLASS lcl_handler IMPLEMENTATION.
METHOD on_double_click.  " customer → his sales orders in a 2nd IDA
DATA ls_kna1 TYPE kna1.
IF ev_field_name <> 'KUNNR'.
MESSAGE 'Please double-click on the customer number' TYPE 'S'.
RETURN.
ENDIF.
TRY.
eo_row_data->get_row_data( IMPORTING es_row = ls_kna1 ).
DATA(lo_orders) = cl_salv_gui_table_ida=>create( iv_table_name = 'VBAK' ).
lo_orders->set_select_options(
io_condition = lo_orders->condition_factory( )->equals( name  = 'KUNNR'
value = ls_kna1-kunnr ) ).
lo_orders->fullscreen( )->display( ).
CATCH cx_salv_ida_contract_violation cx_salv_ida_sel_row_deleted
cx_salv_db_connection cx_salv_db_table_not_supported
cx_salv_ida_unknown_name cx_salv_ida_condition_invalid
cx_salv_ida_associate_invalid INTO DATA(lx_ida).
MESSAGE lx_ida TYPE 'I'.
ENDTRY.
ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
TRY.
DATA(lo_alv) = cl_salv_gui_table_ida=>create( iv_table_name = 'KNA1' ).

" 1 Selection conditions – filtering runs in the database
DATA(lo_ranges) = NEW cl_salv_range_tab_collector( ).
lo_ranges->add_ranges_for_name( iv_name = 'KUNNR' it_ranges = so_kunnr[] ).
lo_ranges->get_collected_ranges( IMPORTING et_named_ranges = DATA(lt_ranges) ).
lo_alv->set_select_options(
it_ranges    = lt_ranges
io_condition = lo_alv->condition_factory( )->equals( name = 'LAND1' value = 'DE' ) ).

" 2 Field catalog – header text, no sort / filter, hide fields
DATA(lo_fcat) = lo_alv->field_catalog( ).
lo_fcat->set_field_header_texts( iv_field_name        = 'NAME1'
iv_header_text       = 'Customer name'
iv_tooltip_text      = 'Name 1'
iv_tooltip_text_long = 'Customer name (NAME1)' ).
lo_fcat->disable_sort( 'KUNNR' ).
lo_fcat->disable_filter( 'KUNNR' ).
lo_fcat->get_all_fields( IMPORTING ets_field_names = DATA(lt_fields) ).
DELETE lt_fields WHERE table_line = 'NAME2' OR table_line = 'SORTL'.
lo_fcat->set_available_fields( lt_fields ).

" 3 Toolbar – switch off printing
lo_alv->standard_functions( )->set_print_active( abap_false ).

" 4 Double click
lo_alv->display_options( )->enable_double_click( ).
DATA(lo_handler) = NEW lcl_handler( ).
SET HANDLER lo_handler->on_double_click FOR ALL INSTANCES.

lo_alv->fullscreen( )->display( ).
CATCH cx_salv_db_connection cx_salv_db_table_not_supported
cx_salv_ida_contract_violation cx_salv_ida_unknown_name
cx_salv_ida_condition_invalid cx_salv_ida_associate_invalid
cx_salv_call_after_1st_display cx_salv_function_not_supported INTO DATA(lx_error).
MESSAGE lx_error TYPE 'I'.
ENDTRY.

Object

Get it with

Used for

IF_SALV_GUI_TABLE_IDA

cl_salv_gui_table_ida=>create( ) / create_for_cds_view( )

Main ALV object

IF_SALV_GUI_FIELD_CATALOG_IDA

lo_alv->field_catalog( )

Header texts, sort/filter, visible fields

IF_SALV_GUI_STD_FUNCTIONS_IDA

lo_alv->standard_functions( )

Toolbar functions (print, export …)

IF_SALV_IDA_CONDITION_FACTORY

lo_alv->condition_factory( )

Conditions: equals, between, and, or …

CL_SALV_RANGE_TAB_COLLECTOR

NEW cl_salv_range_tab_collector( )

Turn select-options into named ranges

IF_SALV_GUI_TABLE_DISPLAY_OPT

lo_alv->display_options( )

Double click, zebra, title

Restrictions

  • Data is read again on every interaction: rows changed or deleted meanwhile are not handled (deleted rows show as empty lines).
  • Totals of amounts / quantities only for one currency / unit; avoid STRING fields; at most about 2 billion cells.
  • No editable cells, no background (batch) processing for in-container display – SAP GUI only.
  • Modern Fiori world: the equivalent is a Fiori elements list report on a CDS / RAP service (see the RAP section).

Part 12 – ABAP SQL vs CDS vs AMDP vs ADBC: which one when?

Choosing between ABAP SQL, CDS view entity, AMDP and ADBC

ABAP SQL

CDS view entity

AMDP

ADBC

What

SQL statements in ABAP code

Declarative data model (DDL) + annotations

SQLScript procedure / function in an ABAP class

Native SQL text via classes

Reuse

Inside one program

Everywhere: ABAP SQL, OData, RAP, analytics

Via class / CDS table function

Inside one program

DB independent

Yes

Yes

No (HANA)

No

Writes data

Yes (DML)

No (read-only; CUD via RAP behaviour)

Yes, but avoid

Yes

Authorization

AUTHORITY-CHECK in code

CDS access control (DCL), automatic

Manual

Manual

ABAP Cloud

Yes

Yes

Yes

No

Typical use

Program-specific reads, all updates

VDM, Fiori / RAP, reports used by many

Multi-step logic, several result sets, HANA functions

Secondary DB, non-DDIC objects

Rule of thumb (SAP Press): need data only in one development object → ABAP SQL; needed across objects with one result set → CDS view; several result sets or procedural logic → AMDP. ADBC only when none of these can reach the data.

Part 13 – Interview questions

Q1. Open SQL (ABAP SQL) vs native SQL?

ABAP SQL is part of ABAP: checked at compile time, database-independent, automatic client handling, uses the table buffer, translated by the DB interface. Native SQL (EXEC SQL / ADBC) is passed unchanged to the database: DB-specific, no compile-time check, no buffer, manual client handling.

Q2. Why the @ in front of variables, and what is strict mode?

@ marks host (ABAP) variables so the parser can tell them from column names. Using any new feature puts the statement in strict mode: comma lists, @ and INTO at the end become mandatory.

Q3. When was Open SQL renamed?

In 7.53 (S/4HANA 1809) it became ABAP SQL.

Q4. FOR ALL ENTRIES or JOIN on HANA?

Prefer a JOIN (or a join with @itab, 7.52): one statement, aggregates possible. FAE pitfalls: empty driver table reads everything, duplicates are removed, no aggregates.

Q5. UNION vs UNION ALL?

UNION (= DISTINCT) removes duplicates, which costs extra work. UNION ALL keeps all rows and is faster. Both need the same number of compatible columns; names come from the first SELECT.

Q6. What is NULL and how do you handle it?

NULL = no value (e.g. outer-join columns without partner); it is not the initial value. In ABAP it arrives as initial. Handle it in SQL with IS [NOT] NULL and coalesce( ).

Q7. WHERE vs HAVING?

WHERE filters single rows before grouping; HAVING filters groups after GROUP BY and can use aggregates.

Q8. Window expression vs GROUP BY?

GROUP BY collapses rows into one row per group. OVER( PARTITION BY … ) computes the aggregate per window but keeps every row – e.g. item value next to order total, ranks, running totals (7.54+).

Q9. What is a CTE?

A named subquery (WITH +name AS ( SELECT … ), 7.51) that lives only for one statement – used for subtotals and multi-step queries without temporary tables.

Q10. What are the risks of ADBC?

SQL injection if strings are concatenated (bind with ?), missing client filter, no syntax check, no buffer, DB-specific SQL, not ABAP Cloud. Use it only for secondary DB connections or non-DDIC objects.

Q11. ALV with IDA vs classic ALV?

Classic ALV needs all data in an internal table. IDA reads only the visible rows and runs sorting, filtering and totals as SQL in the database – fast and memory-friendly for millions of rows. SAP GUI only.

Q12. When ABAP SQL, CDS, AMDP?

ABAP SQL for program-specific access and all updates; CDS for reusable, semantically rich read models (Fiori, RAP, analytics, DCL); AMDP for logic SQL/CDS cannot express or several result sets.

Q13. USING CLIENT vs CLIENT SPECIFIED?

Both read another client. USING CLIENT '100' (7.40 SP05) is the modern form and keeps automatic client handling for that one client; CLIENT SPECIFIED is obsolete.

🏠 Start Here · ◀ 03 · ABAP New Syntax · 05 · CDS Views ▶ · Sections: CORE ABAP | OOPS ABAP | ABAP on HANA | Clean Core | RAP | ABAP Points | SAP Fiori | SAPUI5 | Mobile Development (MDK) | BTP Foundations | BTP Development | CAP | SAP Build | ABAP on BTP | Integration Suite | SAP Business AI | SAP BASIS | Security | SAP SDLC

Functional: FICO ABAP | TRM ABAP | VIM | SAP BIS | SD ABAP | MM ABAP | PP ABAP | QM ABAP | PM ABAP | PS ABAP | EWM | TM ABAP | GTM ABAP | EHS ABAP | HR ABAP | BW | SAP Datasphere | SAP Business Data Cloud | SAP MDG | SAP Analytics Cloud | SAP Ariba | SAP CX | SAP IBP