ABAP SQL: Writing Data

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Sooner or later a program has to keep something: a new expense claim item, a corrected amount, a claim that was withdrawn. In ABAP the persistent place is a database table, and four statements change it: INSERT adds rows, UPDATE changes rows, MODIFY adds or changes rows in one step, and DELETE removes rows. Together they are the "writing" half of ABAP SQL, the SQL dialect built into the language. This page explains each statement for a single row and for a whole internal table, the two system fields that report what happened, why a change is not permanent until a commit, and why new development in ABAP Cloud does not write business data table by table but goes through RAP business objects. It is written against Standard ABAP release 8.16 and ABAP for Cloud Development release 9.20 (2608). The four statements are part of both language versions and work in classic Standard ABAP, on premise, and in the Public Edition alike; the sections on SAP LUWs and COMMIT WORK describe how classic ABAP works, and the section on RAP describes how ABAP Cloud works.

Before you read

  • Internal Tables: the bulk forms of the statements take an internal table.

  • Constructor Expressions: VALUE builds the rows to write inside the statement.

  • Data Types and Data Objects: work areas and structures.

  • Reading data with SELECT has a page of its own, ABAP SQL: Reading Data, that comes earlier in this section; this page uses SELECT only to show the result of a write.

Key terms

  • ABAP SQL: the SQL statements of the ABAP language, which the runtime passes to the database.

  • Writable database object: a database table or CDS entity that INSERT, UPDATE, MODIFY and DELETE are allowed to change.

  • Bulk access: one statement that handles many rows, for example from an internal table, instead of one statement per row.

  • Database LUW: a sequence of database changes that the database either completes in full at a commit or undoes in full at a rollback.

  • SAP LUW: a logical unit of work that spans several database LUWs and is ended by COMMIT WORK.

  • sy-subrc: the system field that holds the return code of the last statement, 0 for success.

The four statements

Think of a database table as a list of rows that each have a key, the way a ledger has one line per entry. The four statements correspond to the four things you do to such a ledger.

Statement What it does Row source

INSERT

Adds new rows. A row whose primary key already exists is not added.

A work area, an internal table, or a subquery

UPDATE

Changes existing rows, either named columns of all rows that match a WHERE condition, or whole rows identified by their key.

SET expressions, a work area, or an internal table

MODIFY

Adds a row when its key does not exist and overwrites the row when it does.

A work area or an internal table

DELETE

Removes rows, either those that match a WHERE condition or those whose key is given.

A condition, a work area, or an internal table

The target of each statement, written writable_obj in the Keyword Documentation, can be a CDS table entity, a writable CDS view entity or a DDIC database table. It is written with the exact name that was defined for it, without a database schema prefix. The examples on this page use a DDIC database table named ZEXP_ITEM with the key columns CLAIM_ID and ITEM_NO and the plain columns CATEGORY and AMOUNT: one row per item of an expense claim. In the local playground the table comes from an abapGit .tabl.xml file; on an SAP system you create it in ADT or SE11.

Inserting rows

