CAST Expressions in ABAP CDS View Entities

55 min read

Why Every ABAP Cloud Developer Must Master CAST

As CDS View Entities become more powerful, developers frequently work with calculated fields, CASE expressions, string functions, aggregations, arithmetic operations, RAP projections, and analytical queries. Almost all of these features eventually introduce situations where different data types need to work together.

This is where CAST becomes one of the most important expressions available in ABAP CDS.

Unfortunately, CAST is also one of the most misunderstood concepts. Many developers believe it converts business values such as currencies or units of measure, while others use it simply to remove compiler errors without understanding why those errors occurred in the first place.

In reality, CAST performs a very specific task—it changes the technical data type of an expression during query execution. Understanding this distinction is essential for building clean, maintainable, and production-ready CDS View Entities in SAP S/4HANA Public Cloud.

CAST Expressions in ABAP CDS View Entities
CAST changes the technical data type of an expression, enabling compatible calculations, comparisons, and database operations without changing the underlying business value.
Click image to enlarge

Learning Objectives

By the end of this lesson, you will have a complete understanding of how CAST works inside ABAP CDS View Entities and when it should be used in real RAP projects.

After Completing This Lesson You Will Be Able To

SkillDescription
Understand CASTExplain the purpose of CAST in ABAP CDS.
Choose Correct Data TypesIdentify when explicit datatype conversion is required.
Avoid Common MistakesRecognize situations where CAST should not be used.
Model Better CDS ViewsUse semantic data elements instead of generic technical types.
Design Production SolutionsApply CAST correctly in RAP and S/4HANA Public Cloud development.

💡 SAP Best Practice

Do not think of CAST as a function that fixes compiler errors. Instead, think of it as a design tool that allows you to explicitly communicate your intent to the CDS compiler and the SAP HANA database.

The Problem CAST Solves

Imagine you are building a reporting CDS View that combines data from Sales Orders, Billing Documents, Business Partners, and Financial Accounting.

Some fields contain numbers, some represent business identifiers, while others are amounts, quantities, dates, or character strings. Although many of these values may look similar when displayed on the screen, they are represented internally using completely different data types.

When CDS evaluates expressions, the database engine expects compatible data types. If two operands are incompatible, activation fails with a compiler error before the view can even be executed.

Real Project Example: Real Project Scenario

A reporting application displays Billing Amount, Exchange Rate, Customer Number, Company Code, and Sales Order Number in a single CDS View.

The Billing Amount participates in calculations, the Exchange Rate requires high precision, while the Sales Order Number is simply an identifier that must preserve leading zeros.

Although these values may all appear as numbers on the screen, they represent completely different business concepts and therefore use different data types internally.

Understanding these differences is the first step toward using CAST correctly.

Before Learning CAST, Understand This Important Principle

One of the biggest mistakes developers make is assuming that data types are determined by how values look on the screen.

Consider the following examples.

Looks Similar, Behaves Completely Differently

Displayed ValueBusiness MeaningTypical CDS Type
5000001234Sales OrderNUMC / Character-Based Identifier
1000Company CodeCHAR / BUKRS
12500.75Billing AmountCURR
250.500QuantityQUAN
20260715Posting DateDATS

Although all of these values may contain digits, they should never be treated as the same kind of data.

Some values identify business objects, while others represent monetary amounts, quantities, or dates. Each category follows different rules, supports different operations, and requires different handling inside CDS expressions.

Architect Perspective

Architect Insight

One of the defining characteristics of experienced SAP developers is that they think in terms of business semantics rather than simply looking at the displayed value.

A Sales Order is not a number—it is an identifier.
A Company Code is not an integer—it represents an organizational entity.
A Currency Amount is more than a decimal value—it carries monetary semantics.

Once you begin thinking this way, deciding when to use CAST becomes significantly easier.

What is CAST?

CAST is a built-in ABAP CDS expression that converts an expression from one technical data type to another during query execution.

It tells the CDS compiler and SAP HANA database how a particular expression should be interpreted while evaluating the query. CAST does not modify the data stored in the underlying database table—it only changes the data type of the result returned by the expression.

General Syntax
ABAP CDS
cast( expression as target_type )

The expression can be a database field, a literal value, a calculation, another CDS expression, or the result of a built-in function.

Components of the CAST Expression

ComponentDescription
expressionThe source value whose data type needs to be changed.
target_typeThe built-in data type or semantic data element to which the expression will be converted.

Simple CAST Examples

Let's begin with a few simple examples before looking at real-world business scenarios.

Convert a Material Number to a Character Field
ABAP CDS
cast( Material as abap.char(40) ) as Material
Convert an Exchange Rate to a High Precision Decimal
ABAP CDS
cast( ExchangeRate as abap.decfloat34 ) as ExchangeRate
Convert a Tax Percentage
ABAP CDS
cast( TaxPercent as abap.dec(5,2) ) as TaxPercentage

