001 ABAP CDS - Key Definition Tips
001 ABAP CDS - Key Definition Tips
KEY is used to define the current element as a key element of the current CDS entity.
Any elements of a SELECT list can be defined as key elements that are placed without
gaps at the start of the list.
It will give syntax error “Key must be contiguous and start at the first position” if key
elements are placed with gaps or not at the start of the list
1
2
ABAP CDS on HANA
The key elements of the CDS entity are evaluated as follows if they are used as data
source of a SELECT statement in Open SQL:
• By the addition ORDER BY PRIMARY KEY in select statement. In this case, the
key elements must be defined at the start of the SELECT list of CDS entity
without any gaps. If key is not mentioned, the system will derive the key fields
implicitly from the key fields of the basis tables and the join conditions.
• In implicit access control
By default, the key elements of the CDS entity are used to document the semantics of
the data model. By default, when CDS view is activated and when it is consumed by
programs, the addition KEY is ignored.
This default setting can be overridden by using the view annotation
AbapCatalog.preservekey:
Let’s take an example to understand this concept.
Case 1)
If the annotation is not specified or specified with the value false, the key elements
defined using KEY statement in CDS entity are ignored by the SQL Database view. The
key fields of the database view, like in classic views, will be derived implicitly from the
key fields of the basis tables and the join conditions. If this is not possible, all the fields
of the database view are key fields.
2
3
ABAP CDS on HANA
For the above CDS entity, we haven’t specified any keys/ annotation
AbapCatalog.preservekey. By default, the SQL database view will derive keys from
basis tables SCARR and SPFLI and the join conditions.
Now let us explicitly define KEY fields in the CDS entity without defining the annotation
AbapCatalog.preservekey and check the database view again.
3
4
ABAP CDS on HANA
We can see there is no change in the key fields of the database view.
Case 2)
If the value true is specified for the annotation AbapCatalog.preservekey, the key
elements defined using the KEY are also used as keys of the SQL database view.
We can now see all the key fields defined using KEY in CDS entity are also keys of the
database view.
4
5
ABAP CDS on HANA
NOTE – There will be no change in the number of records fetched from the database
tables in case of changing the keys of CDS entity.
Output with CDS entity keys as CARRID, CONNID and CARRNAME
5
6
ABAP CDS on HANA
You may find the same information in our website article - https://sapyard.com/cds-part-13-key-
definition-in-cds-views/