INSERT has a form for one row and a form for many. The single-row forms take a work area, which is a structure that holds one row. INSERT INTO target VALUES @wa and INSERT target FROM @wa behave the same and differ only in syntax; a host expression such as @( VALUE #( ... ) ) may stand in for the work area. The bulk form, INSERT target FROM TABLE @itab, inserts every row of an internal table with one statement. The @ in front of a data object marks it as a host variable, a program variable passed into the SQL statement. A fourth form takes the result of a subquery, INSERT target FROM ( SELECT ... ), and copies rows from one table into another without passing through the program.

What happens when a row with the same key already exists depends on the form.

  • With a work area, nothing is inserted and sy-subrc is set to 4.

  • With an internal table, the statement raises an exception, because part of the table may already be written. The addition ACCEPTING DUPLICATE KEYS changes that: the rows without a clash are inserted, the others are skipped, and sy-subrc is 4 when at least one row was skipped.

  • With a subquery, a clash always raises the catchable exception CX_SY_OPEN_SQL_DB.

The addition is the right tool when skipping duplicates is acceptable, for example when a load is repeated. When a duplicate means a mistake in the program, let the exception happen and handle it.

The sy-subrc after a successful bulk insert is 0, also when the internal table is empty. After every INSERT, sy-dbcnt holds the number of rows that were inserted.

Updating rows

UPDATE has two shapes. The first changes columns: UPDATE target SET col1 = value1, col2 = value2 WHERE condition. The right-hand side may be an expression that uses the column’s old value, as in amount = amount + 5. Without a WHERE condition every row of the table, in the current client, is changed, so a missing condition is a mistake to look for in a review. The second shape overwrites whole rows from data: UPDATE target FROM @wa for one row and UPDATE target FROM TABLE @itab for many. The key in the work area or in each table row says which database row is overwritten, and every non-key column is overwritten with the program’s value, including columns the program left empty. When only some columns should change, use SET.

sy-subrc is 0 when at least one row was changed (with SET), when the named row was changed (with a work area) or when all rows of the table were changed. It is 4 when no row matched, or when the change would create a duplicate primary key. The content of key columns can be changed with SET only when no search help is linked to the table. sy-dbcnt holds the number of rows that were changed, which is the way to find out how many rows a WHERE condition hit.

Modifying rows

MODIFY target FROM @wa and MODIFY target FROM TABLE @itab combine the two previous statements: each row whose key exists overwrites the database row, and each row whose key does not exist is inserted. It saves a read when the program does not know whether a row is already there, for example when it receives a full set of items from outside and wants the table to hold exactly those values.

Two cautions apply. As with UPDATE FROM, all non-key columns are overwritten. And MODIFY hides the difference between "new" and "changed", which also hides a program error: if a row should always exist, UPDATE reports a missing row with sy-subrc 4 while MODIFY silently creates it. sy-subrc after MODIFY is 0 when every row was inserted or modified, and sy-dbcnt is the number of processed rows.

Deleting rows

DELETE FROM target WHERE condition removes all rows that match; without WHERE it removes all rows of the current client, which is why that form is rare in application code. DELETE target FROM @wa and DELETE target FROM TABLE @itab remove the rows with the keys given in the work area or the table. The sy-subrc is 0 when at least one row was deleted (with a condition) or when all named rows were deleted, and 4 when none was deleted or, for an internal table, when not all rows were. sy-dbcnt is the number of deleted rows.

Example: insert claim items from an internal table

The report below builds three items of claim C-1001 in an internal table and writes them with one INSERT FROM TABLE statement. It then inserts the same table again to show the exception for a duplicate key, repeats it with ACCEPTING DUPLICATE KEYS, inserts a single row, and finishes with UPDATE, MODIFY and DELETE. Each step prints its sy-subrc. The last lines read the table back with SELECT. The table ZEXP_ITEM stores whole currency units in AMOUNT, to keep the example short.

This listing runs in the local playground (the open-abap lab with a ZEXP_ITEM table definition added to its src folder). The system field sy-dbcnt and the form DELETE ... FROM @wa are left out because the playground does not support them correctly; they are shown in the next section and are not run here.

REPORT zp_wr.

TYPES ty_items TYPE STANDARD TABLE OF zexp_item WITH EMPTY KEY.

DATA(items) = 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-1001' item_no = 3 category = 'HOTEL'  amount = 210 ) ).

" 1 insert a whole table
INSERT zexp_item FROM TABLE @items.
WRITE / |insert table: subrc { sy-subrc }|.

" 2 insert the same keys again: the exception is catchable
TRY.
    INSERT zexp_item FROM TABLE @items.
  CATCH cx_sy_open_sql_db.
    WRITE / 'insert again: duplicate key, exception caught'.
ENDTRY.
INSERT zexp_item FROM TABLE @items ACCEPTING DUPLICATE KEYS.
WRITE / |accepting duplicates: subrc { sy-subrc }|.

" 3 single row
DATA(item) = VALUE zexp_item( claim_id = 'C-1002' item_no = 1 category = 'TAXI' amount = 18 ).
INSERT zexp_item FROM @item.
WRITE / |insert row: subrc { sy-subrc }|.

" 4 update: one column, rows chosen by a condition
UPDATE zexp_item SET amount = amount + 5 WHERE claim_id = 'C-1001' AND category = 'MEALS'.
WRITE / |update: subrc { sy-subrc }|.
UPDATE zexp_item SET amount = 0 WHERE claim_id = 'NONE'.
WRITE / |update no match: subrc { sy-subrc }|.

" 5 modify: one existing row is overwritten, one new row is inserted
MODIFY zexp_item FROM TABLE @( VALUE ty_items(
  ( claim_id = 'C-1001' item_no = 1 category = 'TRAVEL' amount = 99 )
  ( claim_id = 'C-1002' item_no = 2 category = 'PARKING' amount = 7 ) ) ).
WRITE / |modify: subrc { sy-subrc }|.

" 6 delete
DELETE FROM zexp_item WHERE claim_id = 'C-1002' AND category = 'TAXI'.
WRITE / |delete: subrc { sy-subrc }|.
DELETE FROM zexp_item WHERE claim_id = 'C-1001' AND item_no = 3.
WRITE / |delete item 3: subrc { sy-subrc }|.

SELECT claim_id, item_no, category, amount FROM zexp_item ORDER BY claim_id, item_no INTO TABLE @DATA(result).
WRITE / |rows: { lines( result ) } subrc { sy-subrc }|.
LOOP AT result INTO DATA(r).
  WRITE / |{ r-claim_id } { r-item_no } { r-category } { r-amount }|.
ENDLOOP.

The run prints the following.

insert table: subrc 0
insert again: duplicate key, exception caught
accepting duplicates: subrc 4
insert row: subrc 0
update: subrc 0
update no match: subrc 4
modify: subrc 0
delete: subrc 0
delete item 3: subrc 0
rows: 3 subrc 0
C-1001 1 TRAVEL 99
C-1001 2 MEALS 40
C-1002 2 PARKING 7

Read the result against the statements: item 1 was overwritten by MODIFY (120 became 99), the meals amount went from 35 to 40 through UPDATE, the MODIFY also created C-1002 item 2, and the taxi row and item 3 are gone. On an SAP system, ADT would print the same lines through out->write( ... ) in a class that implements if_oo_adt_classrun instead of WRITE.

Forms that report the number of rows

The next listing uses the forms that the playground does not run correctly, and reads sy-dbcnt. It requires an SAP system; not run here.

" whole rows from a table, by key
UPDATE zexp_item FROM TABLE @( VALUE ty_items(
  ( claim_id = 'C-1001' item_no = 2 category = 'MEALS' amount = 41 ) ) ).
WRITE / |rows changed: { sy-dbcnt }|.      " 1 on success

" rows named by key, not by condition
DELETE zexp_item FROM TABLE @( VALUE ty_items(
  ( claim_id = 'C-1002' item_no = 2 ) ) ).
WRITE / |rows deleted: { sy-dbcnt }|.

" a condition that matches several rows: sy-dbcnt says how many
UPDATE zexp_item SET amount = amount + 1 WHERE claim_id = 'C-1001'.
WRITE / |rows changed: { sy-dbcnt }|.

Single rows or the whole table

The Keyword Documentation says that when many rows change, bulk access through internal tables generally performs better than individual statements. Every statement is a round trip between the application server and the database, so a loop with one INSERT per row pays that trip once per row. The performance notes give the same rule for reads: use mass operations instead of single operations, and do not place ABAP SQL statements inside loops. Collect the rows in an internal table first and write them with one INSERT FROM TABLE, UPDATE FROM TABLE, MODIFY FROM TABLE or DELETE FROM TABLE.

Client handling

Most application tables have a client column as the first key field. ABAP SQL handles it for you. The statements that write from a work area, an internal table or a subquery ignore the client column of the data and set the client of the current logon instead, so a program normally writes only into its own client. SET and WHERE conditions cannot name the client column either. You do not write sy-mandt into your rows. The table ZEXP_ITEM in the playground has no client column, so the listings above never show it.

When does a change become permanent

A write statement does not make its change final. The rows go into the database, but they can still be undone, and they hold a database lock until the end of the unit of work. Two units of work matter.

A database LUW (LUW stands for logical unit of work) is a sequence of database operations that the database finishes completely or not at all. It ends with a database commit, which makes the changes permanent, or with a database rollback, which undoes all changes since it started. In between, the isolation level decides whether other users can read the changed rows. While a transaction is open, the statements INSERT, UPDATE, MODIFY and DELETE also hold an exclusive lock on the rows they touched until the commit or rollback.

A classic ABAP program usually runs across several work processes, for example when a screen is shown to the user, and every switch of work process causes an implicit database commit. A program that spans more than one dialog step is therefore not covered by one database LUW. The Keyword Documentation says this directly: for consistent storage in application programs the implicit database LUWs are normally not enough, and an explicit SAP LUW, which normally contains several database LUWs, has to be programmed. In an SAP LUW the change statements are not executed directly. They are registered first, for example as update function modules, and then run by a single work process in one database LUW when the program says COMMIT WORK. Ending the program without COMMIT WORK ignores the registered changes.

flowchart LR A[Program starts an SAP LUW] --> B[Dialog step 1: register changes] B --> C[Dialog step 2: register more changes] C --> D{COMMIT WORK or ROLLBACK WORK?} D -- COMMIT WORK --> E[One work process runs all registered changes in one database LUW] E --> F[Database commit: changes permanent] D -- ROLLBACK WORK --> G[Registered changes discarded] B -. implicit commit at each work process switch .-> H[Direct database writes in this step are already committed]

The following sketch shows the classic pattern. The direct writes with ABAP SQL are fine for a short report that does everything in one step. It requires an SAP system; not run here.

INSERT zexp_item FROM TABLE @items.
IF sy-subrc = 0.
  COMMIT WORK AND WAIT.     " make the changes permanent, wait until done
ELSE.
  ROLLBACK WORK.            " undo everything since the last commit
ENDIF.

Why ABAP Cloud prefers RAP business objects

In ABAP Cloud the picture changes in two ways. First, the language version limits which objects your code may name, as described in Language Versions and Released APIs: your own tables are yours to write, but the tables that belong to SAP applications are not released for it, and writing them directly would also bypass the checks and rules of the application. Second, the Keyword Documentation says that in ABAP Cloud local updates are enforced implicitly: they run in the same work process and are always synchronous, so COMMIT WORK and COMMIT WORK AND WAIT behave identically and, for ordinary code, the return code is 0.

The RAP model goes further. RAP does not introduce its own LUW concept; it applies the rules of the controlled SAP LUW and checks the transactional context for you. A RAP business object works in two phases. During the interaction phase changes are collected in a transactional buffer, where data may be in an inconsistent state. In the save sequence the framework validates the data, writes it to the database, and executes the final database commit. The documentation lists what breaks that contract. An explicit COMMIT WORK or ROLLBACK WORK in a RAP context leads to a runtime error, because the transaction handling and the commit belong to RAP alone, and with strict(2) mode in ABAP for Cloud Development a modifying database operation in the interaction phase or the early-save phase is a runtime error as well.

This is why new development changes business data through the business object and not through a table write: the object validates, determines dependent values, checks authorization and decides when to commit, once, for everybody who uses it. The statement for it is EML, the Entity Manipulation Language. The sketch below creates an item through a hypothetical business object ZI_EXP_CLAIM with an entity Item, and then triggers the save. It requires an SAP system and a behavior definition; not run here.

MODIFY ENTITIES OF zi_exp_claim
  ENTITY Item
    CREATE FIELDS ( claimid itemno category amount )
    WITH VALUE #( ( %cid = 'I1' claimid = 'C-1001' itemno = 4 category = 'TAXI' amount = 18 ) )
  FAILED   DATA(failed)
  REPORTED DATA(reported).

IF failed IS INITIAL.
  COMMIT ENTITIES.
ENDIF.

Source: ABAP RESTful Application Programming Model and ABAP Keyword Documentation: ABAP EML. The statements for transactional behavior are described under "The RAP Transactional Model and the SAP LUW" in the same guide.

Table writes with ABAP SQL stay correct and useful for your own helper tables, for loads that run outside a business object, and for tests, and COMMIT WORK and the SAP LUW still describe the classic ABAP programs you will maintain. For a business object of an application in ABAP Cloud, call the object.

Older material you may meet

  • Books and programs written before ABAP 7.40 use the short forms INSERT dbtab., UPDATE dbtab., MODIFY dbtab. and DELETE dbtab., which read the table header line or the table work area declared with TABLES, and the older INSERT dbtab FROM wa without the @. These forms are obsolete; the forms with @ on this page replace them.

  • Old code often wrote one INSERT per row inside a LOOP, and tested sy-subrc after each. Use the bulk form with an internal table instead.

  • Older code puts COMMIT WORK at the end of every report and function module as a habit. In a classic program that is how the SAP LUW is closed; in a RAP context it is forbidden.

Summary

  • INSERT adds rows, UPDATE changes rows, MODIFY adds or overwrites rows and DELETE removes rows, each for one work area or for a whole internal table.

  • sy-subrc says whether the statement did what you asked (0) or did not (4), and sy-dbcnt holds the number of rows that were inserted, changed, processed or deleted.

  • A bulk INSERT FROM TABLE raises an exception on a duplicate key unless you add ACCEPTING DUPLICATE KEYS; the single-row form sets sy-subrc to 4.

  • Write with one statement per internal table, not one statement per row in a loop.

  • A change is permanent only after a commit: a database LUW ends with a database commit, and in classic ABAP an SAP LUW ends with COMMIT WORK.

  • In ABAP Cloud, change business data through RAP business objects, which own validation, authorization and the commit.

Try it

To do this by hand, follow the guide ABAP SQL on a Local Database: it reads and changes data with ABAP SQL on a local database.