In each example, only the technical data type changes. The business meaning of the value remains exactly the same.

How CAST Works Internally

Many developers imagine that CAST physically changes the value stored in the database. This is not what happens.

During activation, the CDS compiler validates every expression in the projection list and determines whether the participating operands are compatible. When a CAST expression is encountered, the compiler treats the source expression as the specified target data type before passing the statement to the SAP HANA database.

The original database column is never modified. Only the result of the expression is returned using the requested data type.

How CAST Works in ABAP CDS
CAST changes the technical data type during expression evaluation. The underlying database value remains unchanged.
Click image to enlarge

CAST Evaluation Flow

The following simplified flow illustrates what happens when a CAST expression is executed.

Execution Flow
ABAP CDS
Database Field
      │
      ▼
CDS Expression
      │
      ▼
CAST Applies Target Data Type
      │
      ▼
Expression Evaluation
      │
      ▼
Result Returned

Notice that the CAST operation happens while the database evaluates the expression. It is not a post-processing step performed after the query has finished.

Architect Perspective

Architect Insight

Because CAST is evaluated inside the database engine, it fully participates in SAP HANA's code pushdown strategy. Instead of fetching data into the ABAP application server and performing conversions there, the conversion is executed directly where the data resides.

This keeps RAP applications scalable and minimizes unnecessary data transfer between the database and application layer.

CDS CAST vs ABAP Assignment

Developers coming from classical ABAP often compare CAST with moving a value from one variable to another using different data types.

Although the intention is similar, there is an important difference: CDS CAST is part of the SQL expression executed by SAP HANA, whereas ABAP assignments are executed in the ABAP application server after the database has already returned the data.

CDS CAST vs ABAP Variable Assignment

ABAP CDSABAP Class
Executed inside the databaseExecuted in the application server
Part of the SQL statementPart of ABAP program logic
Supports code pushdownOccurs after data retrieval
Optimized by SAP HANAProcessed by the ABAP runtime

💡 SAP Best Practice

Whenever a data type conversion is required as part of a CDS expression, perform it inside the CDS View Entity using CAST rather than retrieving the data first and converting it later in ABAP. This follows SAP's code pushdown principle and typically results in better performance.

Why Do We Need CAST?

At first glance, CAST may seem like a feature that is only required in complex CDS Views. In reality, almost every production-grade RAP application eventually uses CAST somewhere in its data model.

As CDS Views become more sophisticated, developers begin combining fields with different technical data types inside calculations, conditional logic, string functions, aggregate expressions, and UNION statements. These operations require compatible data types, and that is precisely where CAST becomes essential.

Common Situations Where CAST is Used

ScenarioWhy CAST is Required
CASE ExpressionsEnsure all branches return compatible data types.
Arithmetic CalculationsConvert operands into compatible numeric types.
String FunctionsConvert values into character-based data types.
Aggregate FunctionsPrepare expressions for SUM(), AVG(), and similar functions.
UNIONBoth SELECT statements must return compatible data types.
RAP Projection ViewsExpose the required data type to consuming applications.
OData ServicesReturn values using the expected technical type.

💡 SAP Best Practice

Treat CAST as part of your CDS design rather than a workaround for compiler errors. Well-designed CAST expressions make your intent explicit and improve the readability of your data model.

Real SAP Example: Sales Order Number

One of the most common misconceptions among new SAP developers is assuming that a Sales Order is a numeric value simply because it contains only digits.

Sales Order
ABAP CDS
5000001234

Although it looks like an integer, a Sales Order is not intended for mathematical calculations.

It is a business identifier. Its purpose is to uniquely identify a business document—not to participate in arithmetic expressions.

Real Project Example: Production Scenario

Imagine a Fiori application displaying thousands of Sales Orders.

The application filters, searches, sorts, and navigates using the Sales Order number, but it never performs calculations such as:

Code Example
ABAP CDS
SalesOrder + 1

Such an operation has no business meaning because document numbers are identifiers rather than measurable values.

Architect Perspective

Architect Insight

A useful habit is to ask yourself one simple question whenever you encounter a field:

"Does this value identify something, or does it measure something?"

If it identifies a business object, it is usually character-based. If it measures something such as an amount, quantity, percentage, or exchange rate, it is generally numeric.

Real SAP Example: Company Code

Consider another value that often causes confusion.

Company Code
ABAP CDS
1000

Again, the value consists entirely of digits, yet Company Code is not an integer.

It represents an organizational unit within SAP and is modeled using the semantic data element BUKRS, whose underlying technical representation is character-based.

Business Meaning vs Technical Representation

