HANA Modeling Best Practices Guide
HANA Modeling Best Practices Guide
Best Practices
SAP AGS
General Principles on Performance
A B C D D G
OLAP
no Scenario?
yes
OLTP
Scenario Master yes
Data
• Transactional Scenarios
Reporting? • E.g. HR reporting
SQL Optimizer
Calculation
Views
calculation engine
Attribute
Analytic
Views
Views OLAP Join
row store engine
engine engine
Data
Foundation
Delivery
Attribute Header
Delivery ID
View Delivery Date
Ship-to Party
Dimension
Dimension Sold-to Party 50 mio records
Material Sales Org
Delivery
Item
Delivery ID Fact table
Item ID
Material
100 mio records
Value
Item Data
OLAP is not designed to handle mass join operation. The more join operations to be
executed, the slower the query performance !
Avoid joining big tables.
Avoid joining big Attribute Views.
Attribute View
Material
Descriptions
Material ID
Language
Material Output
Description
Material ID
1 Data Foundation
Material Class
Material Order Item
Class Billing Item
Material Class ID
VBELN
1
Name
VBELN
POSNR
POSNR
MATNR
N MATNR
NETWR ORDER Delivery Item
ERDAT
1
VBELN PRSDT
An Analytic View only allows to select measures from one Fact Table within Data Foundation.
Here, the measure NETWR ORDER from the second Fact Table Order Item is modeled as
attribute.
© 2011 SAP AG. All rights reserved. 8
Analytic View - Modeling Measure as attribute 2/3
Example – Risk of wrong aggregation
SELECT
Incorrect Total!!!
MATNR NETWR_ NETWR_
ORDER DEL MATNR,
Due to the measures having the same value. M-01 8150 8150
NETWR_ORDER,
SUM(NETWR_DEL),
Aggregation removes duplicate lines FROM VIEW
GROUP BY MATNR, NETWR_ORDER
NETWR DEL
Measure used as
an attribute Fact
Table
Attribute View
Material
Descriptions
Material ID
Language
Material
Description
Material ID
1 Data Foundation
Material Class
Material Order Item
Class
Material Class ID
VBELN
1
Name
POSNR
POSNR VGBEL
Attribute View VGBEL VGPOS
0..N
Time Dimension VGPOS 0..N AUBEL
ERDAT AUPOS
Date
1
N NETWR DEL PRSDT
Callyear
NETWR BILLING
Calmonh
Calweek
Fact Table
An Analytic View only allows to select measures from one Fact Table within Data Foundation.
In the example, this is Fact Table “Billing Item“ with measure NETWR_BILLING.
Here in this example, the measure NETWR_DEL from the second Fact Table Delivery Item and
the measure NETWR_ORDER from the third Fact Table Order Item are modeled as attributes.
© 2011 SAP AG. All rights reserved. 10
Multiple fact tables – Calculation View
Union with Constant Values
Situation
You have measures coming from two fact tables.
Solution
Create one Analytic View per fact table.
Create a Calculation View with a UNION to
combine both Analytic Views.
Set the counter parts for measures to Constant
Value = ‘0‘ for the Analytic View that does not
provide that measure.
Set the counter parts for an attribute to Constant
Value = NULL for the Analytic View that does not
provide the attribute.
Join
Analytic View
Order Item
VBELN
POSNR
Table
MATNR
NETWR ORDER
Create a Calculation View and join the Analytic View the other Fact Table (in this example:
Order Item)
The Analytic View includes one Fact Table as Data Foundation with measure.
© 2011 SAP AG. All rights reserved. 12
Multiple Fact Tables – Calculation View
Join of Analytic View and Table, Query 1
VBELN POSNR NETWR NETWR
DEL ORDER
Order Item
VBELN
POSNR Table
MATNR
NETWR ORDER
4970 20 ? 8150 ?
SELECT
VBELN,
POSNR,
ERDAT,
Calculation View Output SUM(NETWR_ORDER)
SUM(NETWR_DEL)
FROM CV
GROUP BY VBELN, POSNR
Join
Analytic View
Order Item
VBELN
POSNR Table
MATNR
NETWR ORDER
4970 20 ? ?
© 2011 SAP AG. All rights reserved. 14
Exercise A2
Analytic View - Calculated Attributes 1/2
SELECT YEAR
Warning!
YEAR CROSS REV SALES DEDUCT PROD VAR SUM(A_GROSSREVENUE)
Use with caution 2011 500 200 300 SUM(A_SALESDEDUCTION)
2012 300 100 200 SUM(A_PRODUCTVARIANCE)
FROM AV A
WHERE MATNR = DPC1017
GROUP BY YEAR
_SYS_BIC/<package>/<Analytic View>
Wrapper Calc. View
Add /olap to
directly access the
Analytic View
Analytic View
_SYS_BIC/<package>/<Analytic View>/olap
Calculated Attributes
• A_CURRENT_YEAR_CA: midstr(string(now()),1,4)
• A_PREVIOUS_YEAR_CA: string(double(“A_CURRENT_YEAR_CA")-1)
• A_FILTER_CA: if(“A_CURRENT_YEAR_CA"="YEAR",1,if(“A_PREVIOUS_YEAR_CA"="YEAR",2,-1),-1)
The existence of Calc. Attributes using attributes results in the creation of an additional wrapper
Calc. View runtime object for the Analytic View = _SYS_BIC/<package>/<Analytic View>.
The wrapper Calc. View will always get executed (in the Calc Engine !) regardless if any
Calculated Attributes are selected by the SQL query.
© 2011 SAP AG. All rights reserved. 15
SELECT
Analytic View - Calculated Attributes 2/2 YEAR,
YEAR FILTER CROSS REV SALES DEDUCT PROD VAR A_FILTER_CA
2011 2 500 200 300 SUM(A_GROSSREVENUE)
2012 1 300 100 200
SUM(A_SALESDEDUCTION)
SUM(A_PRODUCTVARIANCE)
FROM AV A
WHERE MATNR = DPC1017
GROUP BY YEAR,
Wrapper Calc. View A_FILTER_CA
Note!
Calc. Attributes are
not pushed down
into plain Analytic
View
Analytic View
Dimensions and measures used in SQL queries will get pushed down where possible.
First, results from the plain Analytic View (/olap) are transferred to the Calc. View.
Then, the Calc. Attributes, here A_FILTER_CA, are executed in the wrapper Calc. View.
Calc. Attributes will not be pushed down to the plain Analytic View
(SYS_BIC/<package>/<Analytic View>/olap).
© 2011 SAP AG. All rights reserved. 16
Filter Operations 1/2
CONSTRAINT, WHERE Clause, CE_PROJECTION, HAVING
CONSTRAINT filter
static design filter, can be applied on a table of an Analytic View or can be defined in a
Projection node of a Calculation View
is forced with inner join, and optional with left / referential join
is executed before join and aggregation
reduces data amount very early and for that it is very fast (especially when constraint
is applied on a dimension table)
normally faster than WHERE CLAUSE, as the result set is reduced before proceeding
WHERE CLAUSE
is defined in the SQL query / SQL statement
the filter applies on the result set of a query
applies on a tuple and has different semantic than constraint filter
is very fast on column tables
Both operations, CONSTRAINT filter and WHERE CLAUSE can be used to filter and reduce the result
set of data.
But from semantic point of view these two operations are not the same at all:
A CONSTRAINT filter gets executed first, the WHERE clause gets executed second.
CE_PROJECTION
the semantic is similar to WHERE clause
In comparison to WHERE clause, the filter here is in the model can be used to filter on a specific
aggregation level within a Calculation View
HAVING
used to reduce the final result set after aggregation -> no performance gain
e.g. HAVING SalesAmount > 10000
HANA client,
Reporting Tool Create Attribute and Analytic
Views first.
Calculation View Use Calculation Views only as
a second option where the
business requirement can’t be
met with Analytic View only.
Calculation View
Column View
Attribute
FILTER 1 FILTER .. N View/RAW
table
Analytical View
Copy .. 2 Copy … N
UNION
Combining multiple Analytical Views Calculation View
2 … N (Input Sources)
The UNION combines data from 2..N input sources, here Projection_A and Projection_B.
Mapped fields can have different names, but the data type must be identical.
Projection_A:
KPLIKZ = 0 = Planned
Projection_B:
KPLIKZ = 1 = Actual
Define a Calculated Attribute inside the Calculation View, but not in the underlying Analytic View,
because then the calculation can be performed after aggregation.
Only define a Calculated Attribute in an Attribute View if the Attribute View is small or filtered.
Otherwise, if the number of calculated records is large it affects the performance.
In case a Calculated Attribute needs to be joined (avoid this if possible), use a Calculation View:
AT_View
CA_CALC
AN_View AT_View
© 2011 SAP AG. All rights reserved. 26
Calculated Fields
Avoid expensive calculations, e.g. complex IF, CASE, String expressions, inside
Calculated Fields (Calculated Attributes, Calculated Columns or Calculated Measures)
Calculations are intermediate results that need to be written into buffer and take
additional time.
A calculation on the fly for a Calculated Field may be very expensive. For that reason it
might be (depending on the scenario) better to add a new table column and do the
calculation during the time of inserting a new data set.
Avoid joins on calculated fields, instead you could materialize the calculated join field by
adding an additional column to the source table.
Here is an example on how to add an additional column ‘bc’ to a table for calculated data
resulting in a faster query execution :
Example:
The Join of an Attribute View with an Analytic View within a Calculation View is slower
than joining the Attribute View within the Analytic View as a dimension table.
Avoid joining big Attribute Views in a
Calculation View.
AN_View AT_View
Reason:
The used engine is different :
Join inside the Calculation View -> ceJoin -> Calculation Engine
Join inside the Analytic View -> BwPopJoin -> OLAP Engine
The Attribute View which is joined within a Calculation View is always scanned
even when the Attribute View does not contain any columns which are specified
in the SELECT statement. The WHERE clause of the Select statement is not pushed
down to the Attribute View. This could lead to massive data movements.
© 2011 SAP AG. All rights reserved. 29
Calculation View – Union and filter on Analytic Views
CALC ENGINE
ABC 60 0 0
ABC 0 180 0
EFG 0 0 60 Warning!
Refrain from
moving large
Filter to reduce
SELECT SPART, SUM(KWMENG) datasets
between
the data set FROM AV GROUP BY SPART engines.
-> Use Filter
OLAP ENGINE
AV A AV B AV C
ABC DPC1017 60 0 0
AV A AV B AV C
SPART MATNR WERKS KWMENGA SPART MATNR WERKS KWMENGB SPART MATNR WERKS KWMENGC
Note! Note!
Difference between NETWR_AGG and OLAP Analytic View transfers
NETWR_PROJ. aggregated data. Less amount of data
Data coming from RAW tables is not transferred. No difference between
aggregated. NETWR_AGG and NETWR_PROJ.
SQL
Be aware that the semantics of relational operations as used in SQL queries and CE
functions are different.
For example consider a Calculation View that is queried using attribute PUBLISHER
(but not YEAR). The CA View contains CE_AGGREGATION as aggregation node
which is defined on PUBLISHER and YEAR.
Need to know:
Only selected fields are fetched with CE functions -> The grouping on YEAR would
be removed from the grouping. Evidently this reduces the granularity of the grouping,
changing the semantics of the model.
On the other hand, if the CA View contains a SQL based Script containing a grouping
on PUBLISHER and YEAR this aggregation-level would NOT be changed if a query
only uses attribute PUBLISHER.
VAR =
Variable name / SELECT
temporary table FLDATE, CARRID, CONNID, Parameter 1
SEATSMAX Analytic View
FROM Name
"SFLIGHT"."SFLIGHT";
Parameter 2 (optional)
Field names(1 … N)
Similar to
VAR =
SELECT
FLDATE, CARRID, CONNID,
Inner Join between p_1 and p_2 on the AGENCYNUM, SUM(PRICE)
fields FROM
FLDATE, CARRID, CONNID "_SYS_BIC".“<package>/AN_BOOK"
and output of the fields GROUP BY
FLDATE, CARRID, CONNID, FLDATE, CARRID, CONNID,
AGENCYNUM, SEATSMAX, PRICE AGENCYNUM;
© 2011 SAP AG. All rights reserved. 40
See Exercise C7.1
Function Expression:
Calculated new column
CC_NEW with value ‘1’
Similar to
VAR =
SELECT
"NAME", "CARRID", "CONNID",
1 AS "CC_NEW" , SUM("PRICE")
FROM
"_SYS_BIC".“<package>/AN_BOOK"
WHERE
"CARRID" = 'AZ'
GROUP BY
"NAME", "CARRID", "CONNID";
Mixing up SQL and CE Functions is technically possible BUT this might impact the
performance. You may get a worse performance than using only one of them.
Preferred
Preferred Preferred
SQL Optimizer
calculation engine
OLAP join
row store engine
engine engine
SQL Optimizer
calc views
calculation engine
analytic attribute
views views
OLAP join
row store engine
engine engine
calculation engine
minimize
transfer!
OLAP join
engine engine
column store
Modeling Guidance I: Minimize Transfer
join on key
order items delivery items
Modeling Guidance I: Minimize Transfer
group by Region
group by Region
UNION
group by Region
Slow as loop
matmoves = SELECT * FROM MSEG works on
FOR EACH matmove in matmoves
item level
IF [Link] = „I“ THEN
plant_text = SELECT plant_text FROM WERKS WHERE id=[Link]
ELSE
plant_text = SELECT plant_text FROM WERKS_EXT WHERE id=[Link]
END
NEXT
[pseudo code]
Modeling Guidance II: Use Set Processing for Mass Data
which_plant, plant_int_text,
plant_ext_text
Operations with calculations are still slower than operations without calculations and it is better to avoid calculations at all
if possible.
Perform explicit type cast per below by converting CURRENT_DATE to a VARCHAR field.
The example below shows the filter on left table ORDERS for field O_CUSTKEY = ‘7255’ is performed on the Row
engine.
The column engine does not natively support join trees that have cycles in join edges if an outer join is involved in
the cycle.
Cyclic inner joins (like below) are natively supported by the column engine, but it is better to avoid them because
their performance is inferior to acyclic inner joins.
Move some of the columns involved in the join to different tables by changing the schema.
Example of faster acyclic inner join where column INVOICE_AMT is moved from table INVOICE to table
INVOICE_ITEMS.
Left outer join processing is generally more expensive than inner join processing.
When an EXISTS or NOT EXISTS predicate is connected with other predicates through OR, it is internally mapped
to a left outer join.
In the example below a LEFT OUTER join is performed on INVOICE_ID between tables INVOICE and PAID.
You can use EXCEPT to deduct the results from one results table from those of another.
The two statements below break the complex query into two simpler SQL statements that are linked via table
variables otherwise a sub-query would need to be repeated multiple times.
Query 1 below with GROUPING SETS is equivalent to query 2 with UNION ALL.
In the example below the results for the 1st level of aggregation O_ORDERDATE are displayed up to row 2406 then
the results for the 2nd level of aggregation O_CUSTKEY, O_ORDERDATE are displayed.
This could save the client the effort of re-examining the query result by returning the different granularities of
groups in distinct table variables therefore saving the client the effort of re-examining the query result.
The reason for this is the additional duplicate elimination performed by the UNION operation.
In the example below UNION results in an additional DISTINCT operation cost to eliminate duplicates.
Also single relational operators within a query are executed on multiple cores in parallel.
It is also possible to execute different statements of a single SQLScript in parallel if these statements are
independent of each other.
SQLScript is translated into a dataflow graph and independent paths in this graph can be executed in parallel.
From an SQLScript developer perspective, we can support the database engine in its attempt to parallelize
execution by avoiding unnecessary dependencies between separate SQL statements.
E.g. use declarative logic (CE functions) instead of imperative logic (Cursors).
In the special case of a read-only procedure that returns a single table a procedure can be created using WITH
RESULT VIEW.
It is then possible to embed a call to the procedure in a SQL SELECT statement as follows.
Cursors involve a row-at-a-time processing and therefore opportunities for parallel optimizations by the SQL engine
are missed.
Query 1 and 2 below produce the same output but query 2 is faster.
Cursors involve a row-at-a-time processing and therefore opportunities for parallel optimizations by the SQL engine
are missed.
Query 1 and 2 below produce the same output but query 2 is faster.
Executing dynamic SQL is slow because compile time checks and query optimization must be performed for every
invocation of the procedure.
Without proper checks of the variables used, this might create a security vulnerability.
Currently input parameters for a calculation view are of scalar type, i.e. no input tables allowed.
For example, a calculation view might pass such an input parameter as a search condition on a
table.
The calculation view expects the string (example string of vendors) like
WITH PARAMETERS ('PLACEHOLDER' = ('$$IN_VENDORNAME$$',
‘(AC INDUSTRIES LTD,
GREAT STAR TOOLS CO. LTD.,
CARLTON TRADING CO.,LTD)’ ) with only one set of quotation marks and brackets.
Two options then exist in HANA to interpret this string and use as search condition on a table;
1) Strip the string into substrings and place each vendor entry in a table. Pass this table in WHERE clause.
2) Use LOCATE string function in WHERE clause to check if a substring of the string exists in the table.
The example procedure (see notes) strips a string into a table using comma , as the separator
field.
The code trims the leading and trailing brackets from the string. TRIM LEADING/TRIM TRAILING.
The string is searched from the first position 0 to the position of the separator (less 1) to remove
the separator. SELECT SUBSTRING.
The remaining length is calculated by subtracting the position of the separator from the length.
The new string starts at the position of the separator + 1 plus the remaining length.
The output from the procedure is a table of entries stripped down from the string.
There are a couple of options for using the table in the WHERE clause.
SELECT….
WHERE
VENDOR_NAME IN (SELECT string_list FROM :out_tab).
SELECT….
WHERE
((EXISTS (SELECT string_list FROM :out_tab WHERE vendor_name = :out_tab.string_list))
This option caused a performance issue when trying to activate the calculation view. An optimization here is
planned for a future revision.
Use LOCATE string function to search the string (iv_vendor_name) for a matching entry in the
table field (vendor_name).
Since the string can contain a brackets and commas before or after the vendor name, all
combinations have to be checked.
For example`, the first check below concatenates the table value with a comma before and after
and checks if this is located in the string.
WHERE
(locate(:iv_vendor_name, ','||"vendor_name"||',') != 0) OR
(locate(:iv_vendor_name, '('||"vendor_name"||',') != 0) OR
(locate(:iv_vendor_name, ','||"vendor_name"||')') != 0) OR
(locate(:iv_vendor_name, '('||"vendor_name"||')') != 0)
)
This option was fast and caused no performance issues when activating the calculation view.
This will automatically be applied as a filter to subsequent selects on analytic view or tables inside
the calculation view.
With latest HANA DB revision the filter is pushed down to Analytic View with better performance.
SAP AGS
© 2011 SAP AG. Alle Rechte vorbehalten.
Weitergabe und Vervielfältigung dieser Publikation oder von Teilen daraus sind, HTML, XML, XHTML und W3C sind Marken oder eingetragene Marken des
zu welchem Zweck und in welcher Form auch immer, ohne die ausdrückliche W3C®, World Wide Web Consortium, Massachusetts Institute of Technology.
schriftliche Genehmigung durch SAP AG nicht gestattet. In dieser Publikation SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP BusinessObjects
enthaltene Informationen können ohne vorherige Ankündigung geändert werden. Explorer, StreamWork und weitere im Text erwähnte SAP-Produkte und -
Die von SAP AG oder deren Vertriebsfirmen angebotenen Softwareprodukte Dienstleistungen sowie die entsprechenden Logos sind Marken oder eingetragene
können Softwarekomponenten auch anderer Softwarehersteller enthalten. Marken der SAP AG in Deutschland und anderen Ländern.
Microsoft, Windows, Excel, Outlook, und PowerPoint sind eingetragene Marken Business Objects und das Business-Objects-Logo, BusinessObjects, Crystal
der Microsoft Corporation. Reports, Crystal Decisions, Web Intelligence, Xcelsius und andere im Text
IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, erwähnte Business-Objects-Produkte und Dienstleistungen sowie die
System x, System z, System z10, System z9, z10, z9, iSeries, pSeries, xSeries, entsprechenden Logos sind Marken oder eingetragene Marken der Business
zSeries, eServer, z/VM, z/OS, i5/OS, S/390, OS/390, OS/400, AS/400, S/390 Objects Software Ltd. Business Objects ist ein Unternehmen der SAP AG.
Parallel Enterprise Server, PowerVM, Power Architecture, POWER6+, POWER6, Sybase und Adaptive Server, iAnywhere, Sybase 365, SQL Anywhere und
POWER5+, POWER5, POWER, OpenPower, PowerPC, BatchPipes, weitere im Text erwähnte Sybase-Produkte und -Dienstleistungen sowie die
BladeCenter, System Storage, GPFS, HACMP, RETAIN, DB2 Connect, RACF, entsprechenden Logos sind Marken oder eingetragene Marken der Sybase Inc.
Redbooks, OS/2, Parallel Sysplex, MVS/ESA, AIX, Intelligent Miner, WebSphere, Sybase ist ein Unternehmen der SAP AG.
Netfinity, Tivoli und Informix sind Marken oder eingetragene Marken der IBM Alle anderen Namen von Produkten und Dienstleistungen sind Marken der
Corporation. jeweiligen Firmen. Die Angaben im Text sind unverbindlich und dienen lediglich zu
Linux ist eine eingetragene Marke von Linus Torvalds in den USA und anderen Informationszwecken. Produkte können länderspezifische Unterschiede
Ländern. aufweisen.
Adobe, das Adobe-Logo, Acrobat, PostScript und Reader sind Marken oder Die in dieser Publikation enthaltene Information ist Eigentum der SAP. Weitergabe
eingetragene Marken von Adobe Systems Incorporated in den USA und/oder und Vervielfältigung dieser Publikation oder von Teilen daraus sind, zu welchem
anderen Ländern. Zweck und in welcher Form auch immer, nur mit ausdrücklicher schriftlicher
Oracle und Java sind eingetragene Marken von Oracle und/oder ihrer Genehmigung durch SAP AG gestattet.
Tochtergesellschaften.
UNIX, X/Open, OSF/1 und Motif sind eingetragene Marken der Open Group.
Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame und
MultiWin sind Marken oder eingetragene Marken von Citrix Systems, Inc.