COALESCE Expression in ABAP CDS View Entities

35 min read

Why Every ABAP Cloud Developer Should Understand COALESCE

Among all built-in CDS expressions, COALESCE is one of the most misunderstood. Many developers assume it behaves like the SQL COALESCE function that replaces any empty or missing value.

In ABAP CDS, the reality is quite different.

Most database fields never become NULL. Instead, they usually contain an initial value such as 0, an empty string, or 00000000.

COALESCE only replaces values that are truly NULL. Understanding where NULL comes from is therefore far more important than memorizing the COALESCE syntax itself.

COALESCE Expression in ABAP CDS
COALESCE replaces NULL values—not blank, zero, or initial values. In modern ABAP Cloud development, NULL most commonly originates from optional associations.
Click image to enlarge

Learning Objectives

By the end of this lesson, you'll understand what NULL really means, where it originates in ABAP CDS, why associations play such an important role, and when COALESCE should—or should not—be used in production CDS View Entities.

After Completing This Lesson You Will Be Able To

SkillDescription
Understand NULLExplain the difference between NULL and initial values.
Use COALESCE CorrectlyReplace NULL values only when appropriate.
Understand AssociationsExplain why optional associations frequently produce NULL values.
Avoid Common MistakesRecognize situations where COALESCE has no effect.
Design Better CDS ViewsHandle optional master data in a clean, production-ready manner.

What is NULL?

Before learning COALESCE, it's essential to understand what NULL actually represents.

NULL does not mean zero, blank, space, or an initial value.

NULL means:

Meaning of NULL
ABAP CDS
There is no value at all.

The value simply does not exist.

Real Project Example: Employee Example

EmployeeManager
JohnDavid
MikeNULL

Mike does not have a manager.

The value is not blank. The value is not an empty string. There is simply no related value available.

NULL is Different from Initial Values

One of the biggest misconceptions among ABAP developers is treating NULL as another initial value.

NULL vs Initial Values

Initial ValueNULL
0No value exists
Blank ('')No value exists
SpaceNo value exists
00000000No value exists

Architect Perspective

Architect Insight

Initial values exist. They simply contain a default value.

NULL is fundamentally different because the database has no value to return.

Why ABAP Developers Rarely Think About NULL

Classical ABAP does not support NULL values for normal variables.

ABAP
ABAP
DATA lv_amount TYPE p.

If no value is assigned, the variable automatically receives its initial value.

Initial Value
ABAP CDS
0

This is one of the reasons many experienced ABAP developers are surprised when they first encounter NULL handling in CDS View Entities.

💡 SAP Best Practice

Remember this simple rule:

ABAP variables become initial.
SQL expressions may become NULL.

Where Does NULL Come From in ABAP CDS?

In modern S/4HANA Public Cloud development, NULL values rarely originate from the primary data source.

Instead, they most commonly appear when CDS follows an optional relationship.

Typical Sources of NULL

SourceCan Produce NULL?
Primary Data SourceUsually No
LEFT OUTER JOINYes
Association [0..1]Yes
Association [1..1]Normally No

Architect Perspective

Most Important Concept

In modern ABAP Cloud development, you'll encounter NULL values much more frequently through optional associations than through explicit LEFT OUTER JOIN statements.

That's why understanding associations is the key to mastering COALESCE.

What is the COALESCE Expression?

The COALESCE expression returns the first expression if it contains a value. If that expression evaluates to NULL, COALESCE returns the alternative value provided as the second argument.

Syntax
ABAP CDS
coalesce( expression1, expression2 )

Parameters

ParameterDescription
expression1The expression that may evaluate to NULL.
expression2The default value returned when expression1 is NULL.

Architect Perspective

Architect Insight

COALESCE does not replace empty strings, zero, blank spaces, or other initial values.

It only replaces values that are actually NULL.

How COALESCE Works

The execution logic of COALESCE is very straightforward.

Execution Flow
ABAP CDS
Is expression1 NULL?
        │
   ┌────┴────┐
   │         │
  Yes       No
   │         │
Return      Return
expression2 expression1
Example
ABAP CDS
coalesce(
    _Product.ProductName,
    'Unknown Product'
)

Result

Product NameReturned Value
LaptopLaptop
NULLUnknown Product

Why Associations Matter

Modern ABAP Cloud development strongly encourages the use of associations instead of explicit LEFT OUTER JOIN statements in CDS View Entities.

Consequently, most NULL values encountered in production CDS Views originate from optional associations rather than the primary data source.

Association Example
ABAP CDS
association [0..1] to I_Product as _Product
    on $projection.Material = _Product.Product

The cardinality [0..1] means that a related Product record may or may not exist.