Business ObjectLooks LikeActually Represents
Sales OrderNumberBusiness Identifier
Purchase OrderNumberBusiness Identifier
Company CodeNumberOrganizational Identifier
Material NumberNumberBusiness Identifier
CustomerNumberBusiness Partner Identifier
SupplierNumberBusiness Partner Identifier

Treating these fields as numeric values can introduce incorrect assumptions into your CDS design and often results in unnecessary CAST expressions later in the development process.

Real SAP Example: Monetary Amount

Now compare the previous examples with a billing amount.

Billing Amount
ABAP CDS
12500.75 INR

Unlike a Sales Order or Company Code, this value represents a measurable amount of money. It participates in calculations, aggregations, currency conversion, and financial reporting.

Because it represents a measurable quantity, numeric operations make perfect sense.

Code Example
ABAP CDS
NetAmount * ExchangeRate

This distinction is extremely important because developers often assume that every value containing digits behaves the same way. Business semantics determine how a field should be treated—not its appearance.

💡 SAP Best Practice

Before introducing a CAST expression, first understand the business meaning of the field. CAST should solve a technical compatibility problem—not compensate for an incorrect understanding of the data.

The Most Important Rule: CAST Changes the Data Type, Not the Business Value

If you remember only one concept from this lesson, make it this one:

Architect Perspective

CAST changes the technical data type of an expression.

CAST does NOT change the business value.

This distinction is frequently misunderstood. Many developers assume that CAST performs business conversions such as changing one currency into another or converting kilograms into pounds.

It does not.

CAST simply tells the CDS compiler and SAP HANA how the expression should be interpreted while the SQL statement is being executed.

Example: Currency Amount

Consider the following billing document.

Billing Document
ABAP CDS
Net Amount : 1,000.00
Currency   : USD

A common misconception is that the following expression converts the amount into another currency.

Incorrect Assumption
ABAP CDS
cast(
    NetAmount
    as abap.curr(15,2)
) as NetAmount

This expression does not convert USD into INR.

What Actually Happens?

Before CASTAfter CAST
1,000.00 USDExactly the same business value
Same CurrencySame Currency
Only the technical type changesBusiness meaning remains unchanged

Architect Perspective

Architect Insight

Think of CAST as changing the shape of the container—not the contents inside it.

The value remains exactly the same. Only its technical representation changes during expression evaluation.

Business Conversion Requires Dedicated CDS Functions

Business conversions involve calculations based on business rules, exchange rates, or unit conversion tables. These operations are far more complex than simply changing a data type.

Choose the Correct Function

RequirementCorrect SolutionPurpose
Change technical data typeCASTTechnical conversion only
Convert USD to INRcurrency_conversion()Business currency conversion
Convert KG to LBunit_conversion()Business unit conversion
Prepare Amount for CalculationCAST (when required)Data type compatibility
Prepare Quantity for Mathematical ExpressionCAST (when required)Data type compatibility

💡 SAP Best Practice

Always ask yourself whether you are trying to change the data type or the business value.

If the business value itself must change, CAST is almost certainly the wrong solution.

Real-World Example: Finance Reporting

Real Project Example: Financial Dashboard

A finance dashboard displays invoice amounts in the company code currency while also calculating tax percentages and profit margins.

During these calculations, developers may need compatible numeric data types for arithmetic expressions.

Code Example
ABAP CDS
cast(
    NetAmount
    as abap.dec(15,2)
) as NetAmount

Here, CAST prepares the expression for calculation.

The invoice amount remains exactly the same. No currency conversion takes place.

Real-World Example: Warehouse Management

Real Project Example: Inventory Reporting

Suppose a warehouse report stores inventory quantities in kilograms.

Stored Value
ABAP CDS
250.500 KG

The following CAST expression:

Code Example
ABAP CDS
cast(
    Quantity
    as abap.quan(13,3)
) as Quantity

does not convert kilograms into pounds.

If the business requirement is to display quantities in pounds, SAP provides the dedicated CDS function:

Code Example
ABAP CDS
unit_conversion(
    quantity    => Quantity,
    source_unit => BaseUnit,
    target_unit => cast( 'LB' as abap.unit )
)

Decision Guide: Which Function Should You Use?

Technical Conversion vs Business Conversion

Business RequirementUse CASTUse Conversion Function
Change data type
Prepare values for CASE
Prepare values for arithmetic
Convert USD to EUR✅ currency_conversion()
Convert KG to LB✅ unit_conversion()
Apply exchange rate✅ currency_conversion()
Convert units of measure✅ unit_conversion()

Common Mistakes

  • Assuming CAST converts business values.
  • Using CAST instead of currency_conversion().
  • Using CAST instead of unit_conversion().
  • Thinking CAST modifies the database value.
  • Confusing technical conversion with business conversion.

Built-in Data Types vs Semantic Data Elements

Up to this point, we have used built-in data types such as abap.char(), abap.dec(), and abap.int4 as CAST targets. Although these types are perfectly valid, they are not always the best choice.

