ABAP Interview Questions with Answers
Most Asked ABAP Interview Questions for Software Engineer Roles
Introduction
This page provides a comprehensive collection of SAP ABAP Interview Questions and Answers designed for students, fresh graduates, SAP consultants, and experienced ABAP developers preparing for technical interviews. The questions cover everything from basic ABAP syntax to advanced SAP development concepts used in enterprise applications. SAP ABAP (Advanced Business Application Programming) is the primary programming language used for developing applications inside SAP ERP systems. Companies using SAP require developers who understand Data Dictionary objects, Internal Tables, Reports, ALV, SmartForms, Module Pool Programming, BAPIs, BADIs, RFCs, performance tuning, debugging, and database optimization. Whether you are preparing for SAP implementation projects, support roles, S/4HANA migration interviews, or senior ABAP developer positions, these interview questions will help you revise important concepts with practical explanations. The questions are organized from beginner to advanced level, making this guide suitable for both freshers and experienced professionals.
Why ABAP?
- Core language for SAP systems – powers the world's leading ERP platform
- Enterprise-grade – used by thousands of companies worldwide for business-critical processes
- Rich data handling – native support for internal tables, database access, and business objects
- Strong integration capabilities – BAPIs, BADIs, RFCs, and IDocs for seamless system communication
- Performance and scalability – optimized for large‑volume transactions and reporting
- Continuous evolution – modern ABAP supports S/4HANA, CDS views, and OData services
- High demand in the job market – SAP skills are consistently sought after in enterprise IT
Most Asked ABAP Interview Questions
ABAP stands for Advanced Business Application Programming. It is a high-level programming language created by SAP used for building business applications, customization, and data processing execution modules within the SAP ecosystem environment.
ABAP lets you manage data layer interactions efficiently via built-in database tools and construct structured execution architectures like transaction monitors, screens, batch workflows, and interactive report outputs.
Key ideas in ABAP- Data Types & Dictionary: Central definitions of databases, views, and data types (SE11).
- Open SQL: DB-independent syntax that lives natively inside ABAP.
- Internal Tables: Highly efficient dynamic arrays stored directly in memory during runtime.
- Modularization: Code reuse components such as Methods, Subroutines (Forms), and Function Modules.
- Event-Driven Processing: Processing segments bound directly to runtime engine hooks.
- Deep integration with SAP enterprise application business logic layers.
- Database independence out-of-the-box via Open SQL architecture translations.
- Robust framework capabilities managing vast structures of concurrent business records.
- Backward compatibility guarantees spanning multiple decades of SAP server upgrades.
- SAP S/4HANA ERP systems, Custom transactional monitors, Global enterprise processes.
In ABAP, modularization units are functional blocks used to split up monolithic application structures into reusable, distinct blocks of logic. Think of them like LEGO blocks—each module controls a designated functional element (Methods, Subroutines, Function Modules) that can be called repeatedly.
REPORT z_welcome_message.
WRITE 'Welcome to ABAP Development'.- z_welcome_message is an executable report context.
- It outputs data directly to the user screen layout list.
- You can reuse logic paths by isolating routines using subroutines or methods.
Open SQL is a standardized subset of database manipulation commands written natively inside ABAP. It abstracts underlying vendor database layers, allowing code to operate identically whether running over SAP HANA, Oracle, or SQL Server. Modern ABAP applications feature inline data declaration tags using the @DATA(...) mechanism.
* Classical Open SQL (Older Syntax)
SELECT SINGLE name FROM zusers INTO lv_name WHERE id = '1'.
* New Open SQL Syntax (With Inline Declaration)
SELECT SINGLE name FROM zusers WHERE id = '1' INTO @DATA(lv_name).- Open SQL automatically validates object targets against the SAP Data Dictionary definitions.
- Use host variable escapes
@when matching variables within inline syntax commands. - Target variables and structures are populated in memory safely via transactional buffers.
ABAP supports two paradigms: Classical Procedural and Object-Oriented (ABAP Objects). Today, enterprise design guidelines almost exclusively mandate ABAP Objects (Classes).
CLASS lcl_airplane DEFINITION.
PUBLIC SECTION.
METHODS: display_details.
ENDCLASS.
CLASS lcl_airplane IMPLEMENTATION.
METHOD display_details.
WRITE: / 'Displaying Flight Information'.
ENDMETHOD.
ENDCLASS.- Modern ABAP Objects access system states cleanly using Methods and event triggers.
- Classical engines rely on global lifecycle include parameters and subroutines.
- Object-Oriented methods provide strict parameter checks, explicit visibility scoping, and simplified unit testing setups.
Parameters are variables used to pass external data payloads across component boundaries, such as from a calling report execution into a targeted functional block or method subroutine interface.
FORM display_user USING pv_name TYPE string.
WRITE: / 'Hello', pv_name.
ENDFORM.
PERFORM display_user USING 'Akash'.- Parameters explicitly declare value assignments via
USING,IMPORTING, orEXPORTING. - Interface signatures prevent variable reference mutations unless marked with a
CHANGINGstatement indicator. - Any typed entry configuration can be mapped: single data values, structures, or dynamic internal tables.
State represents the variable data held inside your system work process memory context at runtime. When processing values change, conditional statements steer execution flows accordingly.
State = values that change over program execution duration. Examples: loop counters, application status switches, screen configuration values, or loaded database buffers.
DATA: lv_counter TYPE i VALUE 0.
DO 5 TIMES.
lv_counter = lv_counter + 1.
WRITE: / 'Current Count:', lv_counter.
ENDDO.- State is managed inside programs using explicit
DATAinstantiation declarations. - Never manipulate structural states without safety steps—ensure index validations are performed before row mutations.
Internal data operations store transactional line values inside operational memories dynamically by populating internal work areas and appending them safely into memory index arrays.
DATA: lt_customers TYPE TABLE OF zcustomer,
ls_customer TYPE zcustomer.
ls_customer-id = '1001'.
ls_customer-name = 'Akash'.
APPEND ls_customer TO lt_customers.DATA: lt_...— initializes a collection array framework internally.ls_...— creates an individual structural work area matching layout specifications.APPEND ... TO ...— commits structural states down into targeted list structures.
The SAP Database Buffer acts as an intermediate performance layer managed in the application server instance memory. It avoids excessive overhead costs by minimizing direct calls to database disks.
- Direct physical disk operations add significant execution latency.
- The buffering model reduces network traffic between application and database layers.
- Results in faster, enterprise-grade application response times.
- Data request triggered → The system checks if table buffers contain relevant records.
- If matching buffer matrices exist, data returns instantly without hitting database engines (Cache Hit).
- If unbuffered, queries execute directly against storage rows, populating memory caches (Sync Replication).
User interface flows require tracking interactive actions like mouse clicks, menu selections, screen transitions, and button inputs. These are managed within transactional screen processing blocks.
MODULE user_command_0100 INPUT.
CASE sy-ucomm.
WHEN 'BACK' OR 'EXIT'.
LEAVE TO SCREEN 0.
WHEN 'SAVE'.
PERFORM save_data.
ENDCASE.
ENDMODULE.sy-ucomm— holds the system user command trigger code values.AT SELECTION-SCREEN— validates data entry parameter fields.AT USER-COMMAND— intercepts menu or output list clicks.PBO (Process Before Output)— configures screen states before rendering.PAI (Process After Input)— handles user interactions on a screen.
Conditional logic means routing program execution paths dynamically based on business criteria evaluations using conditional statements.
IF lv_is_logged_in = abap_true.
WRITE 'Welcome User'.
ELSE.
WRITE 'Please Login'.
ENDIF.ABAP iterates over rows in internal tables using the LOOP AT structural command. To optimize data access, tables should be defined with an explicit KEY type configuration.
INITIALIZATION.
lv_status = 'INITIALIZED'.
START-OF-SELECTION.
PERFORM fetch_data.- Table keys must match structural criteria configurations uniformly.
- Use
ASSIGNING <field_symbol>instead of copying lines to work areas to maximize performance. - Proper table keys help the runtime engine find specific records instantly.
An Include Program is a global modularization block used to group source code across files. It lets you split large programs into manageable source files without creating standalone runtime entry overheads.
* Triggered before selection screen displays
INITIALIZATION.
* Triggered when selection screen outputs (modify screen fields)
AT SELECTION-SCREEN OUTPUT.
* Triggered when core execution begins
START-OF-SELECTION.
* Triggered when database processing ends, before output list layout
END-OF-SELECTION.- Keeps application frameworks clean by separating data declarations from logic layers.
- Short syntax declaration wrapper:
INCLUDE z_my_program_top. - Include programs cannot be executed independently; they must belong to a host report or module pool.
A Field Symbol acts as a memory pointer to an existing data object. Modifying a field symbol updates the underlying data value in memory directly, without the performance cost of a copy operation.
* Modifying global data inside procedural includes without parameters
PERFORM calculate_total. " Relies heavily on globally shared structures
* Encapsulated alternative passing parameters explicitly
PERFORM calculate_total USING lv_quantity
CHANGING lv_total.- Accessing live memory allocations dynamically without copying records.
- Modifying internal table records directly during loop processing.
- Handling dynamic structure components whose types are unknown until runtime.
A structure is a data object made up of multiple fields (components) of possibly different types, grouped under one name — similar to a row in a table.
TYPES: BEGIN OF ty_employee,
id TYPE i,
name TYPE string,
dept TYPE string,
END OF ty_employee.
DATA: ls_emp TYPE ty_employee.
ls_emp-id = 1.
ls_emp-name = 'Akash'.An internal table is a dynamic, in-memory data structure that holds multiple rows of a given line type, similar to an array or list. It's one of ABAP's most powerful runtime features.
DATA: lt_employees TYPE TABLE OF ty_employee.
APPEND ls_emp TO lt_employees.
LOOP AT lt_employees INTO DATA(ls_row).
WRITE: / ls_row-name.
ENDLOOP.- Standard Table — index-based, allows duplicates, fast insert.
- Sorted Table — kept sorted by key, efficient binary search.
- Hashed Table — unique key, O(1) lookup, no linear index access.
A table type is a reusable Data Dictionary or local definition that specifies the line type and table category (standard, sorted, hashed) for internal tables.
TYPES: tt_employees TYPE STANDARD TABLE OF ty_employee WITH DEFAULT KEY.
DATA: lt_emp TYPE tt_employees.The ABAP Dictionary (transaction SE11) is where you centrally define database tables, structures, views, data elements, domains, and search helps, shared consistently across the whole system.
- Tables — physical database objects (transparent, cluster, pooled).
- Structures — reusable field groupings without physical storage.
- Views — logical combinations of one or more tables.
- Data Elements & Domains — reusable semantic and technical field definitions.
A domain defines the technical properties of a field (data type, length, value range). A data element adds business semantics (field labels, documentation) on top of a domain.
* Domain: ZDOM_STATUS (CHAR, length 1, fixed values A/I)
* Data Element: ZDE_STATUS references ZDOM_STATUS, adds field labels
* Table field: STATUS TYPE ZDE_STATUSA transparent table is a database table defined in the ABAP Dictionary that has a direct one-to-one relationship with an actual physical table in the underlying database.
- Every field corresponds directly to a database column.
- Contrast with pooled/cluster tables, which store several logical tables inside one physical database table.
A structure holds exactly one row of data (like a single record). An internal table holds multiple rows, each matching the structure's line type.
DATA: ls_emp TYPE ty_employee, " single row
lt_emp TYPE TABLE OF ty_employee. " multiple rowsA view is a virtual table that combines fields from one or more database tables, typically via a JOIN, without physically storing duplicate data.
- Database View — joins tables, read access, materialized in DB.
- Projection View — subset of fields from a single table.
- Maintenance View — allows data entry across joined tables.
A search help (F4 help) provides users with a dropdown list of valid values for an input field, improving usability and data consistency in selection screens and dialogs.
A lock object (created via SE11, prefixed EZ) prevents concurrent processes from modifying the same data record simultaneously, avoiding inconsistent updates.
CALL FUNCTION 'ENQUEUE_EZLOCK_ORDER'
EXPORTING
order_id = lv_order_id
EXCEPTIONS
foreign_lock = 1
OTHERS = 2.A function module is a reusable, named procedure with a formally defined interface (IMPORTING, EXPORTING, CHANGING, TABLES, EXCEPTIONS) that can be called from anywhere in the system, including via RFC.
FUNCTION z_get_employee_name.
*"----------------------------------------------------------------------
*" IMPORTING VALUE(IV_ID) TYPE I
*" EXPORTING VALUE(EV_NAME) TYPE STRING
*"----------------------------------------------------------------------
SELECT SINGLE name FROM zemployee INTO ev_name WHERE id = iv_id.
ENDFUNCTION.A function group is a container (like a special program) that groups related function modules together and holds their shared global data and includes.
System fields are predefined global variables maintained automatically by the runtime engine, giving access to system status, dates, and processing results.
sy-subrc— return code of the last statement (0 = success).sy-tabix— current line index of an internal table.sy-datum/sy-uzeit— current date / time.sy-uname— logged-in user ID.
The SELECT statement retrieves data from database tables into ABAP variables, structures, or internal tables.
SELECT id, name FROM zemployee
INTO TABLE @DATA(lt_employees)
WHERE dept = 'IT'.The WHERE clause filters rows returned from a database query based on specified conditions, just like in standard SQL.
SELECT * FROM zemployee INTO TABLE @DATA(lt_it_staff)
WHERE dept = 'IT' AND status = 'A'.ABAP provides built-in operators and functions for manipulating strings: concatenation, splitting, searching, replacing, and trimming.
DATA(lv_full_name) = |{ lv_first } { lv_last }|.
FIND 'Akash' IN lv_full_name.
REPLACE 'Akash' IN lv_full_name WITH 'Rahul'.CONCATENATE joins multiple strings into one; SPLIT divides a string into parts based on a separator.
CONCATENATE 'Hello' 'World' INTO DATA(lv_greeting) SEPARATED BY space.
SPLIT lv_greeting AT space INTO DATA(lv_word1) DATA(lv_word2).ABAP provides system fields and functions for working with dates and times, useful for reporting, validation, and scheduling logic.
DATA(lv_today) = sy-datum.
DATA(lv_now) = sy-uzeit.
* Adding days to a date
lv_today = lv_today + 7.CASE evaluates a single variable against multiple possible values, similar to switch statements in other languages.
CASE lv_status.
WHEN 'A'. WRITE 'Active'.
WHEN 'I'. WRITE 'Inactive'.
WHEN OTHERS. WRITE 'Unknown'.
ENDCASE.DO ... ENDDO repeats a fixed or indefinite number of times (often with a counter). WHILE ... ENDWHILE repeats as long as a condition remains true.
DO 3 TIMES.
WRITE: / 'Iteration', sy-index.
ENDDO.
WHILE lv_count < 5.
lv_count = lv_count + 1.
ENDWHILE.MESSAGE displays a system message to the user, sourced from a message class, with a type indicating severity (Information, Warning, Error, etc.).
MESSAGE 'Record saved successfully' TYPE 'S'.
MESSAGE e001(zmsg_class) WITH lv_order_id.I— InformationW— WarningE— Error (stops processing)S— SuccessA— Abort
A selection screen is a standard input screen generated automatically for report programs, using PARAMETERS and SELECT-OPTIONS to gather user input before execution.
PARAMETERS: p_dept TYPE string.
SELECT-OPTIONS: s_id FOR zemployee-id.Selection screens can include RADIOBUTTON groups (mutually exclusive choices) and AS CHECKBOX fields (independent toggles) to capture user preferences.
PARAMETERS: p_opt1 RADIOBUTTON GROUP grp1 DEFAULT 'X',
p_opt2 RADIOBUTTON GROUP grp1,
p_flag AS CHECKBOX.A Type 1 (Report) Program is a classical executable ABAP program that runs top-to-bottom, typically used for listing, extracting, or processing data, often paired with a selection screen.
A Module Pool is a dialog program consisting of screens (dynpros) and PBO/PAI processing modules, used to build interactive transaction screens rather than simple linear reports.
A transaction code is a short alphanumeric identifier that gives users direct access to a specific program, screen, or function within SAP, e.g. SE38, SE11, VA01.
Reports (Type 1) run sequentially and typically end with a list output; Module Pools (Type M) are screen/dialog-driven and require an explicit transaction code, handling multiple user interaction cycles via PBO/PAI.
OO ABAP (ABAP Objects) brings object-oriented concepts — classes, interfaces, inheritance, polymorphism — into ABAP, replacing older procedural constructs for modern, maintainable enterprise code.
A class is a blueprint defining attributes (data) and methods (behavior). Classes can be local (inside a program) or global (created via SE24/ADT, reusable system-wide).
CLASS zcl_employee DEFINITION.
PUBLIC SECTION.
METHODS: constructor IMPORTING iv_name TYPE string,
get_name RETURNING VALUE(rv_name) TYPE string.
PRIVATE SECTION.
DATA: mv_name TYPE string.
ENDCLASS.
CLASS zcl_employee IMPLEMENTATION.
METHOD constructor.
mv_name = iv_name.
ENDMETHOD.
METHOD get_name.
rv_name = mv_name.
ENDMETHOD.
ENDCLASS.An interface declares a set of method signatures without implementation. Any class that implements the interface must provide its own implementation of those methods, enabling polymorphism.
INTERFACE zif_notifier.
METHODS: send_notification IMPORTING iv_message TYPE string.
ENDINTERFACE.
CLASS zcl_email_notifier DEFINITION.
PUBLIC SECTION.
INTERFACES zif_notifier.
ENDCLASS.
CLASS zcl_email_notifier IMPLEMENTATION.
METHOD zif_notifier~send_notification.
WRITE: / 'Email sent:', iv_message.
ENDMETHOD.
ENDCLASS.Inheritance lets a subclass reuse and extend the attributes and methods of a superclass using the INHERITING FROM clause.
CLASS zcl_vehicle DEFINITION.
PUBLIC SECTION.
METHODS: display_type.
ENDCLASS.
CLASS zcl_car DEFINITION INHERITING FROM zcl_vehicle.
PUBLIC SECTION.
METHODS: display_type REDEFINITION.
ENDCLASS.Polymorphism allows different classes to be treated through a common interface or superclass reference, with each executing its own specific method implementation at runtime.
DATA: lo_vehicle TYPE REF TO zcl_vehicle.
lo_vehicle = NEW zcl_car( ).
lo_vehicle->display_type( ). " calls the Car's overridden methodEncapsulation restricts direct access to a class's internal data using visibility sections (PUBLIC, PROTECTED, PRIVATE), exposing only controlled access via public methods.
The CONSTRUCTOR method runs automatically when an object is instantiated with NEW or CREATE OBJECT, typically used to initialize attributes. A CLASS_CONSTRUCTOR runs once per class, before its first use.
DATA(lo_emp) = NEW zcl_employee( iv_name = 'Akash' ).A static method (declared with CLASS-METHODS) belongs to the class itself and can be called without an instance. An instance method requires an object reference to be created first.
CLASS zcl_util DEFINITION.
PUBLIC SECTION.
CLASS-METHODS: get_timestamp RETURNING VALUE(rv_ts) TYPE timestamp.
ENDCLASS.
DATA(lv_ts) = zcl_util=>get_timestamp( ). " no instance neededABAP Objects supports structured exception handling using TRY / CATCH / CLEANUP / ENDTRY, catching class-based exceptions raised during execution.
TRY.
lv_result = 10 / lv_divisor.
CATCH cx_sy_zerodivide INTO DATA(lo_ex).
WRITE: / 'Error:', lo_ex->get_text( ).
ENDTRY.Class-based exceptions are objects derived from the global superclass CX_ROOT (or CX_STATIC_CHECK/CX_DYNAMIC_CHECK), representing structured, typed error conditions that can carry additional attributes.
CLASS cx_insufficient_balance DEFINITION INHERITING FROM cx_static_check.
ENDCLASS.
RAISE EXCEPTION TYPE cx_insufficient_balance.ALV is a standard SAP framework for displaying tabular data in a professional, interactive grid with built-in sorting, filtering, totals, and export options — sparing developers from building custom list layouts.
CL_GUI_ALV_GRID is the classic OO ABAP class used to display and manage an interactive ALV grid embedded inside a screen container.
DATA: lo_alv TYPE REF TO cl_gui_alv_grid,
lo_container TYPE REF TO cl_gui_custom_container.
CREATE OBJECT lo_container EXPORTING container_name = 'ALV_CONTAINER'.
CREATE OBJECT lo_alv EXPORTING i_parent = lo_container.
lo_alv->set_table_for_first_display(
EXPORTING it_fieldcatalog = lt_fieldcat
CHANGING it_outtab = lt_data ).A BAPI (Business Application Programming Interface) is a standardized, released function module that provides stable, documented access to SAP business objects (e.g. creating a sales order, posting a document) — safe for external systems to call.
CALL FUNCTION 'BAPI_SALESORDER_CREATEFROMDAT2'
EXPORTING
order_header_in = ls_header
TABLES
return = lt_return.RFC is SAP's protocol for calling function modules across system boundaries — between two SAP systems, or between SAP and an external application — synchronously or asynchronously.
CALL FUNCTION 'Z_GET_EMPLOYEE_DATA'
DESTINATION 'RFC_DEST_ERP'
EXPORTING iv_id = lv_emp_id
IMPORTING es_data = ls_employee.A BADI is an object-oriented enhancement technique that lets customers implement custom logic at predefined enhancement points in standard SAP code, without modifying the original source.
CLASS zcl_im_my_badi_impl DEFINITION
PUBLIC
FINAL
CREATE PUBLIC.
PUBLIC SECTION.
INTERFACES zif_ex_my_badi.
ENDCLASS.A user exit is a predefined hook (often a subroutine call, e.g. USEREXIT_...) left by SAP in standard programs, letting customers insert custom logic at that specific point without modifying core code.
The Enhancement Framework (transaction SE18/SE19/enhancement spots) is SAP's modern extensibility mechanism, offering BAdIs, enhancement points, and implicit/explicit enhancement options directly within standard code, all upgrade-safe.
A Customer Exit (via transaction SMOD/CMOD) is an older enhancement technique that groups related exits into an enhancement, activated via a project, commonly used in classic SAP ERP releases before the modern Enhancement Framework.
An IDoc (Intermediate Document) is SAP's standard data container format used to exchange business data (orders, invoices, master data) between SAP systems or with external systems, typically via ALE.
ALE is SAP's technology for building distributed, loosely coupled business processes across multiple SAP systems, using IDocs as the message format for asynchronous data exchange.
All three are SAP form-printing technologies of increasing modernity.
- SAPscript: The oldest, text-based form tool with limited layout flexibility.
- Smart Forms: Graphical form designer, easier maintenance, generates function modules.
- Adobe Forms (Interactive Forms by Adobe): PDF-based, supports interactive/fillable forms and complex layouts.
BDC is a classic technique for automating data entry by simulating user input into standard SAP transaction screens, using a batch input session or call transaction.
PERFORM bdc_dynpro USING 'SAPMV45A' '0101'.
PERFORM bdc_field USING 'BDC_CURSOR' 'VBAK-AUART'.
PERFORM bdc_field USING 'VBAK-AUART' 'OR'.
CALL TRANSACTION 'VA01' USING lt_bdcdata MODE 'N'.LSMW (Legacy System Migration Workbench) is a tool for migrating legacy data into SAP, supporting multiple methods including batch input, direct input, BAPI, and IDoc, guided by a step-based wizard.
A transport request packages development or customizing changes made in one SAP system (e.g. Development) so they can be released and moved consistently to other systems (Quality, Production), tracked via transaction SE09/SE10.
The ABAP Debugger (classic or new debugger, accessed via /h or breakpoints) lets developers step through code execution line by line, inspect variable values, and diagnose runtime issues.
BREAK-POINT.
" or a conditional breakpoint:
BREAK-POINT ID zbreak_group.AUTHORITY-CHECK verifies whether the current user has the required authorization (via roles/profiles) to perform a specific action, based on authorization objects and fields.
AUTHORITY-CHECK OBJECT 'ZEMP_DISP'
ID 'ACTVT' FIELD '03'
ID 'DEPT' FIELD lv_dept.
IF sy-subrc <> 0.
MESSAGE 'Not authorized' TYPE 'E'.
ENDIF.A message class (transaction SE91) is a collection of numbered, language-translated messages used with the MESSAGE statement, keeping user-facing text centralized and reusable.
FOR ALL ENTRIES performs a database SELECT using the contents of an existing internal table as filter criteria, avoiding the need for a nested loop with individual SELECTs (a major performance anti-pattern).
SELECT * FROM zorderitem
INTO TABLE @DATA(lt_items)
FOR ALL ENTRIES IN @lt_orders
WHERE order_id = @lt_orders-order_id.- Always check that the driver internal table is not empty before using FOR ALL ENTRIES.
- Automatically removes duplicate WHERE values internally — be mindful when working with aggregate functions.
Open SQL supports INNER JOIN, LEFT OUTER JOIN, and others to combine rows from multiple database tables in a single query, based on matching key fields.
SELECT o~order_id, c~name
FROM zorder AS o
INNER JOIN zcustomer AS c ON o~cust_id = c~id
INTO TABLE @DATA(lt_result).A subquery is a SELECT statement nested inside another SELECT's WHERE clause, used to filter results based on the outcome of the inner query.
SELECT * FROM zemployee INTO TABLE @DATA(lt_emp)
WHERE dept_id IN ( SELECT id FROM zdept WHERE region = 'APAC' ).Issuing a SELECT statement inside a LOOP AT ('nested SELECT') causes one database round-trip per iteration and is a serious performance anti-pattern. FOR ALL ENTRIES (or a JOIN) retrieves all needed data in a single round-trip instead.
A work process is an operating-system-level process on the SAP application server that executes ABAP program logic. Types include Dialog (online user interaction), Background (batch jobs), Update, Spool, and Enqueue.
SAP lets you schedule ABAP programs to run unattended as background jobs, defined via transaction SM36 (create/schedule) and monitored via SM37 (job overview/logs), useful for batch processing and periodic reports.
SUBMIT z_nightly_report
WITH p_dept = 'IT'
VIA JOB 'Z_NIGHTLY_JOB' NUMBER lv_job_num
AND RETURN.ABAP Unit is a built-in testing framework for writing automated unit tests against ABAP classes, using test classes marked FOR TESTING and assertion methods like cl_abap_unit_assert.
CLASS ltc_calculator DEFINITION FOR TESTING.
PRIVATE SECTION.
METHODS test_addition FOR TESTING.
ENDCLASS.
CLASS ltc_calculator IMPLEMENTATION.
METHOD test_addition.
cl_abap_unit_assert=>assert_equals(
act = 2 + 2
exp = 4 ).
ENDMETHOD.
ENDCLASS.ABAP supports regular expressions for advanced pattern matching and text manipulation via statements like FIND and REPLACE with the REGEX addition, or the CL_ABAP_REGEX class.
FIND REGEX '\d{3}-\d{4}' IN lv_phone MATCH OFFSET DATA(lv_off).
REPLACE ALL OCCURRENCES OF REGEX '\s+' IN lv_text WITH ' '.CDS Views are modern, semantically rich data models defined in Data Definition Language (DDL) directly in the database layer, supporting associations, annotations, and calculations — foundational for SAP Fiori and S/4HANA.
@AbapCatalog.sqlViewName: 'ZEMPV'
define view ZI_Employee as select from zemployee {
key id,
name,
dept
}AMDP lets developers write native database procedures (e.g. HANA SQLScript) inside ABAP classes, managed by the ABAP runtime, enabling code pushdown for performance-critical calculations.
CLASS zcl_amdp_demo DEFINITION.
PUBLIC SECTION.
INTERFACES if_amdp_marker_hdb.
METHODS get_total_sales
IMPORTING iv_year TYPE i
EXPORTING ev_total TYPE p
FOR TABLE FUNCTION ztf_sales_total.
ENDCLASS.
CLASS zcl_amdp_demo IMPLEMENTATION.
METHOD get_total_sales BY DATABASE PROCEDURE FOR HDB LANGUAGE SQLSCRIPT.
ev_total := SELECT SUM(amount) FROM sales WHERE year = :iv_year;
ENDMETHOD.
ENDCLASS.Code pushdown means moving data-intensive computation (aggregation, filtering, joins) from the ABAP application layer down into the database layer (CDS Views, AMDP), taking advantage of in-memory HANA processing power and reducing data transfer.
An OData service exposes SAP data and business logic as a RESTful API following the OData protocol, consumed by Fiori apps, mobile apps, or external systems, typically built via SAP Gateway or the RAP model.
SAP Gateway is the technology layer that converts backend ABAP data models into OData services, acting as the bridge between SAP business logic and modern UI technologies like Fiori.
SAP Fiori is SAP's modern web-based UX design system for building responsive apps. On the backend, Fiori apps are powered by ABAP-based OData services (via Gateway or RAP) that expose the underlying business data and logic.
RAP is SAP's current strategic model for building Fiori-ready, OData-based business applications entirely in ABAP, using CDS views, behavior definitions, and behavior implementations, replacing older Gateway-based approaches for new development.
define behavior for ZI_Employee
alias Employee
persistent table zemployee
{
create;
update;
delete;
}Native SQL (EXEC SQL ... ENDEXEC) lets you write database-vendor-specific SQL directly, bypassing Open SQL's portability. AMDP is the modern, structured, HANA-optimized alternative that integrates cleanly with ABAP classes and supports code pushdown safely.
Table buffering configures how a Dictionary table's data is cached on the application server to reduce database access.
- Full buffering: Entire table cached — best for small, rarely-changed tables.
- Generic buffering: Buffered by a specified key prefix (partial buffering).
- Single record buffering: Only individually accessed records are cached.
SELECT ... FOR UPDATE places a database-level lock on selected rows to prevent other transactions from modifying them until the current transaction completes, ensuring data consistency.
SELECT SINGLE * FROM zorder INTO ls_order
WHERE id = lv_id
FOR UPDATE.Pessimistic locking locks a record immediately (e.g. via ENQUEUE) and holds it until the transaction finishes, blocking others. Optimistic locking allows concurrent reads and only checks for conflicts (e.g. via a timestamp/version field) at save time, offering better concurrency for less contested data.
Choosing the right internal table type dramatically affects performance for lookups and inserts.
- Standard Table: Fast append, linear/binary search lookup — good for sequential processing.
- Sorted Table: Maintains sort order automatically, efficient binary search on the key.
- Hashed Table: Constant-time key lookup, but no index-based access — best for large lookup tables.
They differ in storage, access, and key requirements.
DATA: lt_std TYPE STANDARD TABLE OF ty_row,
lt_sorted TYPE SORTED TABLE OF ty_row WITH UNIQUE KEY id,
lt_hashed TYPE HASHED TABLE OF ty_row WITH UNIQUE KEY id.- Standard tables allow duplicate entries and index-based access.
- Sorted tables require a defined key and stay automatically ordered.
- Hashed tables require a unique key and offer the fastest direct-key reads on large datasets.
Modern ABAP (7.40+) introduced constructor expressions for building values inline, reducing boilerplate DATA declarations and explicit assignments.
DATA(lo_emp) = NEW zcl_employee( iv_name = 'Akash' ).
DATA(lt_table) = VALUE tt_employees( ( id = 1 name = 'Akash' )
( id = 2 name = 'Rahul' ) ).
DATA(lv_status_text) = COND string( WHEN lv_status = 'A' THEN 'Active'
ELSE 'Inactive' ).
DATA(lv_label) = SWITCH string( lv_status WHEN 'A' THEN 'Active'
WHEN 'I' THEN 'Inactive' ).Inline declarations let you declare a variable at the point of first use with DATA(var), with the type inferred automatically, reducing the need for separate up-front DATA statements.
SELECT SINGLE name FROM zemployee INTO @DATA(lv_name) WHERE id = '1'.
LOOP AT lt_employees INTO DATA(ls_emp).
WRITE: / ls_emp-name.
ENDLOOP.A functional method is one that returns a value (via RETURNING) and can therefore be used directly inline within expressions, rather than requiring a separate CALL METHOD and result variable.
METHODS get_full_name RETURNING VALUE(rv_name) TYPE string.
" Used directly in an expression:
WRITE lo_employee->get_full_name( ).Since release 7.40, ABAP added many expression-based constructs that make code more concise and functional in style.
- Inline declarations:
DATA(...),FIELD-SYMBOL(...). - Constructor expressions:
NEW,VALUE,COND,SWITCH,REDUCE,FILTER. - String templates:
|text { variable }|. - Table expressions:
lt_table[ id = 1 ]for direct access without READ TABLE.
Asynchronous RFC (aRFC) lets you call function modules in parallel work processes using STARTING NEW TASK, splitting large workloads across multiple processes to reduce total runtime for batch-heavy jobs.
CALL FUNCTION 'Z_PROCESS_CHUNK'
STARTING NEW TASK 'TASK1'
PERFORMING return_handler ON END OF TASK
EXPORTING it_chunk = lt_chunk1.ABAP supports passing data between programs or across transaction/session boundaries using EXPORT ... TO MEMORY ID and IMPORT ... FROM MEMORY ID, a lightweight alternative to shared objects for one-off transfers.
EXPORT lv_user_id FROM lv_user_id TO MEMORY ID 'USER_CONTEXT'.
IMPORT lv_user_id TO lv_current_user FROM MEMORY ID 'USER_CONTEXT'.The Adapter/Proxy pattern wraps an external or incompatible interface (e.g. a legacy function module or external RFC) behind a clean, standardized ABAP OO interface, isolating the rest of the application from the details of the underlying system.
ABAP TDD combines ABAP Unit test classes with test doubles (via CL_ABAP_TESTDOUBLE) to isolate the class under test from its real dependencies, allowing fast, repeatable, dependency-free unit tests.
DATA(lo_double) = cl_abap_testdouble=>create( 'ZIF_EMPLOYEE_DAO' ).
cl_abap_testdouble=>configure_call( lo_double )->returning( 'Akash' ).
lo_double->get_name( 1 ).Code Inspector (SCI) and its successor ATC are static code analysis tools that check ABAP code against performance, security, and best-practice rules, commonly enforced as a quality gate before transport release.
Optimizing ABAP for SAP HANA focuses on minimizing data transferred to the application server, favoring code pushdown (CDS Views, AMDP), avoiding row-by-row processing, and leveraging HANA's in-memory columnar engine for aggregations and joins.
Classic extensibility (user exits, BAdIs, enhancements) modifies or extends on-premise ABAP systems directly. In-app extensibility uses SAP's Fiori-based key user tools within S/4HANA Cloud. Side-by-side extensibility builds separate apps on SAP BTP that consume APIs from the core system, keeping the core clean and upgrade-safe.
A simple class with a constructor and a getter method.
CLASS zcl_product DEFINITION.
PUBLIC SECTION.
METHODS: constructor IMPORTING iv_price TYPE p,
get_price RETURNING VALUE(rv_price) TYPE p.
PRIVATE SECTION.
DATA mv_price TYPE p.
ENDCLASS.
CLASS zcl_product IMPLEMENTATION.
METHOD constructor.
mv_price = iv_price.
ENDMETHOD.
METHOD get_price.
rv_price = mv_price.
ENDMETHOD.
ENDCLASS.Implementing a shared interface across two different classes.
INTERFACE zif_shape.
METHODS get_area RETURNING VALUE(rv_area) TYPE f.
ENDINTERFACE.
CLASS zcl_circle DEFINITION.
PUBLIC SECTION.
INTERFACES zif_shape.
DATA radius TYPE f.
ENDCLASS.
CLASS zcl_circle IMPLEMENTATION.
METHOD zif_shape~get_area.
rv_area = 3.14159 * radius * radius.
ENDMETHOD.
ENDCLASS.Handling a division error safely with cleanup logic.
TRY.
lv_result = lv_numerator / lv_denominator.
CATCH cx_sy_zerodivide INTO DATA(lo_ex).
WRITE: / 'Division error:', lo_ex->get_text( ).
CLEANUP.
CLEAR lv_result.
ENDTRY.Filtering rows directly within a LOOP using a WHERE condition.
LOOP AT lt_employees INTO DATA(ls_emp) WHERE dept = 'IT'.
WRITE: / ls_emp-name.
ENDLOOP.Building an internal table inline without explicit APPEND statements.
DATA(lt_employees) = VALUE tt_employees(
( id = 1 name = 'Akash' dept = 'IT' )
( id = 2 name = 'Rahul' dept = 'HR' )
).Assigning a value inline based on a condition.
DATA(lv_message) = COND string(
WHEN lv_score >= 90 THEN 'Excellent'
WHEN lv_score >= 60 THEN 'Pass'
ELSE 'Fail'
).Mapping a status code to a readable label.
DATA(lv_label) = SWITCH string( lv_status
WHEN 'A' THEN 'Active'
WHEN 'I' THEN 'Inactive'
ELSE 'Unknown'
).Combining strings using the modern string template syntax.
DATA(lv_greeting) = |Hello, { lv_name }! Today is { sy-datum DATE = USER }.|.Fetching exactly one row matching a key.
SELECT SINGLE name FROM zemployee
INTO @DATA(lv_name)
WHERE id = '1001'.Fetching multiple rows directly into an internal table.
SELECT id, name, dept FROM zemployee
INTO TABLE @DATA(lt_employees)
WHERE dept = 'IT'.Fetching order items for a set of previously-selected orders.
IF lt_orders IS NOT INITIAL.
SELECT * FROM zorderitem
INTO TABLE @DATA(lt_items)
FOR ALL ENTRIES IN @lt_orders
WHERE order_id = @lt_orders-order_id.
ENDIF.Joining orders with customer names in a single query.
SELECT o~order_id, c~name AS customer_name
FROM zorder AS o
INNER JOIN zcustomer AS c ON o~cust_id = c~id
INTO TABLE @DATA(lt_orders_with_names).Displaying an internal table as a simple ALV list using a function module.
CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'
EXPORTING
it_fieldcat = lt_fieldcat
TABLES
t_outtab = lt_employees.Creating a sales order via a standard BAPI and checking the return messages.
CALL FUNCTION 'BAPI_SALESORDER_CREATEFROMDAT2'
EXPORTING
order_header_in = ls_header
TABLES
order_items_in = lt_items
return = lt_return.
READ TABLE lt_return WITH KEY type = 'E' TRANSPORTING NO FIELDS.
IF sy-subrc = 0.
WRITE: / 'Order creation failed'.
ENDIF.Calling a custom function module with exception handling.
CALL FUNCTION 'Z_GET_EMPLOYEE_NAME'
EXPORTING
iv_id = lv_emp_id
IMPORTING
ev_name = lv_name
EXCEPTIONS
not_found = 1
OTHERS = 2.
IF sy-subrc <> 0.
WRITE: / 'Employee not found'.
ENDIF.Modifying rows in-place during a loop using a field symbol for performance.
FIELD-SYMBOLS: <fs_emp> TYPE ty_employee.
LOOP AT lt_employees ASSIGNING <fs_emp>.
<fs_emp>-status = 'A'.
ENDLOOP.Verifying a user's authorization before displaying sensitive employee data.
AUTHORITY-CHECK OBJECT 'ZEMP_DISP'
ID 'ACTVT' FIELD '03'
ID 'DEPT' FIELD ls_emp-dept.
IF sy-subrc <> 0.
MESSAGE 'You are not authorized to view this record' TYPE 'E'.
ENDIF.Submitting a report to run as a background job with selection screen values.
SUBMIT z_nightly_report
WITH p_dept = 'IT'
VIA JOB 'Z_NIGHTLY_JOB' NUMBER lv_job_num
AND RETURN.
CALL FUNCTION 'JOB_CLOSE'
EXPORTING
jobcount = lv_job_num
jobname = 'Z_NIGHTLY_JOB'
strtimmed = 'X'.A basic test class verifying a calculator method's result.
CLASS ltc_calculator DEFINITION FOR TESTING RISK LEVEL HARMLESS.
PRIVATE SECTION.
METHODS test_add FOR TESTING.
ENDCLASS.
CLASS ltc_calculator IMPLEMENTATION.
METHOD test_add.
DATA(lv_result) = 2 + 3.
cl_abap_unit_assert=>assert_equals( act = lv_result exp = 5 ).
ENDMETHOD.
ENDCLASS.A basic CDS view selecting active employees with an annotation.
@AbapCatalog.sqlViewName: 'ZEMPACTV'
@EndUserText.label: 'Active Employees'
define view ZI_ActiveEmployee as select from zemployee {
key id,
name,
dept
} where status = 'A'An AMDP method that pushes down a sum calculation to the HANA database.
CLASS zcl_sales_amdp DEFINITION.
PUBLIC SECTION.
INTERFACES if_amdp_marker_hdb.
METHODS get_total
IMPORTING iv_year TYPE i
EXPORTING ev_total TYPE p.
ENDCLASS.
CLASS zcl_sales_amdp IMPLEMENTATION.
METHOD get_total BY DATABASE PROCEDURE FOR HDB LANGUAGE SQLSCRIPT.
ev_total := SELECT SUM(amount) FROM zsales WHERE year = :iv_year;
ENDMETHOD.
ENDCLASS.A minimal behavior definition enabling standard CRUD operations for a RAP business object.
managed implementation in class zbp_i_employee unique;
strict ( 2 );
define behavior for ZI_Employee alias Employee
persistent table zemployee
lock master
{
create;
update;
delete;
field ( readonly ) id;
}Validating and cleaning up a phone number string using regular expressions.
IF lv_phone CP '+*'.
" simple pattern check
ENDIF.
FIND REGEX '^\+\d{1,3}-\d{3,10}$' IN lv_phone MATCH OFFSET DATA(lv_off).
IF sy-subrc <> 0.
WRITE: / 'Invalid phone format'.
ENDIF.
REPLACE ALL OCCURRENCES OF REGEX '[^0-9+]' IN lv_phone WITH ''.