If no Product is found, every field exposed through _Product evaluates to NULL.

💡 SAP Best Practice

When working with optional master data such as Product, Customer, Supplier, Employee, or Business Partner, always consider whether a default value should be returned instead of NULL.

Practice Example 1 - Product Description

This is one of the most common production scenarios in SAP S/4HANA Public Cloud.

CDS Example
ABAP CDS
define view entity ZI_PRODUCT_INFO
  as select from I_SalesDocumentItem

  association [0..1] to I_Product as _Product
      on $projection.Material = _Product.Product
{
    key SalesDocument,

    Material,

    coalesce(
        _Product.ProductName,
        'Unknown Product'
    ) as ProductName
}

Real Project Example: Business Scenario

A Sales Order still exists, but the corresponding Product has been archived or is no longer available.

Instead of returning NULL to the Fiori application, the CDS View displays "Unknown Product", providing a better user experience.

Practice Example 2 - Customer Name

Customer Association
ABAP CDS
association [0..1] to I_Customer as _Customer
    on $projection.SoldToParty = _Customer.Customer

coalesce(
    _Customer.CustomerName,
    'Customer Deleted'
) as CustomerName

This pattern is frequently used in reporting applications where historical documents remain available even after the associated customer master data has been removed or is no longer accessible.

Practice Example 3 - Supplier Name

Supplier Association
ABAP CDS
association [0..1] to I_Supplier as _Supplier
    on $projection.Supplier = _Supplier.Supplier

coalesce(
    _Supplier.SupplierName,
    'No Supplier'
) as SupplierName

Returning a meaningful default value makes analytical reports easier to understand than exposing NULL values directly to business users.

Understanding Association Cardinality

When is COALESCE Useful?

CardinalityCan Return NULL?COALESCE Recommended?
[1..1]Normally NoUsually unnecessary
[0..1]YesYes
[0..*]Multiple recordsCannot project a single field directly

Architect Perspective

Architect Insight

COALESCE works with scalar expressions.

A to-many association ([0..*]) does not represent a single value, so an expression such as:

Code Example
ABAP CDS
coalesce(
    _Items.Material,
    'N/A'
)
is not valid because _Items.Material is not a single scalar value.

Real SAP Production Scenarios

Common Uses of COALESCE

Business ObjectDefault Value
Product'Unknown Product'
Customer'Customer Deleted'
Supplier'No Supplier'
Employee'Former Employee'
Business Partner'Deleted Business Partner'

💡 SAP Best Practice

COALESCE is particularly valuable when displaying optional master data in analytical reports and RAP applications. Returning a meaningful business description is almost always preferable to exposing NULL values directly to end users.

Common Mistakes

Although the COALESCE expression is simple, it is frequently misunderstood. Most mistakes occur because developers assume it replaces initial values instead of NULL values.

Common Mistakes

  • Using COALESCE on fields from the primary data source that can never be NULL.
  • Expecting COALESCE to replace 0, blank ('') or initial values.
  • Using COALESCE instead of CASE for business rules.
  • Applying COALESCE to to-many associations ([0..*]).
  • Adding COALESCE simply because a field is optional without understanding the data model.

Why COALESCE(NetAmount, 0) Usually Has No Effect

One of the most common mistakes is applying COALESCE to amount or quantity fields coming directly from the primary data source.

Common Mistake
ABAP CDS
coalesce(
    NetAmount,
    0
) as NetAmount

In most CDS View Entities, NetAmount is a field from the base data source. If no value exists, it usually contains its initial value rather than NULL.

Why This Doesn't Help

FieldTypical ValueCOALESCE Required?
NetAmount0.00❌ No
Quantity0❌ No
CreationDate00000000❌ No
_Product.ProductNameNULL✅ Yes

Architect Perspective

Architect Insight

Ask yourself one question before writing COALESCE:

Can this expression actually evaluate to NULL?

If the answer is no, COALESCE adds no value.

Why COALESCE(Material, 'N/A') Is Usually Unnecessary

Unnecessary COALESCE
ABAP CDS
coalesce(
    Material,
    'N/A'
) as Material

Since Material originates from the primary data source, it typically contains either a valid value or its initial value—not NULL.

In this situation, COALESCE will almost never change the returned result.

💡 SAP Best Practice

Reserve COALESCE for expressions that may actually become NULL, especially fields accessed through optional associations.

COALESCE vs CASE

Although both expressions can return alternative values, they solve different problems.

CASE vs COALESCE

CASECOALESCE
Evaluates business conditions.Checks only for NULL.
Supports multiple WHEN branches.Supports two expressions.
Ideal for classifications.Ideal for optional relationships.
Can evaluate numeric ranges.Cannot evaluate conditions.
Use CASE
ABAP CDS
case
    when NetAmount = 0 then 'Free'
    else 'Paid'