SAP provides thousands of predefined semantic data elementsthat represent real business concepts such as Company Code, Material, Customer, Supplier, Currency, and Unit of Measure.

Whenever your expression represents one of these business concepts, using the corresponding semantic data element makes your CDS model easier to understand and aligns it with SAP's Virtual Data Model (VDM).

Built-in Types vs Semantic Data Elements

Business ConceptBuilt-in TypePreferred Semantic Data Element
Company Codeabap.char(4)BUKRS
Plantabap.char(4)WERKS_D
Storage Locationabap.char(4)LGORT_D
Materialabap.char(40)MATNR
Customerabap.char(10)KUNNR
Supplierabap.char(10)LIFNR
Currencyabap.cukyWAERS
Unit of Measureabap.unitMEINS
Quantityabap.quan(13,3)MENGE_D
Sales Orderabap.numc(10)VBELN_VA
Purchase Orderabap.numc(10)EBELN

Why Semantic Data Elements Are Preferred

Consider the following two CAST expressions.

Using a Built-in Data Type
ABAP CDS
cast(
    CompanyCode
    as abap.char(4)
) as CompanyCode
Using a Semantic Data Element
ABAP CDS
cast(
    CompanyCode
    as BUKRS
) as CompanyCode

Technically, both expressions may produce values with the same length. However, they communicate very different intentions.

The first expression simply states that the result is a four-character field.

The second clearly communicates that the value represents a Company Code, preserving the business semantics of the data.

Architect Perspective

Architect Insight

Experienced SAP developers model business concepts—not just technical data types.

A developer reading BUKRS immediately understands the purpose of the field.

A developer reading abap.char(4) only knows the field contains four characters.

Real-World Example: Financial Reporting

Real Project Example: Invoice Analytics CDS

A finance reporting CDS View exposes Company Code, Billing Amount, Currency, Customer, and Material information to a Fiori analytical application.

Although Company Code could technically be exposed using abap.char(4), using BUKRS immediately tells every developer, consultant, and architect what the field represents.

This makes the CDS View easier to understand, easier to maintain, and more consistent with SAP standard interface views.

💡 SAP Best Practice

Whenever SAP already provides a semantic data element that matches your business concept, prefer it over a generic built-in data type.

CDS Type Syntax vs ABAP Class Syntax

Developers frequently move between CDS View Entities and ABAP Classes. Although the concepts are similar, the syntax differs significantly.

CDS vs ABAP Type Declaration

Business TypeCDS View EntityABAP Class
Characterabap.char(10)TYPE c LENGTH 10
Numeric Characterabap.numc(10)TYPE n LENGTH 10
Integerabap.int4TYPE int4
Packed Decimalabap.dec(15,2)TYPE p LENGTH 8 DECIMALS 2
Decimal Floatabap.decfloat34TYPE decfloat34
Stringabap.stringTYPE string
Dateabap.datsTYPE d
Timeabap.timsTYPE t
Currencyabap.cukyTYPE waers
Unitabap.unitTYPE meins

Understanding both syntaxes is important because RAP development regularly alternates between CDS View Entities and ABAP implementation classes.

Choosing the Right CAST Target

Selecting the target type is not simply about making the compiler happy. The chosen type should accurately reflect the business meaning of the resulting value.

Recommended CAST Targets

ScenarioRecommended TargetReason
Company CodeBUKRSPreserves business semantics
MaterialMATNRMatches SAP standard data model
Currency KeyWAERSClearly represents currency
Unit of MeasureMEINSMaintains unit semantics
Generic Character Dataabap.char()When no semantic element exists
Numeric Calculationabap.dec() / abap.decfloat34Suitable for arithmetic operations

Common Mistakes

  • Casting every character field to abap.char() even when a semantic data element exists.
  • Choosing target types purely based on length instead of business meaning.
  • Ignoring SAP's standard semantic data elements.
  • Assuming semantic data elements behave differently from their technical types during execution.

Real-World CAST Scenarios

In real projects, CAST is rarely used in isolation. It usually appears inside calculations, conditional expressions, reporting views, RAP projections, analytical queries, and OData services.

Let's look at some common scenarios where experienced SAP developers use CAST to create clean and production-ready CDS View Entities.

Scenario 1: Financial Reporting

Real Project Example: Billing Analytics

A finance reporting CDS View displays invoice amounts together with calculated tax percentages and profit margins.

Before participating in arithmetic calculations, the amount may need to be represented using a compatible numeric data type.

Preparing an Amount for Calculation
ABAP CDS
cast(
    NetAmount
    as abap.dec(15,2)
) as NetAmount

Notice that the invoice amount itself does not change. CAST simply prepares the expression so it can safely participate in subsequent calculations.

💡 SAP Best Practice

