Foreign Keys, Check Tables and Indexes

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

Data in a business system is spread over many tables that point at each other: an expense claim has items, and each item must belong to a claim that really exists. The ABAP Dictionary, the system’s central catalogue of type definitions, lets you write this relationship down as a foreign key, and it lets you add an index, a lookup structure that makes searches on a table faster. A newcomer meets both as soon as a table is more than a list of rows, and both are easy to misunderstand: a foreign key in the Dictionary is a description, not a lock, and an index is a promise about speed, not about correctness. This page explains the check table and the foreign key, how to read and write the cardinality and the optional properties, which checks the Dictionary performs for you and which it does not, how a value table differs from a check table, and how and when to add a secondary index. It is written against Standard ABAP release 8.16 and ABAP for Cloud Development release 9.20 (2608), and it applies to ABAP Cloud, classic Standard ABAP, on premise and the Public Edition alike, because the Dictionary objects are the same. The running example adds a table of claim items with a foreign key to the claim table of the previous page.

Before you read

  • Database Tables and Structures: the claim table, its key, the client field and the source form of a table that this page extends.

  • Domains and Data Elements: a foreign key field needs a data element, and a domain may name a value table.

  • ABAP SQL Basics: the SELECT and INSERT statements that read and write the tables on this page.

  • ADT (Eclipse) Setup: the editor in which these definitions are written.

  • Dictionary views and search helps, which are built on foreign keys, have a page of their own that comes after this one.

Key terms

  • Foreign key: one or more fields of a table whose values must match the primary key of another table.

  • Check table: the table that holds the allowed values of a foreign key, because its primary key is the foreign key.

  • Foreign key table: the table that contains the foreign key fields and points at the check table.

  • Cardinality: how many rows on one side of a foreign key can belong to one row on the other side.

  • Value table: a table named by a domain that is only a default proposal for the check table and triggers no check.

  • Text table: a table that holds the language-dependent texts of the rows of a check table.

  • Secondary index: an extra index on a table, on fields other than the primary key, that speeds up reads on those fields.

  • Selectivity: how well the values of a field tell the rows apart; a field with many different values is selective.

Two tables that point at each other

A foreign key says: a value in this table must exist as a key in that other table. Think of the claim items of the running example. Every item carries a claim number, and that number is only meaningful when a claim with that number exists. The claim table is the one that knows the valid numbers, so the item table points at it. The Keyword Documentation names the two roles. The table that holds the allowed values is the check table. The table that carries the field to be checked is the foreign key table. The fields of the foreign key table that take part are the foreign key fields, and together they form the foreign key. They correspond to the primary key of the check table, one field to one key field, and each corresponding pair must have the same data type. A table can have several foreign keys, and the Dictionary then knows a foreign key dependency between the foreign key table and each of its check tables.

The next diagram shows the claim table and the item table with their cardinalities. One claim has any number of items, including none, and every item belongs to exactly one claim.