end
Use COALESCE
ABAP CDS
coalesce(
    _Product.ProductName,
    'Unknown Product'
)

Architect Perspective

Remember

CASE evaluates conditions.
COALESCE replaces NULL.
They are complementary—not interchangeable.

COALESCE with Aggregate Functions

COALESCE can also be used together with aggregate functions.

Example
ABAP CDS
coalesce(
    sum( NetAmount ),
    0
) as TotalAmount

However, there is an important detail that experienced CDS developers should understand.

Real Project Example: Grouped CDS View

In a grouped CDS View, every group already contains at least one row. Therefore, SUM() normally returns a value and not NULL.

As a result, wrapping SUM() with COALESCE is often unnecessary unless there is a realistic possibility that the aggregate expression itself can evaluate to NULL.

Performance Considerations

COALESCE is executed directly in SAP HANA as part of the SQL statement and fully participates in code pushdown.

Performance Recommendations

RecommendationReason
Use COALESCE only where NULL is possible.Keeps CDS Views clean and readable.
Prefer associations over explicit joins in ABAP Cloud.Aligns with SAP's VDM and RAP design principles.
Avoid unnecessary COALESCE expressions.Improves maintainability.
Return meaningful business values.Provides a better user experience in Fiori apps.

Interview Questions

BeginnerInterview Question

What does the COALESCE expression do?

Answer: COALESCE returns the first expression if it is not NULL; otherwise it returns the second expression.

BeginnerInterview Question

Does COALESCE replace blank values or zero?

Answer: No. COALESCE replaces only NULL values, not blank strings, spaces, zero, or other initial values.

ExperiencedInterview Question

Where do NULL values usually originate in ABAP CDS?

Answer: Most NULL values originate from optional relationships such as LEFT OUTER JOIN or associations with cardinality [0..1].

ExperiencedInterview Question

Why is COALESCE commonly used with associations?

Answer: Because optional associations may not find a matching record, causing associated fields to evaluate to NULL.

ExperiencedInterview Question

Why is COALESCE(NetAmount, 0) usually unnecessary?

Answer: NetAmount from the primary data source typically contains an initial value such as 0.00 rather than NULL, so COALESCE has no effect.

ExperiencedInterview Question

Can COALESCE be used with a [0..*] association?

Answer: No. A to-many association does not represent a single scalar value, so it cannot be passed directly to COALESCE.

ArchitectInterview Question

When should you prefer CASE over COALESCE?

Answer: Use CASE for business rules and conditional logic. Use COALESCE only when replacing NULL values.

ArchitectInterview Question

Why is COALESCE inexpensive from a performance perspective?

Answer: It is evaluated directly in SAP HANA as part of the SQL statement and therefore benefits from code pushdown.

🧩
Developer Reference

COALESCE Expression Cheat Sheet

NULL Handling • Optional Associations • SAP HANA Pushdown

This quick reference summarizes the key concepts of the COALESCE() function in ABAP CDS. It highlights where NULL values originate, when COALESCE() should be used, and common mistakes to avoid in production-ready CDS View Entities.

TopicSyntax / ValueSummary
Purposecoalesce(expr1, expr2)Returns expr2 only when expr1 is NULL; otherwise returns expr1.
Typical NULL Source[0..1] AssociationMost NULL values originate from optional associations or LEFT OUTER JOINs.
Works on Initial Values?❌ NoInitial values such as '', 0, or '00000000' are not NULL.
CASE Replacement?❌ NoCASE evaluates conditions, whereas COALESCE() only replaces NULL values.
To-Many Association❌ Not SupportedFields from [0..*] associations cannot be passed directly to COALESCE().
PerformanceSAP HANAEvaluated directly in the database as part of code pushdown.
Common UsageProduct, Customer, SupplierDisplay fallback values such as 'Unknown Product' or 'Deleted Customer'.

💡 Key Takeaway

COALESCE is not a general-purpose replacement for empty or initial values. Its sole purpose is to replace NULLexpressions with a meaningful alternative value.

In modern ABAP Cloud development, NULL values most commonly originate from optional associations rather than the primary data source. Understanding association cardinality is therefore just as important as understanding the COALESCE syntax itself.

When used appropriately, COALESCE improves the user experience by replacing missing master data with meaningful business descriptions, making RAP applications and analytical reports easier to understand.

Watch the Complete ADT Walkthrough

In the accompanying video, we'll build practical CDS View Entities using optional associations, observe how NULL values are produced, and learn when COALESCE should—and should not—be used in SAP S/4HANA Public Cloud development.