Use CAST to make arithmetic expressions compatible—not to perform financial calculations themselves.

Scenario 2: CASE Expressions

Every branch of a CASE expression must return compatible data types. If different branches return different types, the CDS compiler cannot determine the final result type.

Using CAST inside CASE
ABAP CDS
case
    when OverallSDProcessStatus = 'C'
        then cast( 'Completed' as abap.char(15) )
    when OverallSDProcessStatus = 'B'
        then cast( 'In Process' as abap.char(15) )
    else
        cast( 'Open' as abap.char(15) )
end as StatusText

Explicitly casting each branch makes the result predictable and avoids data type inconsistencies.

Architect Perspective

Architect Insight

CAST is commonly used inside CASE expressions because the compiler must determine a single result type for the entire expression before activation.

Scenario 3: Preparing Values for String Functions

String functions expect character-based input. If the source expression is not already compatible, CAST may be required before the function can be evaluated.

Example
ABAP CDS
upper(
    cast(
        Supplier
        as abap.char(10)
    )
) as SupplierUpper

Here, CAST ensures that the input expression is treated as character data before the UPPER() function is applied.

Scenario 4: UNION Compatibility

Both SELECT statements participating in a UNION must expose compatible data types for corresponding columns.

If one side returns a different technical type, CAST can be used to align the structures.

Simplified Example
ABAP CDS
cast(
    CompanyCode
    as BUKRS
) as CompanyCode

This ensures that both branches of the UNION expose identical technical definitions.

💡 SAP Best Practice

Whenever UNION reports data type incompatibility, review the data model first. Use CAST only after confirming that both columns represent the same business concept.

Scenario 5: RAP Projection Views

Real Project Example: Exposing Business Data

Interface CDS Views are often reused by multiple RAP Business Objects. Projection Views expose only the fields required by the consuming application.

During this projection, CAST can be used to expose the desired technical representation without modifying the underlying interface view.

Code Example
ABAP CDS
cast(
    CompanyCode
    as BUKRS
) as CompanyCode

Architect Perspective

Architect Insight

Avoid using CAST to compensate for incorrect Interface CDS design. If the source model itself is incorrect, fixing it at the Interface View level is usually preferable to repeatedly casting fields in every consuming Projection View.

Scenario 6: Preparing Data for OData Services

CDS View Entities frequently serve as the foundation for RAP services and OData APIs.

The exposed metadata depends on the data types defined in the CDS projection. CAST can therefore influence how client applications interpret the returned values.

Real Project Example: API Development

An external consumer expects a field to be exposed using a specific technical type. Instead of changing the underlying persistence object, the Projection View can expose the required representation using CAST.

Summary of Common Production Scenarios

Where CAST is Commonly Used

ScenarioPurpose of CASTTypical Usage
Financial ReportingPrepare numeric calculationsTax, Margin, Discounts
CASE ExpressionsReturn compatible result typesStatus Descriptions
String FunctionsProvide character inputUPPER(), LOWER(), CONCAT()
UNIONAlign compatible columnsCombined Reports
Projection ViewsExpose desired technical typeRAP
OData ServicesControl exposed metadataAPI Development

💡 SAP Best Practice

CAST should improve the clarity and compatibility of your CDS View. If you find yourself adding CAST to almost every field, it's often a sign that the underlying data model should be reviewed.

Advanced CAST Usage

Up to this point, we have used CAST in relatively simple expressions. In production CDS Views, however, CAST is frequently combined with arithmetic operations, aggregate functions, CASE expressions, and layered VDM models.

Understanding these advanced scenarios helps you design CDS View Entities that are easier to maintain, easier to extend, and better optimized for SAP HANA.

Using CAST in Arithmetic Expressions

Arithmetic expressions require compatible numeric data types. Depending on the source fields, CAST may be required before the calculation can be evaluated correctly.

Preparing an Amount for Calculation
ABAP CDS
cast(
    NetAmount
    as abap.dec(15,2)
) * ExchangeRate as ConvertedAmount

In this example, CAST ensures that the first operand participates in the multiplication using the required numeric representation.

Real Project Example: Financial Analytics

A reporting CDS View calculates gross profit, discounts, taxes, and profit margins. These calculations often combine values originating from different business objects and technical types.

Explicit CAST expressions make the calculation easier to understand and reduce the likelihood of compiler errors caused by incompatible operand types.

Using CAST with Aggregate Functions

Aggregate functions such as SUM(), AVG(), MIN(), and MAX() operate on compatible data types.

Depending on the source expression, CAST may be used before applying the aggregate function.

Aggregate Example
ABAP CDS
sum(
    cast(
        NetAmount
        as abap.dec(15,2)
    )
) as TotalNetAmount

Architect Perspective

Architect Insight

CAST is generally applied before the aggregation so that the database performs the calculation using the intended data type.