erDiagram ZEXP_CLAIM ||--o{ ZEXP_ITEM : "has items (claim_id)" ZEXP_CLAIM { string client PK string claim_id PK string employee_id string status } ZEXP_ITEM { string client PK string claim_id PK, FK string item_id PK int amount }

What the Dictionary checks and what it does not

This is the point where a foreign key is most often misread. The Keyword Documentation states it directly: a foreign key table usually contains only entries whose foreign key also occurs exactly once as primary key content in the check table, but the developer must consider this in writes made with ABAP SQL, because there is no automatic check. A foreign key in the Dictionary does not become a constraint that stops an INSERT. What it does is the following.

  • Input checks. On a screen field that is taken from the Dictionary field, the system checks the entered value against the check table, if the foreign key’s input check is switched on. The classic screen documentation says that this check runs only when the Foreign Key attribute is set for the input field, and that the input help and the check are not necessarily the same, so the programmer must make sure that the values the help offers will pass the check.

  • Documentation and tooling. The foreign key tells people and tools how the tables relate. The cardinality mainly serves as documentation, and for the foreign key types the Keyword Documentation says that the first two are for documentation only.

  • Consistent changes to the check table. While a table is a check table, you cannot delete one of its key fields or change their order. Its key can only be extended by appending new key fields at the end, and the existing foreign keys then become generic for the new key fields. A client field cannot be inserted later into an existing check table.

What it does not do is guard the data written by your own code. The example below runs in the local playground and shows the consequence. It has two tables, a claim table and an item table whose claim_id field would be the foreign key in a real system. The playground has no Dictionary and no foreign key, but ABAP SQL behaves the same way in a real system, as quoted above: the first INSERT stores an item whose claim does not exist and sy-subrc is 0. The program then does by hand what a careful program does, it looks the claim up first, and stores the second item only when the claim was found.

REPORT zexp_fk_demo.

DATA claim TYPE zexp_claim.
DATA item  TYPE zexp_item.

claim-claim_id = 'C-1001'.
claim-status   = 'N'.
claim-amount   = 12050.
INSERT zexp_claim FROM @claim.

item-item_id  = '0010'.
item-claim_id = 'C-9999'.
item-amount   = 4000.
INSERT zexp_item FROM @item.
WRITE / |insert item for unknown claim rc { sy-subrc }|.

SELECT SINGLE claim_id FROM zexp_claim WHERE claim_id = @item-claim_id INTO @DATA(found).
WRITE / |claim lookup rc { sy-subrc }|.

item-item_id  = '0020'.
item-claim_id = 'C-1001'.
SELECT SINGLE claim_id FROM zexp_claim WHERE claim_id = @item-claim_id INTO @found.
IF sy-subrc = 0.
  INSERT zexp_item FROM @item.
  WRITE / |insert item for known claim rc { sy-subrc }|.
ENDIF.

SELECT item_id, claim_id FROM zexp_item ORDER BY item_id INTO TABLE @DATA(items).
LOOP AT items INTO DATA(i).
  WRITE / |item { i-item_id } claim { i-claim_id }|.
ENDLOOP.

It runs in the local playground and prints the lines below. The item 0010 is stored although claim C-9999 does not exist, which is the gap the quotation from the Keyword Documentation describes.

insert item for unknown claim rc 0
claim lookup rc 4
insert item for known claim rc 0
item 0010 claim C-9999
item 0020 claim C-1001

In an application built with the ABAP RESTful Application Programming Model the same duty falls to the code you write, for example a validation that rejects an item whose claim does not exist. Associations in ABAP CDS describe the same relationship for reading, as CDS Associations and Compositions shows, but they do not check anything either.

Defining a foreign key in source code

A foreign key is written in the definition of the foreign key table. It is attached to a table field with the words WITH FOREIGN KEY, followed by an optional cardinality in square brackets, the name of the check table and a WHERE condition that pairs each key field of the check table with a field of the foreign key table. Several pairs are joined with AND. The statement can be used in DEFINE TABLE and, with the same meaning, in DEFINE STRUCTURE. Two rules from the Keyword Documentation shape the example. The check table must already exist, and the field that carries the foreign key must have its data type given by a data element: a field whose type is given directly, by a built-in type, cannot be assigned a check table. So the claim number of the running example needs a data element, here called zexp_claim_id, used by both tables, and the claim table of the previous page is read with that data element in place of the built-in type of its claim_id field. The item table follows. It requires an SAP system; not run here.

@EndUserText.label : 'Expense claim item'
@AbapCatalog.enhancement.category : #NOT_EXTENSIBLE
@AbapCatalog.tableCategory : #TRANSPARENT
@AbapCatalog.deliveryClass : #A
@AbapCatalog.dataMaintenance : #RESTRICTED
define table zexp_item {
  key client   : abap.clnt not null;
  @AbapCatalog.foreignKey.label : 'Claim of the item'
  @AbapCatalog.foreignKey.keyType : #KEY
  @AbapCatalog.foreignKey.screenCheck : true
  key claim_id : zexp_claim_id not null
    with foreign key [0..*,1] zexp_claim
      where client   = zexp_item.client
        and claim_id = zexp_item.claim_id;
  key item_id  : abap.numc(4) not null;
  amount       : abap.int4 not null;
}

The statement is modelled on SAP’s own example, which gives the table SPFLI the check table SCARR for its field CARRID. Read the item table from the top. The client field is the first key field, as on every client-dependent table. The claim_id field is the foreign key field. Its WHERE condition pairs the client field and the claim number of the check table with the same fields of the item table, so a claim is always looked up in the logon client. The five annotations above the field are the optional foreign key annotations, and the next section explains what they do. The item number makes each item unique inside its claim, and the amount is a plain field.

Notice that the foreign key field is also part of the primary key of the item table, which is the usual shape for dependent rows: the claim number plus the item number identify one item, and no item can exist without a claim number. That is a statement about the key. Whether the claim exists is the job of the foreign key.

Foreign key annotations

The annotations in front of the foreign key field set the properties of the foreign key. All are optional, and the ADT user guide recommends adding them whenever you define a foreign key.

Annotation Meaning

@AbapCatalog.foreignKey.label

The short text of the foreign key, an explanation for people that reads like documentation.

@AbapCatalog.foreignKey.keyType

The meaning of the foreign key fields in the foreign key table: #KEY when they are key fields or identify a row uniquely, #NON_KEY when they do not, and #TEXT_KEY for the key of a text table. For structures this information is documentation only.

@AbapCatalog.foreignKey.screenCheck

true switches the input value check on dynpros on, false switches it off. The check tests whether the check table contains a row with the key given by the values of the foreign key fields.

@AbapCatalog.foreignKey.messageClass and @AbapCatalog.foreignKey.messageNumber

Replace the standard message of a failed input check with a message of your own. Add them only when screenCheck is true.

The Keyword Documentation adds three more properties that the source form shows through the WHERE condition. A foreign key field can be generic, which means it is left out of the input check against the check table. A foreign key field can be given a constant value, and then the check table row found through the other fields must carry that constant in the assigned field. And the fields of an included structure can be foreign key fields: by default the including table inherits the foreign key and follows later changes to it, and this inheritance can be removed. The placeholders of a replaced message are filled with the contents of the foreign key fields assigned to the first three key fields of the check table after the client field, and the fourth with the name of the check table.

Cardinality and optionality

The cardinality of a foreign key answers two questions at once. How many rows of the check table must exist for one row of the foreign key table? And how many rows of the foreign key table may point at one row of the check table? The Keyword Documentation says that the cardinality mainly serves a documentation purpose, so the Dictionary does not enforce it on the database either. It is still worth writing down, because it is what a reader and a tool look at first. The Dictionary writes the cardinality as n:m with these values.

Side Value Meaning

n: check table rows for one foreign key row

1

Precisely one row of the check table must exist for each record of the foreign key table. The link is mandatory.

C

No rows must exist in the check table for a record of the foreign key table. The link is optional.

m: foreign key rows for one check table row

1

Precisely one row in the foreign key table must exist for each row of the check table.

C

At most one row of the foreign key table for each row of the check table.

N

At least one row of the foreign key table for each row of the check table.

CN

Any number of rows of the foreign key table for each row of the check table.

In the source form each value is written in brackets: [0..1] for C, [1..*] for N and [0..*] for CN, and SAP’s own examples write the pair as [0..*,1]. The ADT user guide explains that the first number counts the records of the surrounding foreign key table for each check table row, and the second counts the check table rows for each record. So [0..*,1] in the item table says that every item has exactly one claim (optionality 1, a mandatory link) and that a claim can have any number of items. In the Dictionary’s n:m notation that is 1:CN. The Keyword Documentation page for the statement lists the allowed values of n and m in the opposite order from its own example, so when you read a definition, trust the example: the SPFLI example [0..*,1] means each flight has one airline and an airline has many flights.

Optionality is the n part of the Dictionary notation, which is the second number inside the brackets, and it is the part that changes a design. A link with exactly one check table row (1) means that every item must name an existing claim. A link marked optional with C ([0..1] in the source) means an item may exist without a claim row. The Keyword Documentation adds that defining a generic foreign key turns the cardinalities 1:m and C:m into CN:m, because several rows of the check table can then fit one dependent row; this cannot be written explicitly.

Check table, value table and fixed values

Three different things look alike to a beginner, and only one of them is a foreign key. The next table sets them side by side.

Concept What it is Does it check input?

Check table

A table assigned to a field of a foreign key table through a foreign key. The field must be typed by a data element.

Yes on dynpros, when the foreign key’s input check is on. Never in ABAP SQL.

Value table

A table named in the semantic properties of a domain. It serves as the default proposal for the check table of any field whose data element uses the domain.

No. The Keyword Documentation states that specifying a value table alone does not trigger a check.

Fixed values of a domain

A list of values or intervals stored in the domain itself.

Yes on dynpros for fields that refer to the domain; ignored in ABAP programs and for table fields.

The workflow of the classic maintenance screens makes the link between the first two concrete. When you create a foreign key on the field maintenance screen of a table, the system looks at the domain of the check field. If the domain has a value table, it offers that table as the check table and proposes the assignment of the key fields. If the domain has no value table, you enter the check table yourself. The check table must have a key field to which the domain of the check field is assigned. The screen also offers the Check required switch, the counterpart of screenCheck in the source, and a field for a message class and message number of your own.

Text tables

A check table holds codes, such as a status or a department number, and people want to see names, not codes. A text table holds those names in several languages. The Keyword Documentation says that when a foreign key has the type #TEXT_KEY, the foreign key table is handled as a text table of the check table. Its primary key must match the primary key of the check table and must contain one additional language key field of the type LANG. A check table can have only one text table, otherwise the system gives a warning when you activate. The system uses the texts, among other things, to explain the input helps on screens. The texts of the running example’s claim status, for instance, would live in a text table of the status check table.

Indexes in plain words

An index on a database table works like the index at the back of a book. Without it the database reads every row to find the ones you asked for. With an index on the field you search by, it jumps to the matching rows. The price is that the index must be updated every time a row is inserted or changed, and it takes space. The Keyword Documentation defines an index as a special structure on the database that can improve query processing time or provide additional query capabilities such as text search. There are three kinds that matter here.

  • The primary index exists for every table and consists of the key fields. It is unique, and the system creates it automatically. Each of the key fields of the claim table is already covered by it, which is why searching a claim by its number needs no extra index.

  • A secondary index is one you add on other fields. It can be unique or non-unique. A secondary index is identified by an index ID of three alphanumeric characters, and on the database its name is the table name, the delimiter ~ and the index ID. A secondary index on the claim table with the ID EMP is called ZEXP_CLAIM~EMP on the database. A short text is required for each secondary index, and the ID 0 is reserved for the primary index.

  • A fuzzy search index supports similarity search on one text column of a table in a SAP HANA column store. It is always non-unique, and ABAP SQL cannot use it yet, so a program reaches it only through AMDP or native SQL.

Indexes are also classified by how they are stored in the repository. A standard index belongs to the table and is transported with it. An extension index is a separate repository object that is transported on its own, so that another system can add an index to a table without changing the original. Index IDs that start with Y or Z are for indexes that customers add to tables delivered by SAP, IDs that start with J are for partners, and IDs that start with H are reserved for SAP HANA indexes that come from a performance analysis.

Creating a secondary index

In ADT an index is a development object of its own. You start the Table Index wizard, enter the index name in the form table name, ~ and index ID, as in the SAP example ZDMO_TABLE~007, add a description and assign a transport request. Then you open the Table Index editor, mark whether the index is unique and add the index fields in the order you want. Its properties include the options Unique Index, Index on Table Buffer only and Fuzzy Search Index. A unique index of a client-dependent table must always contain the client field. When you save, check and activate, the index is created on the database and in the ABAP table buffer, or only in the buffer when the buffer-only option is set.

For the claim table, an index that makes the question "which claims belong to this employee?" fast would be defined like this. These are the entries, written as a table because ADT edits them in the form of the editor and not as source text. They require an SAP system; not run here.

Entry Value

Index name

ZEXP_CLAIM~EMP

Description

Claims by employee

Index properties

none ticked: a non-unique index on the database

Index fields

employee_id

The ABAP code that profits from it does not mention the index. The query is an ordinary read.

SELECT claim_id, status
  FROM zexp_claim
  WHERE employee_id = @employee_id
  INTO TABLE @DATA(claims).

This listing requires an SAP system; not run here. The database optimizer decides whether the index is actually used for the query, so the choice is not part of your statement.

When to add a secondary index

An index is a trade, so SAP gives rules of thumb for it, and they are conservative.

  • Measure first. On SAP HANA with the column store, predicates are evaluated very efficiently by the database, and secondary indexes are often not necessary. An index may improve performance for large tables with a high access frequency to a column of high selectivity.

  • Prefer one field. Usually an index is defined on one column, which keeps its cost during INSERT and UPDATE low. A compound index with more than one field is for exceptional cases, for example when a single column does not have enough selectivity. The classic guidance for tables on any database says an index should have only a few fields, as a rule no more than four, because it is updated with every change of those fields.

  • Do not repeat the primary index. There is no need for an index on columns that are already part of the primary index.

  • Put the most selective field first. The order of the fields matters, and fields that are selected often and have a high selectivity belong at the beginning of the index.

  • Avoid mostly-empty fields and overlaps. A field whose value is initial for most rows should not be in an index, and several indexes on one table should not overlap.

  • Know the limits. Fields of the built-in types STRING, RAWSTRING and GEOM_EWKB cannot be index fields.

  • Mind the buffer. If table buffering with generic or full buffering is switched on, every index also results in an in-memory index for the buffered data; the buffer-only option creates the index there and not on the database.

Applied to the example: an index on employee_id of a claim table with millions of rows read all day by employee is defensible. The same index on a table of a few thousand rows is not, and an index on the status field, which has four values, is a poor candidate because those values do not tell the rows apart. Check with the database’s own tools how a statement is executed before and after you add an index, and remove an index that is not used.

Older material you may meet

  • Books and older programs create a foreign key on the SE11 field maintenance screen: you select the check field, choose the foreign key button, accept the proposal made from the domain’s value table or enter a check table, assign the key fields, and use Check required, Generic and the Constant column for what the source form writes as screenCheck, a generic field and a constant. The result is the same foreign key as in the source above. Its Semantic attributes are primarily documentation, like the cardinality that the source writes in brackets.

  • Older documentation and some ADT pages describe cardinality values with the letters 1, C, N and CN. The brackets [0..1], [1..*] and [0..*] are the same values.

  • Secondary indexes in older systems were added on the Indexes screen of the table, with a three-character ID and the radio buttons Standard Index, Fuzzy Index and Full Text Index. The full text index is deprecated for SAP HANA and cannot be created on SAP HANA Cloud; SAP recommends the fuzzy search index instead.

Summary

  • A foreign key links a field of one table, the foreign key table, to the primary key of another, the check table. The field must be typed by a data element, and each corresponding pair of fields must have the same data type.

  • ABAP SQL does not check a foreign key when it writes. The Dictionary uses the foreign key for input checks on screens and as documentation, so your own code or a RAP validation must keep the data consistent.

  • The cardinality tells how many rows belong to one row on each side; [0..*,1] means each item has exactly one claim and a claim has any number of items. It documents the relationship and does not enforce it.

  • A value table named in a domain is only a default proposal for the check table and triggers no check; a text table holds the language-dependent names of the check table’s rows.

  • The primary index is created for every table. A secondary index is added on other fields; it is named table~ID, prefers one selective field, and must be justified by measurement because it slows writes and uses space.