Using CAST with GROUP BY and HAVING

CAST is often used together with aggregated CDS Views. However, developers should remember that CAST does not remove the normal SQL rules governing GROUP BY and HAVING clauses.

Real Project Example: Sales Summary Report

A CDS View groups Billing Documents by Company Code and calculates the total billing amount for each company.

Code Example
ABAP CDS
sum(
    cast(
        NetAmount
        as abap.dec(15,2)
    )
) as TotalAmount

The CAST expression prepares the amount for aggregation, while the GROUP BY clause still controls how the records are grouped.

💡 SAP Best Practice

Think of CAST and GROUP BY as solving two different problems. CAST controls the data type of an expression, whereas GROUP BY determines how rows are aggregated.

Why Can't You Reuse an Alias?

One of the most common questions asked by CDS developers is why an alias defined earlier in the projection list cannot be referenced by another expression in the same SELECT statement.

This Does Not Work
ABAP CDS
cast(
    NetAmount
    as abap.dec(15,2)
) as Amount,

cast(
    Amount
    as abap.char(20)
) as AmountText

Although this looks perfectly reasonable, CDS activation fails because aliases are not available to other expressions within the same projection list.

Architect Perspective

Architect Insight

CDS evaluates all projection expressions in parallel rather than sequentially.

Since every expression is evaluated independently, the alias Amount does not yet exist when the second CAST expression is parsed.

Recommended Solution: Layer Your CDS Views

Instead of creating long projection lists with complex nested expressions, SAP recommends breaking the logic into multiple CDS layers.

Recommended Design
ABAP CDS
Interface View
        │
        ▼
Composite View
        │
        ▼
Projection View
        │
        ▼
Consumption / RAP Service

The first layer performs calculations and creates reusable aliases. Subsequent layers consume those aliases without repeating complex expressions.

Real Project Example: Production Design

An Interface CDS calculates the billing amount once. A Composite CDS performs additional calculations. Finally, the Projection View exposes the required fields to the RAP Business Object.

This layered approach keeps every CDS View focused on a single responsibility and significantly improves readability.

💡 SAP Best Practice

Whenever you find yourself repeating the same CAST expression multiple times, consider moving that calculation into a lower CDS layer instead of duplicating logic throughout the model.

Performance Considerations

CAST participates in SAP HANA's code pushdown mechanism and is generally inexpensive when used appropriately.

Nevertheless, unnecessary CAST expressions can make a CDS View more difficult to read and may indicate opportunities to simplify the underlying model.

Performance Recommendations

RecommendationReason
Cast only when necessaryAvoid unnecessary complexity.
Prefer semantic target typesImproves readability and maintainability.
Layer complex calculationsReduces duplicated logic.
Keep calculations in CDSSupports SAP HANA code pushdown.
Review the source model firstRepeated CAST expressions often indicate modelling issues.

Common Compiler Errors and How to Fix Them

Every SAP developer eventually encounters compiler errors while building CDS View Entities. Most of these errors are not caused by incorrect syntax—they occur because the participating expressions use incompatible data types.

Rather than memorizing individual error messages, it's much more useful to understand why the compiler rejects a particular expression. Once you understand the underlying type system, most CAST-related errors become straightforward to resolve.

Error 1: Function DIV - Type DECFLOAT34 Not Supported

Real Project Example: Compiler Error

Code Example
ABAP CDS
div(
    cast(
        NetAmount
        as abap.decfloat34
    ),
    10
)

Activating this CDS View results in a compiler error similar to:

Compiler Error
ABAP CDS
Function DIV:
Type DECFLOAT34 is not supported.

The DIV() function performs integer division and only supports specific numeric data types. Although DECFLOAT34 is numeric, it is intentionally excluded because DIV is designed for integer-style arithmetic.

Architect Perspective

Why does this happen?

Developers often assume that every numeric type can be used with every mathematical function.

In reality, each CDS function defines its own supported input types.

💡 SAP Best Practice

If decimal precision is required, use DIVISION() instead of DIV().

Error 2: Function MOD - Type DEC Not Supported

Real Project Example: Compiler Error

Code Example
ABAP CDS
mod(
    cast(
        NetAmount
        as abap.dec(15,2)
    ),
    10
)
Compiler Error
ABAP CDS
Function MOD:
Type DEC is not supported.

MOD() calculates the remainder after integer division. Since decimal values can produce fractional remainders, CDS restricts MOD to integer-compatible data types.

Supported by MOD()

SupportedNot Supported
INT1DEC
INT2CURR
INT4QUAN
INT8DECFLOAT16

Error 3: CASE Branches Return Different Data Types

Every branch of a CASE expression must return a compatible data type.

Incorrect Example
ABAP CDS
case
    when OverallSDProcessStatus = 'C'
         then 'Completed'
    else
         NetAmount
end

In this example, one branch returns character data while the other returns a numeric amount. Since CDS cannot determine a single result type, activation fails.

💡 SAP Best Practice

Ensure every branch returns the same or a compatible data type. CAST can be used when necessary to make the result type explicit.

Error 4: CAST Combination Not Supported

Not every source type can be converted into every target type.

Example
ABAP CDS
cast(
    UUID
    as abap.char(20)
)

Depending on the source and target types, CDS may reject the conversion because no valid conversion rule exists.

Architect Perspective

Architect Insight

Always verify that the requested conversion is supported.

Just because two values can be displayed similarly does not mean CDS allows direct conversion between their technical data types.

Error 5: Alias Cannot Be Referenced

Incorrect Example
ABAP CDS
cast(
    NetAmount
    as abap.dec(15,2)
) as Amount,

cast(
    Amount
    as abap.char(20)
) as AmountText

CDS evaluates every projection expression independently. Therefore, aliases are not available to other expressions within the same projection list.

💡 SAP Best Practice

Move the first calculation into a lower CDS View and reference it from a higher layer instead of repeating the same expression.

Error 6: Confusing CAST with Currency Conversion

Real Project Example: Common Mistake

Code Example
ABAP CDS
cast(
    NetAmount
    as abap.curr(15,2)
)

Developers sometimes expect this expression to convert one currency into another.

Correct Solution

RequirementCorrect Function
Change technical data typeCAST
Convert USD to EURcurrency_conversion()
Convert KG to LBunit_conversion()

Checklist Before Using CAST

Developer Checklist

QuestionRecommendation
Am I changing the data type or the business value?If the business value changes, CAST is probably not the correct solution.
Does SAP already provide a semantic data element?Prefer semantic types such as BUKRS, MATNR, WAERS, and MEINS.
Can the calculation be moved into a lower CDS layer?Avoid repeating complex CAST expressions.
Are all participating expressions compatible?Review the source data types before introducing CAST.
Am I solving the actual problem?Don't use CAST simply to suppress compiler errors.

Common Mistakes

  • Using CAST as a workaround without understanding the compiler error.
  • Expecting CAST to perform currency or unit conversion.
  • Casting every field instead of reviewing the underlying data model.
  • Ignoring semantic data elements.
  • Creating overly complex expressions instead of layering CDS Views.

Interview Questions

The following questions are commonly asked in interviews for ABAP Cloud, RAP, S/4HANA Public Cloud, and Senior Technical Consultant roles. They test not only your understanding of CAST syntax but also your ability to make correct architectural decisions.

BeginnerInterview Question

What is the purpose of CAST in ABAP CDS?

Answer: CAST changes the technical data type of an expression during query execution. It enables compatible calculations, comparisons, CASE expressions, UNION operations, and other CDS expressions without modifying the underlying database value.

BeginnerInterview Question

Does CAST modify the value stored in the database?

Answer: No. CAST affects only the result of the expression during query execution. The original value stored in the database remains unchanged.

BeginnerInterview Question

Can CAST be used to convert USD into EUR?

Answer: No. CAST changes only the technical data type. Business conversions such as currency conversion must use the CDS function currency_conversion().

ExperiencedInterview Question

Why do CASE expressions frequently use CAST?

Answer: Every branch of a CASE expression must return compatible data types. CAST explicitly defines the result type and avoids compiler errors caused by incompatible branches.

ExperiencedInterview Question

Why can't an alias be reused in another expression within the same CDS projection?

Answer: CDS evaluates all projection expressions in parallel. Since aliases are created only after the projection list has been evaluated, they are not available to other expressions in the same SELECT list.

ExperiencedInterview Question

When should you CAST to a semantic data element instead of a built-in data type?

Answer: Whenever SAP provides a semantic data element representing the business concept. For example, prefer BUKRS over abap.char(4), MATNR over abap.char(40), and WAERS over abap.cuky because they preserve business semantics and improve readability.

ExperiencedInterview Question

Why is a Sales Order not considered a numeric value even though it contains only digits?

Answer: A Sales Order is a business identifier rather than a measurable quantity. Although it appears numeric, it represents a document key and should not participate in arithmetic calculations.

ExperiencedInterview Question

What is the difference between CAST and currency_conversion()?

Answer: CAST changes only the technical data type of an expression. currency_conversion() changes the business value by applying exchange rates and converting between currencies.

ExperiencedInterview Question

Can every source data type be CAST to every target data type?

Answer: No. CDS supports only specific conversion combinations. Unsupported source and target combinations result in compiler errors during activation.

ExperiencedInterview Question

Why is CAST commonly used before aggregate functions such as SUM()?

Answer: CAST ensures that the expression participates in the aggregation using the intended data type, especially when calculations involve different numeric representations.

ArchitectInterview Question

Would you use CAST to fix every compiler error related to incompatible data types?

Answer: No. CAST should never be used as a workaround. First determine whether the underlying CDS model is correct. Repeated CAST expressions often indicate that the data model or layering strategy should be improved.

ArchitectInterview Question

How would you avoid repeating the same CAST expression throughout a RAP application?

Answer: Move the calculation into a lower CDS layer such as an Interface or Composite View and expose the calculated field through higher Projection Views. This avoids duplicated logic and improves maintainability.

ArchitectInterview Question

How does CAST support SAP HANA code pushdown?

Answer: CAST is executed inside the database as part of the SQL statement. This allows SAP HANA to perform the conversion during query execution instead of transferring raw data to the ABAP application server for post-processing.

ArchitectInterview Question

What is the biggest misconception developers have about CAST?

Answer: Many developers believe CAST changes business values such as currencies or units of measure. In reality, CAST changes only the technical data type. Business conversions require dedicated CDS conversion functions.

Architect Checklist Before Using CAST

Production Readiness Checklist

QuestionRecommendation
Am I solving a technical compatibility issue?If yes, CAST may be appropriate.
Am I trying to change the business value?Use currency_conversion() or unit_conversion() instead.
Does a semantic data element already exist?Prefer semantic data elements over generic built-in types.
Can this calculation be moved to a lower CDS layer?Layer Interface, Composite, and Projection Views whenever possible.
Will another developer immediately understand this CAST expression?Prioritize readability over clever implementations.
Am I introducing CAST only to silence a compiler error?Review the underlying data model before adding CAST.

Architect Perspective

Architect Insight

Production-quality CDS Views are not judged by how many advanced expressions they contain.

They are judged by how easy they are to understand, extend, and maintain.

CAST should improve the clarity of your data model—not increase its complexity.
🔄
Developer Reference

CAST Expression Cheat Sheet

Type Conversion • Data Compatibility • SAP HANA Pushdown

This quick reference summarizes the most important concepts of the CAST expression in ABAP CDS. Use it as a quick guide when converting data types, building calculations, or preparing CDS Views for RAP applications and technical interviews.

TopicSyntax / ValueSummary
Purposecast( expression as type )Converts an expression from one data type to another.
Changes Database Value?❌ NoCAST only changes how the value is interpreted; the stored database value remains unchanged.
Changes Business Meaning?❌ NoBusiness semantics remain unchanged after the conversion.
Typical UsageCASE, UNION, CalculationsCommonly used for type compatibility, arithmetic expressions, projections, and OData exposure.
Currency Conversioncurrency_conversion()Use the dedicated conversion function instead of CAST for currency conversion.
Unit Conversionunit_conversion()Use the dedicated conversion function instead of CAST for unit conversion.
Amount Conversioncurr_to_decfloat_amount()Preferred when performing calculations on CURR fields.
Preferred Target TypeSemantic Data ElementWhenever possible, cast to a semantic ABAP data element rather than a primitive type.
PerformanceSAP HANACAST is executed directly in the database as part of code pushdown.
Common MistakeCAST ≠ Business ConversionCAST changes only the technical data type, not the business meaning or value.

💡 Key Takeaway

CAST is one of the most frequently used expressions in ABAP CDS, but it is often misunderstood.

Throughout this lesson, we learned that CAST is responsible only for changing the technical data type of an expression. It does not modify the stored value, perform currency conversion, or change the business meaning of the data.

We also explored why understanding SAP business semantics is just as important as understanding technical data types. Choosing semantic data elements such as BUKRS, MATNR, WAERS, and MEINS results in CDS models that are easier to read, easier to maintain, and more closely aligned with SAP's Virtual Data Model.

Finally, we examined how CAST is used in production CDS View Entities—including calculations, CASE expressions, RAP Projection Views, OData Services, analytical reporting, and SAP HANA code pushdown—along with common compiler errors and architectural best practices.

Watch the Complete ADT Walkthrough

In the accompanying video, we'll implement every concept covered in this lesson using Eclipse ADT and SAP S/4HANA Public Cloud.

We'll build real CDS View Entities, explore common compiler errors, understand why they occur, and apply CAST correctly in practical RAP development scenarios.

What's Next?

Now that you understand how to work with different data types and use CAST effectively, you're ready to learn one of the most powerful expression constructs available in ABAP CDS: CASE Expressions.

In the next lesson, you'll learn how to implement conditional logic directly in CDS View Entities using both Simple CASE and Searched CASE, create business-friendly calculated fields, combine CASE with CAST, and apply these techniques to real-world reporting and RAP applications.

💡 SAP Best Practice

Before continuing, make sure you're comfortable identifying SAP business identifiers, semantic data elements, and the distinction between technical and business conversions. These concepts form the foundation for many advanced CDS expressions you'll encounter later in this learning path.