Top Banner
SAP In-Memory Database SQL Reference Guide SAP In-Memory Appliance (SAP HANA) 1.0 SPS 02 Target Audience Consultants Administrators Others Public Document version 1.1 10/21/2011
100
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: hana sql

SAP In-Memory Database SQL Reference Guide

SAP In-Memory Appliance (SAP HANA) 1.0 SPS 02

Target Audience

■ Consultants ■ Administrators ■ Others

Public

Document version 1.1 – 10/21/2011

Page 2: hana sql

© Copyright 2011 SAP AG. All rights reserved.

No part of this publication may be reproduced or transmitted in any

form or for any purpose without the express permission of SAP AG.

The information contained herein may be changed without prior

notice.

Some software products marketed by SAP AG and its distributors

contain proprietary software components of other software vendors.

© Copyright 2011 Sybase, Inc. All rights reserved. Unpublished rights

reserved under U.S. copyright laws.

Sybase, the Sybase logo, Adaptive Server, iAnywhere, Sybase 365,

SQL Anywhere and other Sybase products and services mentioned

herein as well as their respective logos are trademarks or registered

trademarks of Sybase, Inc. All other trademarks are the property of

their respective owners.

Microsoft, Windows, Outlook, and PowerPoint are registered

trademarks of Microsoft Corporation.

IBM, DB2, DB2 Universal Database, System i, System i5, System p,

System p5, System x, System z, System z10, System z9, z10, z9,

iSeries, pSeries, xSeries, zSeries, eServer, z/VM, z/OS, i5/OS, S/390,

OS/390, OS/400, AS/400, S/390 Parallel Enterprise Server, PowerVM,

Power Architecture, POWER6+, POWER6, POWER5+, POWER5,

POWER, OpenPower, PowerPC, BatchPipes, BladeCenter, System

Storage, GPFS, HACMP, RETAIN, DB2 Connect, RACF, Redbooks,

OS/2, Parallel Sysplex, MVS/ESA, AIX, Intelligent Miner,

WebSphere, Netfinity, Tivoli and Informix are trademarks or

registered trademarks of IBM Corporation.

Linux is the registered trademark of Linus Torvalds in the U.S. and

other countries.

Adobe, the Adobe logo, Acrobat, PostScript, and Reader are either

trademarks or registered trademarks of Adobe Systems Incorporated in

the United States and/or other countries.

Oracle is a registered trademark of Oracle Corporation.

UNIX, X/Open, OSF/1, and Motif are registered trademarks of the

Open Group.

Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame,

VideoFrame, and MultiWin are trademarks or registered trademarks of

Citrix Systems, Inc.

HTML, XML, XHTML and W3C are trademarks or registered

trademarks of W3C®, World Wide Web Consortium, Massachusetts

Institute of Technology.

Java is a registered trademark of Sun Microsystems, Inc.

JavaScript is a registered trademark of Sun Microsystems, Inc., used

under license for technology invented and implemented by Netscape.

SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP

BusinessObjects Explorer, and other SAP products and services

mentioned herein as well as their respective logos are trademarks or

registered trademarks of SAP AG in Germany and other countries.

Business Objects and the Business Objects logo, BusinessObjects,

Crystal Reports, Crystal Decisions, Web Intelligence, Xcelsius, and

other Business Objects products and services mentioned herein as well

as their respective logos are trademarks or registered trademarks of

Business Objects Software Ltd. in the United States and in other

countries.

Sybase and Adaptive Server, iAnywhere, Sybase 365, SQL Anywhere,

and other Sybase products and services mentioned herein as well as

their respective logos are trademarks or registered trademarks of

Sybase, Inc. Sybase is an SAP company.

All other product and service names mentioned are the trademarks of

their respective companies. Data contained in this document serves

informational purposes only. National product specifications may

vary.

These materials are subject to change without notice. These materials

are provided by SAP AG and its affiliated companies ("SAP Group")

for informational purposes only, without representation or warranty of

any kind, and SAP Group shall not be liable for errors or omissions

with respect to the materials. The only warranties for SAP Group

products and services are those that are set forth in the express

Page 3: hana sql

warranty statements accompanying such products and services, if any.

Nothing herein should be construed as constituting an additional

warranty.

Disclaimer

Some components of this product are based on Java™. Any

code change in these components may cause unpredictable

and severe malfunctions and is therefore expressively

prohibited, as is any decompilation of these components.

Any Java™ Source Code delivered with this product is

only to be used by SAP’s Support Services and may not be

modified or altered in any way.

Documentation in the SAP Service Marketplace

You can find this documentation at the following address:

http://service.sap.com/hana

Terms for Included Open

Source Software

This SAP software contains also the third party open source software

products listed below. Please note that for these third party products

the following special terms and conditions shall apply.

1. This software was developed using ANTLR.

2. gSOAP

Part of the software embedded in this product is gSOAP software.

Portions created by gSOAP are Copyright (C) 2001-2004 Robert A.

van Engelen, Genivia inc. All Rights Reserved.

THE SOFTWARE IN THIS PRODUCT WAS IN PART PROVIDED

BY GENIVIA INC AND ANY EXPRESS OR IMPLIED

WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE

IMPLIED WARRANTIES OF MERCHANTABILITY AND

FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.

IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY

DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR

CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT

LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR

SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS

INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY

OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,

OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)

ARISING IN ANY WAY OUT OF THE USE OF THIS

SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF

SUCH DAMAGE.

3. SAP License Agreement for STLport SAP License Agreement for

STLPort between SAP Aktiengesellschaft Systems, Applications,

Products in Data Processing Neurottstrasse 16 69190 Walldorf,

Germany (hereinafter: SAP) and you (hereinafter: Customer)

a) Subject Matter of the Agreement

A) SAP grants Customer a non-exclusive, non-transferrable, royalty-

free license to use the STLport.org C++ library (STLport) and its

documentation without fee.

B) By downloading, using, or copying STLport or any portion thereof

Customer agrees to abide by the intellectual property laws, and to all

of the terms and conditions of this Agreement.

C) The Customer may distribute binaries compiled with STLport

(whether original or modified) without any royalties or restrictions.

D) Customer shall maintain the following copyright and permissions

notices on STLport sources and its documentation unchanged:

Copyright 2001 SAP AG

E) The Customer may distribute original or modified STLport sources,

provided that:

o The conditions indicated in the above permissions notice are met;

o The following copyright notices are retained when present, and

conditions provided in accompanying permission notices are met:

Coypright 1994 Hewlett-Packard

Company

Copyright 1996,97 Silicon Graphics

Computer Systems Inc.

Copyright 1997 Moscow Center for

SPARC Technology.

Copyright 1999,2000 Boris Fomitchev

Copyright 2001 SAP AG

Permission to use, copy, modify, distribute and sell this software and

its documentation for any purposes is hereby granted without fee,

provided that the above copyright notice appear in all copies and that

both that copyright notice and this permission notice appear in

supporting documentation. Hewlett-Packard Company makes no

representations about the suitability of this software for any purpose.

It is provided “as is” without express or implied warranty.

Permission to use, copy, modify, distribute and sell this software and

its documentation for any purpose is hereby granted without fee,

Page 4: hana sql

provided that the above copyright notice appear in all copies and that

both that copyright notice and this permission notice appear in

supporting documentation. Silicon Graphics makes no representations

about the suitability of this software for any purpose. It is provided “as

is” without express or implied warranty.

Permission to use, copy, modify, distribute and sell this software and

its documentation for any purposes is hereby granted without fee,

provided that the above copyright notice appear in all copies and that

both that copyright notice and this permission notice appear in

supporting documentation. Moscow Center for SPARC makes no

representations about the suitability of this software for any purpose. It

is provided “as is” without express or implied warranty.

Boris Fomitchev makes no representations about the suitability of this

software for any purpose. This material is provided "as is", with

absolutely no warranty expressed or implied.

Any use is at your own risk. Permission to use or copy this software

for any purpose is hereby granted without fee, provided the above

notices are retained on all copies.

Permission to modify the code and to distribute modified code is

granted, provided the above notices are retained, and a notice that the

code was modified is included with the above copyright notice.

Permission to use, copy, modify, distribute and sell this software and

its documentation for any purposes is hereby granted without fee,

provided that the above copyright notice appear in all copies and that

both that copyright notice and this permission notice appear in

supporting documentation. SAP makes no representations about the

suitability of this software for any purpose. It is provided with a

limited warranty and liability as set forth in the License Agreement

distributed with this copy.

SAP offers this liability and warranty obligations only towards its

customers and only referring to its modifications.

b) Support and Maintenance SAP does not provide software

maintenance for the STLport. Software maintenance of the STLport

therefore shall be not included.

All other services shall be charged according to the rates for services

quoted in the SAP List of Prices and Conditions and shall be subject to

a separate contract.

c) Exclusion of warranty

As the STLport is transferred to the Customer on a loan basis and free

of charge, SAP cannot guarantee that the STLport is error-free,

without material defects or suitable for a specific application under

third-party rights. Technical data, sales brochures, advertising text and

quality descriptions produced by SAP do not indicate any assurance of

particular attributes.

d) Limited Liability

A) Irrespective of the legal reasons, SAP shall only be liable for

damage, including unauthorized operation, if this (i) can be

compensated under the Product Liability Act or (ii) if caused due to

gross negligence or intent by SAP or (iii) if based on the failure of a

guaranteed attribute.

B) If SAP is liable for gross negligence or intent caused by employees

who are neither agents or managerial employees of SAP, the total

liability for such damage and a maximum limit on the scope of any

such damage shall depend on the extent to which its occurrence ought

to have anticipated by SAP when concluding the contract, due to the

circumstances known to it at that point in time representing a typical

transfer of the software.

C) In the case of Art. 4.2 above, SAP shall not be liable for indirect

damage, consequential damage caused by a defect or lost profit.

D) SAP and the Customer agree that the typical foreseeable extent of

damage shall under no circumstances exceed EUR 5,000.

E) The Customer shall take adequate measures for the protection of

data and programs, in particular by making backup copies at the

minimum intervals recommended by SAP. SAP shall not be liable for

the loss of data and its recovery, notwithstanding the other limitations

of the present Art. 4 if this loss could have been avoided by observing

this obligation.

F) The exclusion or the limitation of claims in accordance with the

present Art. 4 includes claims against employees or agents of SAP.

4. Adobe Document Services Adobe, the Adobe logo, Acrobat,

PostScript, and Reader are either registered trademarks or trademarks

of Adobe Systems Incorporated in the United States and / or other

countries. For information on Third Party software delivered with

Adobe document services and Adobe LiveCycle Designer, see SAP

Note 854621

Page 5: hana sql
Page 6: hana sql

SAP In-Memory Database SQL Reference Manual

2

Table of Contents

About this Guide ........................................................................................................................................... 7

SAP HANA Guides .......................................................................................................................................... 7

Notation ........................................................................................................................................................ 8

Functions ....................................................................................................................................................... 9

Data type conversion functions ................................................................................................................ 9

CAST Function ....................................................................................................................................... 9

TO_BIGINT Function .............................................................................................................................. 9

TO_BINARY Function ............................................................................................................................. 9

TO_BLOB Function .............................................................................................................................. 10

TO_CHAR Function .............................................................................................................................. 10

TO_CLOB Function .............................................................................................................................. 10

TO_DATE Function .............................................................................................................................. 10

TO_DATS Function .............................................................................................................................. 11

TO_DECIMAL Function ........................................................................................................................ 11

TO_DOUBLE Function ......................................................................................................................... 11

TO_INT Function ................................................................................................................................. 12

TO_INTEGER Function ......................................................................................................................... 12

TO_NCHAR Function ........................................................................................................................... 12

TO_NCLOB Function ............................................................................................................................ 12

TO_NUMBER Function ........................................................................................................................ 13

TO_REAL Function ............................................................................................................................... 13

TO_SMALLINT Function ...................................................................................................................... 13

TO_TINYINT Function .......................................................................................................................... 13

TO_TIME Function ............................................................................................................................... 14

TO_TIMESTAMP Function ................................................................................................................... 14

DateTime Functions ................................................................................................................................ 15

ADD_DAYS Function ............................................................................................................................ 15

ADD_MONTHS Function ..................................................................................................................... 15

Page 7: hana sql

SAP In-Memory Database SQL Reference Manual

3

ADD_YEARS Function .......................................................................................................................... 15

ADD_SECONDS Function ..................................................................................................................... 15

DAYS_BETWEEN Function ................................................................................................................... 16

DAYNAME Function ............................................................................................................................ 16

DAYOFMONTH Function ..................................................................................................................... 16

DAYOFYEAR Function .......................................................................................................................... 16

EXTRACT Function ............................................................................................................................... 17

HOUR Function .................................................................................................................................... 17

LAST_DAY Function ............................................................................................................................. 17

MINUTE Function ................................................................................................................................ 17

MONTH Function ................................................................................................................................ 18

MONTHNAME Function ...................................................................................................................... 18

NEXT_DAY Function ............................................................................................................................ 18

NOW Function ..................................................................................................................................... 18

SECOND Function ................................................................................................................................ 19

SECONDS_BETWEEN Function ............................................................................................................ 19

WEEK Function .................................................................................................................................... 19

WEEKDAY Function ............................................................................................................................. 20

YEAR Function ..................................................................................................................................... 20

Miscellaneous Functions ......................................................................................................................... 21

COALESCE Function ............................................................................................................................. 21

IFNULL Function .................................................................................................................................. 21

NULLIF Function .................................................................................................................................. 21

CURRENT_CONNECTION Function ...................................................................................................... 22

CURRENT_SCHEMA Function .............................................................................................................. 22

CURRENT_USER Function ................................................................................................................... 22

DATABASE Function ............................................................................................................................ 23

USER Function ..................................................................................................................................... 23

GROUPING_ID Function ...................................................................................................................... 23

SESSION_CONTEXT Function ............................................................................................................... 24

SYSUUID Function ............................................................................................................................... 25

Number Functions................................................................................................................................... 26

Page 8: hana sql

SAP In-Memory Database SQL Reference Manual

4

ABS Function ....................................................................................................................................... 26

ACOS Function..................................................................................................................................... 26

ASIN Function ...................................................................................................................................... 26

ATAN Function .................................................................................................................................... 26

ATAN2 Function .................................................................................................................................. 27

BITAND Function ................................................................................................................................. 27

CEIL / CEILING Function ...................................................................................................................... 27

COS Function ....................................................................................................................................... 28

COSH Function .................................................................................................................................... 28

COT Function ....................................................................................................................................... 28

EXP Function ....................................................................................................................................... 28

FLOOR Function .................................................................................................................................. 29

GREATEST Function ............................................................................................................................. 29

LEAST Function .................................................................................................................................... 29

LN Function ......................................................................................................................................... 30

LOG Function ....................................................................................................................................... 30

MOD Function ..................................................................................................................................... 30

POWER Function ................................................................................................................................. 31

ROUND Function ................................................................................................................................. 31

SIGN Function...................................................................................................................................... 31

SIN Function ........................................................................................................................................ 31

SINH Function...................................................................................................................................... 32

SQRT Function ..................................................................................................................................... 32

TAN Function ....................................................................................................................................... 32

TANH Function .................................................................................................................................... 32

String Functions ...................................................................................................................................... 34

ASCII Function ..................................................................................................................................... 34

CONCAT Function ................................................................................................................................ 34

LEFT Function ...................................................................................................................................... 34

LCASE Function.................................................................................................................................... 34

LENGTH Function ................................................................................................................................ 35

LOCATE Function ................................................................................................................................. 35

Page 9: hana sql

SAP In-Memory Database SQL Reference Manual

5

LOWER Function ................................................................................................................................. 35

LPAD Function ..................................................................................................................................... 36

LTRIM Function ................................................................................................................................... 36

REPLACE Function ............................................................................................................................... 36

RIGHT Function ................................................................................................................................... 37

RPAD Function .................................................................................................................................... 37

RTRIM Function ................................................................................................................................... 37

SUBSTRING Function ........................................................................................................................... 37

SUBSTR_AFTER Function ..................................................................................................................... 38

SUBSTR_BEFORE Function .................................................................................................................. 38

TRIM Function ..................................................................................................................................... 38

UCASE Function ................................................................................................................................... 39

UNICODE Function .............................................................................................................................. 39

UPPER Function ................................................................................................................................... 39

SQL Statements ........................................................................................................................................... 41

ALTER TABLE........................................................................................................................................ 41

ALTER USER ......................................................................................................................................... 44

CREATE CALCULATION SCENARIO ....................................................................................................... 45

CREATE COLUMN VIEW....................................................................................................................... 47

CREATE INDEX ..................................................................................................................................... 52

CREATE ROLE ....................................................................................................................................... 53

CREATE SCHEMA ................................................................................................................................. 54

CREATE SEQUENCE.............................................................................................................................. 55

CREATE SYNONYM .............................................................................................................................. 57

CREATE TABLE ..................................................................................................................................... 58

CREATE TYPE ....................................................................................................................................... 62

CREATE USER ....................................................................................................................................... 63

CREATE VIEW ...................................................................................................................................... 64

DELETE ................................................................................................................................................. 65

DROP CALCULATION SCENARIO .......................................................................................................... 66

DROP INDEX ........................................................................................................................................ 67

DROP ROLE .......................................................................................................................................... 68

Page 10: hana sql

SAP In-Memory Database SQL Reference Manual

6

DROP SCHEMA .................................................................................................................................... 69

DROP SEQUENCE ................................................................................................................................. 70

DROP SYNONYM ................................................................................................................................. 71

DROP TABLE ........................................................................................................................................ 72

DROP TYPE .......................................................................................................................................... 73

DROP TABLE ........................................................................................................................................ 74

DROP USER .......................................................................................................................................... 75

DROP VIEW.......................................................................................................................................... 76

RENAME INDEX ................................................................................................................................... 77

GRANT ................................................................................................................................................. 78

INSERT ................................................................................................................................................. 81

LOAD ................................................................................................................................................... 82

MERGE DELTA ..................................................................................................................................... 83

RENAME COLUMN .............................................................................................................................. 84

RENAME INDEX ................................................................................................................................... 85

RENAME TABLE ................................................................................................................................... 86

REVOKE ............................................................................................................................................... 87

SELECT ................................................................................................................................................. 88

SET TRANSACTION .............................................................................................................................. 93

UNLOAD .............................................................................................................................................. 94

UPDATE ............................................................................................................................................... 95

UPSERT / REPLACE .............................................................................................................................. 96

Page 11: hana sql

SAP In-Memory Database SQL Reference Manual

7

About this Guide This document contains a list of functions and SQL statements supported by the SAP In-Memory

Database as part of SAP In-Memory Appliance (SAP HANA) 1.0 SPS 02.

SAP HANA Guides For more information about SAP HANA landscape, security, installation and administration, see the

resources listed in the table below.

Topic Guide/Tool Quick Link

SAP HANA

Landscape,

Deployment &

Installation

SAP HANA Knowledge

Center on SAP Service

Marketplace

https://service.sap.com/hana

SAP HANA 1.0 Master Guide

SAP HANA 1.0 Installation Guide

SAP HANA

Administration &

Security

SAP HANA Knowledge

Center on SAP Help

Portal

http://help.sap.com/hana

SAP HANA 1.0 Technical Operations Manual

SAP HANA 1.0 Security Guide

Page 12: hana sql

SAP In-Memory Database SQL Reference Manual

8

Notation This reference use BNF (Backus Naur Form) which is the notation technique used to define

programming languages, to describe SQL. BNF describes the syntax of a grammar using a set of

production rules using a set of symbols. Table 1 presents meta symbols of BNF and descriptions.

The Meta symbols of BNF

Meta-symbol Description

< > Angle brackets are placeholders for syntactical units explained in this

document.

::= Production rule has a left hand side (LHS) and a right hand side (RHS)

separated by the meta-symbol "::=". The symbol on the left-hand side of

the ::= is defined by the right hand side.

[ ] Enclose optional element. Element between [ ] can be specified or omitted.

{ } Groups items. Elements between {} must be specified.

| Possible option elements in the formula. Elements follow by | can be chosen differently than front of | parts

... Displays several repeated item in the formula

Page 13: hana sql

SAP In-Memory Database SQL Reference Manual

9

Functions Functions are used to return information from the database. They are allowed anywhere an expression is allowed. Functions use the same syntax conventions used by SQL statements.

Data type conversion functions Data type conversion functions are used to convert arguments from one data type to another, or

to test whether they can be converted.

CAST Function Syntax:

CAST(expr AS data_type)

Description:

Returns the value of an expression converted to a supplied data type.

Parameters:

expression - The expression to be converted.

data type The target data type.

BIGINT | BINARY | BLOB | CHAR | CLOB | DATE | DECIMAL | DOUBLE | NCHAR |

NCLOB | REAL | TIME | TIMESTAMP

Example: SELECT TOP 1 CAST(7 AS CHAR(10)) "cast" FROM users;

Retrieves: cast 7

TO_BIGINT Function Syntax:

TO_BIGINT(expr)

Description:

Converts the expr of a data type into a value of bigint data type. Example:

SELECT TOP 1 TO_BIGINT('10') "to bigint" FROM users;

Retrieves: to bigint

10

TO_BINARY Function Syntax:

TO_BINARY(expr)

Description:

Converts the expr of a data type into a value of binary string type.

Page 14: hana sql

SAP In-Memory Database SQL Reference Manual

10

Example:

SELECT TOP 1 TO_BINARY('abcde') "to binary" FROM users;

Retrieves: to binary

6162636465

TO_BLOB Function Syntax:

TO_BLOB(expr)

Description:

Converts the expr of a data type into a value of blob type. expr must be a binary string. Example:

SELECT TOP 1 TO_BLOB(TO_BINARY('abcde')) "to blob" FROM users; Retrieves: to blob

abcde

TO_CHAR Function Syntax:

TO_CHAR(expr [,format]) Description:

Converts the expr of a data type into a value of character data type. Example:

SELECT TOP 1 TO_CHAR(TO_DATE('2009-12-31'), 'YYYY/MM/DD') "to char" FROM users;

Retrieves: to char

2009/12/31

TO_CLOB Function Syntax:

TO_CLOB(expr) Description:

Converts the expr of a data type into a value of CLOB data type. Example:

SELECT TOP 1 TO_CLOB ('TO_CLOB converts an expression into a value of CLOB data type') "to clob" FROM users;

Retrieves: to clob

TO_CLOB converts an expression into a value of CLOB data type

TO_DATE Function Syntax:

TO_DATE(expr [, format]) Description:

Page 15: hana sql

SAP In-Memory Database SQL Reference Manual

11

Converts the expr of a data type into a value of DATE data type.

Example:

SELECT TOP 1 TO_DATE('2010-01-12', 'YYYY-MM-DD') "to date" FROM users; Retrieves: to date

2010-01-12

TO_DATS Function Syntax:

TO_DATS(expr) Description:

Converts the expr of a data type into a value of ABAP DATE data type.

Example:

SELECT TOP 1 TO_DATS('2010-01-12') "abap date" FROM users;

Retrieves: abap date

20100112

TO_DECIMAL Function Syntax:

TO_DECIMAL(expr[, precision, scale]) Description:

Converts the expr of a data type into a value of DECIMAL(precision, scale) data type. Example:

SELECT TOP 1 TO_DECIMAL(7654321.89, 9, 2) "to decimal" FROM users;

Retrieves: to decimal

7654321.89

TO_DOUBLE Function Syntax:

TO_DOUBLE(expr) Description:

Converts the expr of a data type into a value of DOUBLE (double precision) data type.

Example:

SELECT TOP 1 3*TO_DOUBLE ('15.12') "to double" FROM users; Retrieves: to double

45.36

Page 16: hana sql

SAP In-Memory Database SQL Reference Manual

12

TO_INT Function Syntax:

TO_INT(expr) Description:

Converts the expr of a data type into a value of INTEGER data type. Example:

SELECT TOP 1 TO_INT('10') "to int" FROM users;

Retrieves: to int

10

TO_INTEGER Function Syntax:

TO_INTEGER(expr) Description:

Converts the expr of a data type into a value of INTEGER data type. Example:

SELECT TOP 1 TO_INTEGER('10') "to int" FROM users; Retrieves: to int

10

TO_NCHAR Function Syntax:

TO_NCHAR(expr [,format]) Description:

Converts the expr of a data type into a value of national character data type.

If format is omitted, it converts to the corresponding format using the date format model. Example:

SELECT TOP 1 TO_NCHAR(TO_DATE('2009/12/31'), 'YY-MM-DD') "to nchar" FROM users;

Retrieves: to nchar

09-12-31

TO_NCLOB Function Syntax:

TO_NCLOB(expr) Description:

Converts the expr of a data type into a value of NCLOB data type. Example:

SELECT TOP 1 TO_NCLOB ('TO_NCLOB converts an expression into a value of NCLOB data type') "to nclob" FROM users;

Page 17: hana sql

SAP In-Memory Database SQL Reference Manual

13

Retrieves: to nclob

TO_NCLOB converts an expression into a value of NCLOB data type

TO_NUMBER Function Syntax:

TO_NUMBER(expr) Description:

Converts the expr of a data type into a numeric data type.

Example:

SELECT TOP 1 3.1*TO_NUMBER ('15') "to number" FROM users;

Retrieves: to number

46.5

TO_REAL Function Syntax:

TO_REAL(expr) Description:

Converts the expr of a data type into the value of REAL (single precision) data type. Example:

SELECT TOP 1 3*TO_REAL ('15.12') "to real" FROM users;

Retrieves: to real

45.36

TO_SMALLINT Function Syntax:

TO_SMALLINT(expr) Description:

Converts the expr of a data type into a value of SMALLINT data type. Example:

SELECT TOP 1 TO_SMALLINT('10') "to smallint" FROM users; Retrieves: to smallint

10

TO_TINYINT Function Syntax:

TO_TINYINT(expr) Description:

Converts the expr of a data type into a value of TINYINT data type. Example:

SELECT TOP 1 TO_TINYINT('10') "to tinyint" FROM users;

Page 18: hana sql

SAP In-Memory Database SQL Reference Manual

14

Retrieves: to tinyint

10

TO_TIME Function Syntax:

TO_TIME(expr [, format]) Description:

Converts the expr of a data type into a value of TIME data type. If format is omitted, it converts expr into the corresponding format using the date format model. Example:

SELECT TOP 1 TO_TIME ('08:30 AM', „HH12:MI AM‟) "to time" FROM users;

Retrieves: to time

08:30:00

TO_TIMESTAMP Function Syntax:

TO_TIMESTAMP(expr [, format]) Description:

Converts the expr of a data type into the TIMESTAMP data type.

If format is omitted, it converts expr into the corresponding format using the date format model. Example:

SELECT TOP 1 TO_TIMESTAMP ('2010-01-11 13:30:00', 'YYYY-MM-DD HH24:MI:SS') "to timestamp" FROM users; Retrieves: to timestamp

2010-01-11 13:30:00.000

Page 19: hana sql

SAP In-Memory Database SQL Reference Manual

15

DateTime Functions

ADD_DAYS Function Syntax:

ADD_DAYS(d, n) Description:

Computes the date d plus n days. Example:

SELECT TOP 1 ADD_DAYS(TO_DATE('2009-12-05', 'YYYY-MM-DD'), 30) "add days" FROM users;

Retrieves: add days

2010-01-04

ADD_MONTHS Function Syntax:

ADD_MONTHS(d, n) Description:

Computes the date d plus n months. Example:

SELECT TOP 1 ADD_MONTHS(TO_DATE('2009-12-05', 'YYYY-MM-DD'), 1) "add months" FROM users;

Retrieves: add months

2010-01-05

ADD_YEARS Function Syntax:

ADD_YEARS(d, n) Description:

Computes the date d plus n years. Example:

SELECT TOP 1 ADD_YEARS(TO_DATE('2009-12-05', 'YYYY-MM-DD'), 1) "add years" FROM users;

Retrieves: add years

2010-12-05

ADD_SECONDS Function Syntax:

ADD_SECONDS(t, n) Description:

Computes the time t plus n seconds. Example:

SELECT TOP 1 ADD_SECONDS(TO_TIME('23:30:45'), 60*30) "add seconds" FROM users;

Page 20: hana sql

SAP In-Memory Database SQL Reference Manual

16

Retrieves: add seconds

00:00:45.000

DAYS_BETWEEN Function Syntax:

DAYS_BETWEEN (date1, date2) Description:

Computes the number of days between date1 and date2. Example:

SELECT TOP 1 DAYS_BETWEEN(TO_DATE('2009-12-05', 'YYYY-MM-DD'), TO_DATE('2010-01-05', 'YYYYMM-DD')) "days between" FROM users;

Retrieves: days between

31

DAYNAME Function Syntax:

DAYNAME(expr) Description:

Returns the name of the weekday in English. Example:

SELECT TOP 1 DAYNAME('2011-05-30') "dayname" FROM users; Retrieves: dayname

MONDAY

DAYOFMONTH Function Syntax:

DAYOFMONTH(expr) Description:

Returns the day of the month in integer. Example:

SELECT TOP 1 DAYOFMONTH ('2011-05-30') "dayofmonth" FROM users; Retrieves: dayofmonth

30

DAYOFYEAR Function Syntax:

DAYOFYEAR(expr) Description:

Returns the day of the year in integer.

Page 21: hana sql

SAP In-Memory Database SQL Reference Manual

17

Example:

SELECT TOP 1 DAYOFYEAR ('2011-05-30') "dayofyear" FROM users;

Retrieves: dayofyear

150

EXTRACT Function Syntax:

EXTRACT({YEAR | MONTH | DAY | HOUR | MINUTE | SECOND} FROM datetime_value) Description:

Finds and returns the value of a specified datetime field from a datetime_value. Example:

SELECT TOP 1 EXTRACT(YEAR FROM TO_DATE('2010-01-04', 'YYYY-MM-DD')) "extract" FROM users; Retrieves: extract

2010

HOUR Function Syntax:

HOUR(expr) Description:

Extract hour from expr. Example:

SELECT TOP 1 HOUR ('12:34:56‟) "hour" FROM users;

Retrieves: hour

12

LAST_DAY Function Syntax:

LAST_DAY(d) Description:

Returns the date of the last day of the month that contains d. Example:

SELECT TOP 1 LAST_DAY(TO_DATE('2010-01-04', 'YYYY-MM-DD')) "last day" FROM users; Retrieves: last day

2010-01-31

MINUTE Function Syntax:

MINUTE(expr) Description:

Page 22: hana sql

SAP In-Memory Database SQL Reference Manual

18

Extract minute from expr. Example:

SELECT TOP 1 MINUTE ('12:34:56‟) "minute" FROM users; Retrieves: minute

34

MONTH Function Syntax:

MONTH(expr) Description:

Returns the number of the month from a given date. Example:

SELECT TOP 1 MONTH ('2011-05-30‟) "month" FROM users; Retrieves: month

5

MONTHNAME Function Syntax:

MONTHNAME(expr) Description:

Returns the name of the month in English. Example:

SELECT TOP 1 MONTHNAME ('2011-05-30‟) "monthname" FROM users; Retrieves: monthname

MAY

NEXT_DAY Function Syntax:

NEXT_DAY(d) Description:

Returns the date of the next day of d. Example:

SELECT TOP 1 NEXT_DAY(TO_DATE('2009-12-31', 'YYYY-MM-DD')) "next day" FROM users; Retrieves: next day

2010-01-01

NOW Function Syntax:

Page 23: hana sql

SAP In-Memory Database SQL Reference Manual

19

NOW() Description:

Returns the current timestamp. Example:

SELECT TOP 1 NOW() "now" FROM users;

Retrieves: now

2010-01-01 16:34:19

SECOND Function Syntax:

SECOND(t) Description:

Returns the second number of a given time t. Example:

SELECT TOP 1 SECOND(‟12:34:56‟) "second" FROM users;

Retrieves: second

56

SECONDS_BETWEEN Function Syntax:

SECONDS_BETWEEN(d1, d2) Description:

Computes the number of seconds between d1 and d2, which is semantically equal to d2 – d1. Example:

SELECT TOP 1 SECONDS_BETWEEN('2009-12-05', '2010-01-05') "seconds between" FROM users; Retrieves: Seconds between

2678400

WEEK Function Syntax:

WEEK(d) Description:

Returns the week number of a given date d. Example:

SELECT TOP 1 WEEK(TO_DATE('2011-05-30', 'YYYY-MM-DD')) "week" FROM users; Retrieves: week

22

Page 24: hana sql

SAP In-Memory Database SQL Reference Manual

20

WEEKDAY Function Syntax:

WEEKDAY(d) Description:

Returns the day of week of a given date d. The return value ranges from 0 to 6, each of which

represents Monday to Sunday. Example:

SELECT TOP 1 WEEKDAY(TO_DATE('2010-12-31', 'YYYY-MM-DD')) "week day" FROM users; Retrieves: week day

4

YEAR Function Syntax:

YEAR(d) Description:

Returns the year number of a given date d. Example:

SELECT TOP 1 YEAR(TO_DATE('2011-05-30', 'YYYY-MM-DD')) "year" FROM users; Retrieves: year

2011

Page 25: hana sql

SAP In-Memory Database SQL Reference Manual

21

Miscellaneous Functions

COALESCE Function Syntax :

COALESCE(expr_list) Description:

Returns the first non-NULL expression from a list. At least two expressions must be passed into the function, and all expressions must be comparable.The result will be NULL if all the arguments are NULL. Example:

SELECT * FROM tab; Retrieves: ID A B

1 100.0 80.0

2 NULL 63.0

3 NULL NULL

SELECT id, a, b, COALESCE(a, b*1.1, 50.0) "coalesce" FROM tab; Retrieves: ID A B coalesce

1 100.0 80.0 100

2 NULL 63.0 69.3

3 NULL NULL 50

IFNULL Function Syntax:

IFNULL(expr1, expr2) Description:

Returns expr1 if expr1 is not NULL and expr2 if expr1 is NULL. Example:

SELECT TOP 1 IFNULL('diff', 'same') "ifnull" FROM users;

Retrieves: ifnull

diff

NULLIF Function Syntax:

NULLIF(expr1, expr2) Description:

NULLIF compares the values of the two expressions. If the first expression equals the second expression, NULLIF returns NULL. If the first expression does not equal the second expression, or if the second expression is NULL, NULLIF returns the first expression.

Page 26: hana sql

SAP In-Memory Database SQL Reference Manual

22

The NULLIF function provides a short way to write some CASE expressions. Example:

SELECT TOP 1 NULLIF('diff', 'same') "nullif" FROM users; Retrieves: nullif

diff

SELECT TOP 1 NULLIF('same', 'same') "nullif" FROM users; Retrieves: nullif

NULL

CURRENT_CONNECTION Function Syntax:

CURRENT_CONNECTION

Description:

Returns the current connection id. Example:

SELECT TOP 1 CURRENT_CONNECTION "current connection" FROM users; Retrieves: current connection

2

CURRENT_SCHEMA Function Syntax:

CURRENT_SCHEMA

Description:

Returns the current schema name in the string. Example:

SELECT TOP 1 CURRENT_SCHEMA "current schema" FROM users; Retrieves: current schema

SYSTEM

CURRENT_USER Function Syntax:

CURRENT_USER

Description:

Returns the current user name in the string. Example:

SELECT TOP 1 CURRENT_USER "current user" FROM users; Retrieves: current user

Page 27: hana sql

SAP In-Memory Database SQL Reference Manual

23

SYSTEM

DATABASE Function Syntax:

DATABASE()

Description:

Returns the current schema name. Example:

SELECT TOP 1 DATABASE() FROM users; Retrieves: CURRENT_SCHEMA

SYSTEM

USER Function Syntax:

USER()

Description:

Returns the current user name. Example:

SELECT TOP 1 USER() "current user" FROM users;

Retrieves: current user

SYSTEM

GROUPING_ID Function Syntax:

GROUPING_ID(column_name_list)

Description:

GROUPING_ID function can be used with GROUPING SETS to return multiple levels of aggregations in a single result set. GROUPING_ID returns an integer value to identify which grouping set each row belongs to. Each column in GROUPING_ID must be an element of the GROUPING SETS.

GROUPING_ID is assigned by converting the bit vector generated from GROUPING SETS to a decimal

number by treating the bit vector as a binary number. When a bit vector is composed, 0 is assigned to each column specified in the GROUPING SETS and 1 otherwise in the order it appears in the GROUPING SETS. By treating the bit vector as a binary number, this function returns an integer value as the output. Example:

SELECT customer, year, product, SUM(sales), GROUPING_ID(customer, year, product) FROM guided_navi_tab GROUP BY GROUPING SETS ( (customer, year, product),

(customer, year), (customer, product),

Page 28: hana sql

SAP In-Memory Database SQL Reference Manual

24

(year, product), (customer), (year), (product)

); Retrieves:

CUSTOMER YEAR PRODUCT SUM(SALES) GROUPING_ID(CUSTOMER,YEAR,PRODUCT)

1 C1 2009 P1 100 0

2 C1 2010 P1 50 0

3 C2 2009 P1 200 0

4 C2 2010 P1 100 0

5 C1 2009 P2 200 0

6 C1 2010 P2 150 0

7 C2 2009 P2 300 0

8 C2 2010 P2 150 0

9 C1 2009 ? 300 1

10 C1 2010 ? 200 1

11 C2 2009 ? 500 1

12 C2 2010 ? 250 1

13 C1 ? P1 150 2

14 C2 ? P1 300 2

15 C1 ? P2 350 2

16 C2 ? P2 450 2

17 ? 2009 P1 300 4

18 ? 2010 P1 150 4

19 ? 2009 P2 500 4

20 ? 2010 P2 300 4

21 C1 ? ? 500 3

22 C2 ? ? 750 3

23 ? 2009 ? 800 5

24 ? 2010 ? 450 5

25 ? ? P1 450 6

26 ? ? P2 800 6

SESSION_CONTEXT Function Syntax:

SESSION_CONTEXT(session_parameter)

Description:

Page 29: hana sql

SAP In-Memory Database SQL Reference Manual

25

Returns the value of session_parameter assigned to the current user or the value of a personal

setting. The parameter can be set when the session is created. Currently available read only session

variables are „locale‟, „locale_sap‟, „client‟, „conn_id‟, „applicationname‟, „clientuser‟, „clienthostname‟.

Example:

SELECT TOP 1 SESSION_CONTEXT(„conn_Id‟) “session context” FROM users;

Retrieves: session context

4

SYSUUID Function Syntax:

SYSUUID

Description:

Returns the SYSUUID. Example:

SELECT TOP 1 SYSUUID FROM users; Retrieves: SYSUUID

4DE3CD576C79511BE10000000A3C2220

Page 30: hana sql

SAP In-Memory Database SQL Reference Manual

26

Number Functions Number functions take numeric values or strings with numeric characters as inputs and returns numeric values. When strings with numeric characters are given as inputs, implicit conversion from string to number is performed automatically before computing the result values.

ABS Function Syntax :

ABS ( n ) Description:

Returns the absolute value of a numeric expression n. Example:

SELECT TOP 1 ABS(-1) "absolute" FROM users;

Retrieves: absolute

1

ACOS Function Syntax:

ACOS ( n ) Description:

Returns the arc-cosine, in radians, of a numeric expression n between -1 and 1.

Example:

SELECT TOP 1 ACOS(0.5) "acos" FROM users; Retrieves: acos

1.0471975511965979

ASIN Function Syntax:

ASIN ( n )

Description:

Returns the arc-sine, in radians, of a number n between -1 and 1.

Example:

SELECT TOP 1 ASIN(0.5) "asin" FROM users; Retrieves: asin

0.5235987755982989

ATAN Function

Page 31: hana sql

SAP In-Memory Database SQL Reference Manual

27

Syntax :

ATAN ( n ) Description:

Returns the arc-tangent, in radians, of a number n. The argument is a number and the range of n is

unlimited. Example:

SELECT TOP 1 ATAN(0.5) "atan" FROM users;

Retrieves: atan

0.4636476090008061

ATAN2 Function Syntax :

ATAN2 (n, m)

Description:

Returns the arc-tangent, in radians, of the ratio of two numbers n and m. This is the same result as

ATAN(n/m). Example:

SELECT TOP 1 ATAN2(1.0, 2.0) "atan2" FROM users;

Retrieves: atan2

0.4636476090008061

BITAND Function Syntax:

BITAND (expr1, expr2) Description:

Calculates an AND operation on the bits of expr1 and expr2. Both expr1 and expr2 must be non-negative

integers. The BITAND function returns an integer. Example:

SELECT TOP 1 BITAND(255, 123) "bitand" FROM users; Retrieves: bitand

123

CEIL / CEILING Function Syntax :

CEIL ( n ) Description:

Returns the first integer that is greater or equal to a given value n. For positive numbers, this is known as rounding up.

Page 32: hana sql

SAP In-Memory Database SQL Reference Manual

28

Example:

SELECT TOP 1 CEIL(14.5) "ceiling" FROM users;

Retrieves: ceiling

15

COS Function Syntax:

COS ( n ) Description:

Returns the cosine of the angle in radians given by its argument n.

Example:

SELECT TOP 1 COS(0.0) "cos" FROM users;

Retrieves: cos

1.0

COSH Function Syntax:

COSH ( n ) Description:

Computes the hyperbolic cosine of n. Example:

SELECT TOP 1 COSH(0.5) "cosh" FROM users;

Retrieves: cosh

1.1276259652063807

COT Function Syntax:

COT ( n ) Description:

Computes the cotangent of n. Example:

SELECT TOP 1 COT(40) "cot" FROM users;

Retrieves: Cot

1.5423510453569202

EXP Function Syntax:

EXP ( n )

Page 33: hana sql

SAP In-Memory Database SQL Reference Manual

29

Description:

Returns the result of the base of natural logarithms e raised to the power of the given argument n. Example:

SELECT TOP 1 EXP(1.0) "exp" FROM users; Retrieves: exp

2.718281828459045

FLOOR Function Syntax:

FLOOR ( n ) Description:

Returns the largest integer not greater than the given number n. Example:

SELECT TOP 1 FLOOR(14.5) "floor" FROM users; Retrieves: floor

14

GREATEST Function Syntax:

GREATEST ( n1 [, n2]...) Description:

Returns the greatest value among the arguments: n1, n2, ... Example:

SELECT TOP 1 GREATEST ('aa', 'ab', 'ba', 'bb') "greatest" FROM users; Retrieves: greatest

bb

LEAST Function Syntax:

LEAST ( n1 [, n2]...) Description:

Returns the least value among the arguments: n1, n2... Example:

SELECT TOP 1 LEAST('aa', 'ab', 'ba', 'bb') "least" FROM users;

Retrieves: least

aa

Page 34: hana sql

SAP In-Memory Database SQL Reference Manual

30

LN Function Syntax:

LN ( n ) Description:

Returns the natural logarithm of a given value n, where n is greater than 0.

Example:

SELECT TOP 1 LN(9) "ln" FROM users;

Retrieves:

ln

2.1972245773362196

LOG Function Syntax :

LOG(m, n) Description:

Returns the natural logarithm of n base m. The base m must be a positive value other than 1 and n must be

any positive value. Example:

SELECT TOP 1 LOG(10, 2) "log" FROM users;

Retrieves: log

0.30102999566398114

MOD Function Syntax:

MOD(n, d) Description:

Returns the remainder of a number n divided by a divisor d.

When n is negative this function acts differently to the standard computational modulo operation.

The following explains example of what MOD functions returns as the result. If d is zero, then this function returns n. If n is greater than 0 and n is less than d, then this function returns n.

If n is less than 0 and n is greater than d, then this function returns n. Otherwise, this function calculates the remainder of the absolute value of n divided by the

absolute value of d to calculate the absolute value of the remainder. If m is less than 0, then the returned remainder from MOD is a negative number, and if m is greater than 0, then the returned remainder from MOD is a positive number.

Example:

SELECT TOP 1 MOD(15, 4) "modulus" FROM users;

Retrieves: modulus

Page 35: hana sql

SAP In-Memory Database SQL Reference Manual

31

3

POWER Function Syntax:

POWER(b, e)

Description:

Calculates the base number b raised to the power of an exponent e. Example:

SELECT TOP 1 POWER(2, 10) "power" FROM users; Retrieves: power

1024.0

ROUND Function Syntax:

ROUND(n [, pos ]) Description:

Rounds n to the specified pos amount of places after the decimal point. Example:

SELECT TOP 1 ROUND(16.16, 1) "round" FROM users;

Retrieves: round

16.2

SELECT TOP 1 ROUND(16.56) "round" FROM users; Retrieves: round

17

SIGN Function Syntax:

SIGN ( n ) Description:

Returns the sign (positive or negative) of the given number.n. Returns 1 if n is a positive value, -1

if n is a negative value, and 0 if n is equal to zero. Example:

SELECT TOP 1 SIGN(-15) "sign" FROM users;

Retrieves: sign

-1

SIN Function Syntax:

Page 36: hana sql

SAP In-Memory Database SQL Reference Manual

32

SIN ( n ) Description:

Returns the sine of n, where the argument is an angle expressed in radians. Example:

SELECT TOP 1 SIN( 3.141592653589793/2) "sine" FROM users; Retrieves: sine

1.0

SINH Function Syntax:

SINH (n) Description:

Returns the hyperbolic sine of n, where the argument is an angle expressed in radians. Example:

SELECT TOP 1 SINH(0.0) "sinh" FROM users;

Retrieves: sinh

0.0

SQRT Function Syntax:

SQRT ( n ) Description:

Returns the square root of a number n. Example:

SELECT TOP 1 SQRT(2) "sqrt" FROM users; Retrieves: sqrt

1.4142135623730951

TAN Function Syntax:

TAN ( n ) Description:

Returns the tangent of a number n. Example:

SELECT TOP 1 TAN(0.0) "tan" FROM users; Retrieves: tan

0.0

TANH Function

Page 37: hana sql

SAP In-Memory Database SQL Reference Manual

33

Syntax:

TANH ( n ) Description:

Returns the hyperbolic tangent of a number n. Example:

SELECT TOP 1 TANH(1.0) "tanh" FROM users; Retrieves: tanh

0.7615941559557649

Page 38: hana sql

SAP In-Memory Database SQL Reference Manual

34

String Functions

ASCII Function Syntax:

ASCII(c) Description:

Returns the integer ASCII value of the first byte in a string c. Example:

SELECT TOP 1 ASCII('Ant') "ascii" FROM users; Retrieves: ascii

65

CONCAT Function Syntax :

CONCAT(str1, str2) Description:

Returns a combined string which consists of str1 followed by str2. The concatenation operator (||) is

identical to this function. Example:

SELECT TOP 1 CONCAT('C', 'at') "concat" FROM users; Retrieves: concat

Cat

LEFT Function Syntax :

LEFT(str, n) Description:

Returns n characters from the beginning of a string str. Example:

SELECT TOP 1 LEFT('Hello', 3) "left" FROM users;

Retrieves: left

Hel

LCASE Function Syntax:

LCASE(s) Description:

Converts all characters in a string s to lowercase. The LCASE function is identical to the LOWER function.

Page 39: hana sql

SAP In-Memory Database SQL Reference Manual

35

Example:

SELECT TOP 1 LCASE('Test') "lcase” FROM users;

Retrieves: lcase

test

LENGTH Function Syntax:

LENGTH(s) Description:

Returns the number of characters in the specified string.s. For CLOB or NCLOB, it returns the

length in bytes. Example:

SELECT TOP 1 LENGTH('length in char') "length" FROM users; Retrieves: length

14

LOCATE Function Syntax:

LOCATE(haystack, needle) Description:

Returns the position of sub-string needle within string haystack. Returns 0 if needle is not found

from haystack. Example:

SELECT TOP 1 LOCATE('length in char', „char‟) "locate" FROM users; Retrieves: Locate

11

LOWER Function Syntax

LOWER(s) Description

Converts all characters in a string s to lowercase. The LOWER function is identical to the LCASE function. Example

SELECT TOP 1 LOWER('Ant') "lower" FROM users;

Retrieves: lower

ant

Page 40: hana sql

SAP In-Memory Database SQL Reference Manual

36

LPAD Function Syntax:

LPAD(target, n[, pattern]) Description:

Pad the left side of a target string with spaces or pattern to make the target n characters in length.. Example:

SELECT TOP 1 LPAD('end', 15, '12345') "lpad" FROM users;

Retrieves: lpad

123451234512end

LTRIM Function Syntax:

LTRIM(target [, remove_set]) Description:

Removes from the leftmost of target all of the characters that appear in remove_set until reaching a character not in remove_set and then returns the result. If remove_set is not specified, a single blank

space is used. Please note that remove_set is treated as a set of characters and not a search string. Example:

SELECT TOP 1 LTRIM('babababAabend','ab') "ltrim" FROM users;

Retrieves: ltrim

Aabend

REPLACE Function Syntax:

REPLACE (original_string, search_string, replace_string) Description:

Searches in original_string for all occurrences of search_string and replaces them with replace_string. If original_string is an empty string, then the result will also be an empty string.

If two overlapping substrings match the search_string in the original_string, then only the first occurrence will be replaced with the replace_string.

If original_string does not contain any occurrence of search_string, then the function returns the

original_string unchanged. If original_string, search_string, or replace_string is NULL, then the function returns NULL.

Example:

SELECT TOP 1 REPLACE ('DOWNGRADE DOWNWARD','DOWN', 'UP') "replace" FROM users;

Retrieves: replace

UPGRADE UPWARD

Page 41: hana sql

SAP In-Memory Database SQL Reference Manual

37

RIGHT Function Syntax:

RIGHT(target, n) Description:

Returns the rightmost n characters of a string target. Example:

SELECT TOP 1 RIGHT('HI0123456789', 3) "right" FROM users; Retrieves: right

789

RPAD Function Syntax:

RPAD (target, n[, pattern]) Description:

Pad the right side of a target string with spaces or pattern to make the target n characters in length. Example:

SELECT TOP 1 RPAD('end', 15, '12345') "right padded" FROM users; Retrieves: right padded

end123451234512

RTRIM Function Syntax:

RTRIM (target [,remove_set ]) Description:

Removes from the rightmost of target all of the characters that appear in remove_set until reaching a character not in remove_set and then returns the result. If remove_set is not specified, a single blank

space is used. Please note that remove_set is treated as a set of characters and not a search string.

Example:

SELECT TOP 1 RTRIM ('endabAabbabab','ab') "rtrim" FROM users;

Retrieves: rtrim

endabA

SUBSTRING Function Syntax:

SUBSTRING (target, start_position [, string_length]) Description:

Returns a substring of a string target starting from the start_position of the string. SUBSTRING can

either return the remaining part of a string from the start_position or, optionally, a number of characters set by the string_length parameter.

Page 42: hana sql

SAP In-Memory Database SQL Reference Manual

38

If start_position is less than 0, then it is considered as 1. If string_length is less than 1, then an empty string is returned as the result. Example:

SELECT TOP 1 SUBSTRING('1234567890',4,2) "substring" FROM users;

Retrieves: substring

45

SUBSTR_AFTER Function Syntax:

SUBSTR_AFTER(target, pattern) Description:

Returns a substring of the target string that follows the first occurrence of the pattern argument in the target string. If target does not contain a substring which is the same as pattern, then an empty string is

returned.

If pattern is an empty string, then target is returned. If target or pattern is NULL, then NULL is returned. Example:

SELECT TOP 1 SUBSTR_AFTER('Hello My Friend','My ') "substr after" FROM users;

Retrieves: substr after

Friend

SUBSTR_BEFORE Function Syntax:

SUBSTR_BEFORE(target, pattern) Description:

Returns a substring of the target string before the first occurrence of the pattern argument in the target string. If target does not contain a substring which is the same as pattern, then an empty string is

returned. If pattern is an empty string, then target is returned. If target or pattern is NULL, then NULL is returned. Example:

SELECT TOP 1 SUBSTR_BEFORE('Hello My Friend','My') "substr before" FROM users; Retrieves: substr before

Hello

TRIM Function Syntax:

TRIM ([[LEADING | TRAILING | BOTH] trim_char FROM] target_string ) Description:

Returns a string after trimming a trim_char from trim_source string. The trimming operation is carried

out either from the start (LEADING), end (TRAILING) or both(BOTH) ends of the target_string.

Page 43: hana sql

SAP In-Memory Database SQL Reference Manual

39

If either target_string or trim_char is a null value, then a NULL is returned. If no option is specified, it removes both the leading and trailing substring trim_char from

target_string string. If trim_char is not specified, then a single blank space will be used.

Example:

SELECT TOP 1 TRIM („a‟ FROM „aaa123456789aa‟) "trim both" FROM users; Retrieves: trim both

123456789

SELECT TOP 1 TRIM (LEADING ‟a‟ FROM „aaa123456789aa‟) "trim leading" FROM users;

Retrieves: trim leading

123456789aa

UCASE Function Syntax :

UCASE(target) Description:

Converts all characters in the target string to uppercase Example:

SELECT TOP 1 UCASE('Ant') "ucase" FROM users;

Retrieves: ucase

ANT

UNICODE Function Syntax :

UNICODE(c) Description:

Returns an integer containing the Unicode code point of the first character in the string, or NULL if the first character is not a valid encoding.

Example:

SELECT TOP 1 UNICODE('#') "unicode" FROM users;

Retrieves: unicode

54620

UPPER Function Syntax:

UPPER(target) Description:

Converts all characters in the target string to uppercase. Example:

Page 44: hana sql

SAP In-Memory Database SQL Reference Manual

40

SELECT TOP 1 UPPER('Ant') "uppercase" FROM users; Retrieves: uppercase

ANT

Page 45: hana sql

SAP In-Memory Database SQL Reference Manual

41

SQL Statements This chapter describes the SQL statements that are supported by the HDB.

ALTER TABLE

SQL Syntax: ALTER TABLE table_name { <add_column_clause> | < drop_column_clause> | <add_primary_key_clause> | < drop_primary_key_clause> | < preload_clause> | <table_conversion_clause>

| < move_clause> }

[WITH PARAMETERS ( parameter_key_value, ... ) ]

Parameters:

add_column_clause::= ADD ( column_definition, ... )

drop_column_clause ::=DROP ( column_name, ... )

add_primary_key_clause ::= ADD [CONSTRAINT constraint_name] PRIMARY KEY ( column_name, ... )

CONSTRAINT

Specifies the name of a constraint. PRIMARY KEY A primary key constraint is a combination of a NOT NULL constraint and a UNIQUE constraint. It prohibits multiple rows from having the same value in the same column.

drop_primary_key_clause ::= DROP PRIMARY KEY

preload_clause ::= PRELOAD ALL | PRELOAD ( column_name ) | PRELOAD NONE

PRELOAD sets/removes the preload flag of the given tables or columns. As a consequence,

these tables are automatically loaded into memory after an index server start. The current status of the preload flag is visible in the system table TABLES, column PRELOAD, possible values ('FULL', 'PARTIALLY', 'NO' ) and in system table TABLE_COLUMNS, column PRELOAD, possible values ('TRUE', 'FALSE').

table_conversion_clause ::= [ MODIFY TYPE ] [ ROW | COLUMN ] [ THREADS int_constr ] [ BATCH

batch_size ] MODIFY TYPE ROW | COLUMN This command is used to convert the table storage from ROW to COLUMN or from COLUMN to ROW.

THREADS int_const Specifies how many threads should be used in parallel for table conversion. Default: The default value is TABLE_CONVERSION_PARALLELISM that is, the number of CPU cores

specified in the indexserver.ini file. BATCH int_const

Page 46: hana sql

SAP In-Memory Database SQL Reference Manual

42

Specifies the number of rows inserted in batch. Insert into column table will be immediately committed after every int_const records insertion, which may reduce memory consumption. BATCH option can be used only when the table is converted from ROW to COLUMN. The default value is 2147483647.

A new table with a different storage type can be created from an existing table by copying the existing table's columns and data. This command is used to convert the table storage from ROW to COLUMN or from COLUMN to ROW. If the source table was in ROW storage, then the created table will be in COLUMN storage.

move_clause ::= MOVE TO LOCATION <host:port>

MOVE TO LOCATION A column store table can be moved to the specified location in a distributed environment.

When a table is in row store need to be moved, convert the row table to a column table first and then move to a new location using this command.

WITH PARAMETERS ( <parameter_key_value>, ... ) Column store-specific options can be passed in using the "WITH PARAMETERS" clause.

• Keys and single values can be any string constant • Duplicate keys are allowed • Keys are automatically mapped into their uppercase representation

parameter_key_value ::=

<string_literal> = <string_literal> |

<identifier> = <string_literal> | <string_literal> = (<string_literal>, ... )

Current parameters

„AUTO_MERGE‟ = 'ON' | 'OFF' Default=ON Automatic delta merge triggered by memwatcher.

„CONCAT_ATTRIBUTE‟ = (new_att, exist_att_list) Creating concatenated attributes:

new_att:= „string_literal‟ exist_att_list = 'string_literal' | exist-att-list ',' 'string_literal'

„DELETE_CONCAT_ATTRIBUTE‟ := exist_att Deleting concatenated attributes:

exist_att := 'string_literal'

„TREX_FLAGS‟ = ('column_name','flags'), Flags are the implementation flags; the integer value is currently between 0 and 67108864. „INDEX_PROPERTY‟ = ('prop#', 'value')

Changing column table properties ALTER TABLE <table_name> WITH PARAMETERS („INDEX_PROPERTY‟ = ('prop#', 'value') )

„PARTITION_SPEC‟ = 'partition spec',

Page 47: hana sql

SAP In-Memory Database SQL Reference Manual

43

For example, 'HASH 2 a, b' where 2 is the number of parts to create and 'a' and 'b' are the columns that are used to create that hash value for each row. The ALTER TABLE either splits or merges the table. Use 'MERGE' as partition spec to merge the parts. The tables have to be merged before they can be split using a different partition specification.

„DSO_ACTIVATE_REQUESTS‟ = (rid_list) dso-activation of the given request IDs in the corresponding DSO index. rid_list has to be a comma-separated list of strings. Activation in the DSO sense means changing the active data of the DSO index by applying the changes of the given requests residing in the Activation Queue. This parameter will only work for DSO indexes.

„DSO_ROLLBACK_REQUESTS‟ = (rid_list)

dso-rollback of the given RequestIds in the corresponding DSO index.

rid_list has to be a comma-separated list of strings. Rollback in the DSO sense means

removing the changes in the active data of the DSO that were caused by the given requests.

This parameter will only work for DSO indexes.

Description: The ALTER TABLE statement adds, deletes or modifies a column from a table and creates or drops a

primary key. It can also delete or add multiple columns at a time. The new column will initially be filled with a default value. If a default is not specified, then the value is NULL. Example 1: ALTER TABLE T1 ADD (column_a VARCHAR(10));

ALTER TABLE T1 WITH PARAMETERS('CONCAT_ATTRIBUTE'=('A$B','A','B'));

Page 48: hana sql

SAP In-Memory Database SQL Reference Manual

44

ALTER USER SQL Syntax: ALTER USER user_name IDENTIFIED BY password ALTER USER user_name IDENTIFIED EXTERNALLY AS external_identity

Parameters: IDENTIFIED BY You can change a user‟s password with this command

IDENTIFIED EXTERNALLY You can change the external authentication. For information about external identities, contact your

system administrator. Description: The ALTER USER statement modifies the database user.

Users created with IDENTIFIED BY cannot be changed to EXTERNALLY and vice versa, the users created with EXTERNALLY cannot be changed to IDENTIFIED BY.

Example: ALTER USER my_user IDENTIFIED BY AAAAAAa1;

Page 49: hana sql

SAP In-Memory Database SQL Reference Manual

45

CREATE CALCULATION SCENARIO SQL Syntax:

CREATE CALCULATION SCENARIO name USING <xml> [WITH PARAMETERS ( <parameter_key_value>, ... ) ]

Parameters: xml ::= string_literal

parameter_key_value ::=

'DEFAULT_SCHEMA' = schema_name |'INMEMORY_SCENARIO' = '0' |'INMEMORY_SCENARIO' = '1'

|'EXPOSE_NODE' = ( node_name, view_name )

|'EXPOSE_NODE' = ( node_name, schema_name, view_name )

Description: The CREATE CALCULATION SCENARIO statement creates a calculation scenario.

Please note that a calculation scenario is not a default catalog object, so it cannot be accessed via a SELECT statement after its creation. A column view of type calculation is required on top of the scenario to query it.

As it is not a catalog object, it is also not linked to a catalog schema. The first part of the name can be rather seen as a package in which the scenario is created. This implies that a drop of a (database)

schema does not drop the calculation scenarios. The scenario is defined with the used XML-string which has to be formatted as described in the XSD. The default schema defines on the one hand the package in which the scenario is created (if not defined explicitly), and the schema for the views on top listed in the expose nodes on the other.

It can be either in-memory only (set optional parameter value 'INMEMORY_SCENARIO' = '1') or persistent. The default scenario is persistent and stored in the repository. With an expose node item it is possible to directly create a column view of type calculation on top of a specified node on top of the scenario. The view name is defined in 'view_name'. The referenced node has to be specified in 'node_name'.

Note that sub-transactions have started (and committed) in order to create the views.

Note: For application development, do not use these exposed node items. Instead, create the column views of type calculation manually. Example

DROP TABLE TEST1;

CREATE INSERT ONLY COLUMN TABLE TEST1(A INTEGER, B DOUBLE);

insert into test1 values ( 1, 2);

insert into test1 values ( 11, 22);

insert into test1 values ( 111, 222);

DROP CALCULATION SCENARIO SYSTEM.DEMO_PROJECTION_OP cascade;

CREATE CALCULATION SCENARIO SYSTEM.DEMO_PROJECTION_OP USING '

<?xml version="1.0" encoding="utf-8"?>

<cubeSchema version="2" operation="createCalculationScenario">

<calculationScenario schema="SYSTEM" name="DEMO_PROJECTION_OP">

Page 50: hana sql

SAP In-Memory Database SQL Reference Manual

46

<dataSources>

<tableDataSource name="demo_projection_datasource" schema="SYSTEM"

table="TEST1">

<attributes>

<allAttribute/>

</attributes>

</tableDataSource>

</dataSources>

<calculationViews>

<projection name="demo_projection" defaultViewFlag="true">

<inputs>

<input name="demo_projection_datasource" />

</inputs>

<attributes>

<allAttribute />

<calculatedAttribute name="C" datatype="double" isViewAttribute="true">

<formula>"A" * "B"</formula>

</calculatedAttribute>

</attributes>

<filter>"C" &gt; 1</filter>

</projection>

</calculationViews>

</calculationScenario>

</cubeSchema>'

;

DROP VIEW SYSTEM.MYCALCVIEW;

CREATE COLUMN VIEW SYSTEM.MYCALCVIEW TYPE CALCULATION

WITH PARAMETERS

('PARENTCALCINDEXPACKAGE'='SYSTEM',

'PARENTCALCINDEX'='DEMO_PROJECTION_OP',

'PARENTCALCNODE'='demo_projection');

SELECT * FROM SYSTEM.MYCALCVIEW;

DROP CALCULATION SCENARIO SYSTEM.DEMO_PROJECTION_OP CASCADE;

Page 51: hana sql

SAP In-Memory Database SQL Reference Manual

47

CREATE COLUMN VIEW

SQL Syntax:

CREATE COLUMN VIEW view_name [ ( column_name, ... ) ] [ TYPE <types> ] AS <subquery> [ WITH PARAMETERS (<parameter_key_value>, ... ) ]

Parameters:

types := OLAP | JOIN | HIERARCHY | PROPERTY | LANGUAGE | CALCULATION | FBO

parameter_key_value ::=

<string_literal> = <string_literal> |

<identifier> = <string_literal> | <string_literal> = (<string_literal>, ... )

string_literal ::= description | index_type | join_index | join_condition | join_path | constraint | index_alias | join_index_type | join_index_estimation |view_attribute | view | default_view | semantic_relation | rfc_destination | auto_replication| key_figure | unit_conversion |

optimize_metamodel | free_style_search_attribute |all_attrs_free_style_relevant | flags | characteristic | hierarchy_definition_type | hierarchy_definition description ::= „DESCRIPTION‟ = string_literal

index_type ::= „INDEXTYPE‟ = int_const

OLAP_INDEX = 5,

JOIN_INDEX = 6,

CALC_INDEX = 11

join_index ::= „JOININDEX‟ = table_name Table name to be joined. Join_index can be repeated as desired.

join_condition ::= „JOINCONDITION‟ = ( string_literal , table_name , column_name , table_name ,column_name ) |„JOINCONDITION‟ = ( string_literal , table_name , column_name , table_name, column_name , string_literal , int_const , int_const ) |„JOINCONDITION‟ = ( string_literal ,table_name , column_name , table_name , column_name , string_literal , int_const , int_const', string_literal )

|„JOINCONDITION‟ = ( string_literal , table_name , column_name , table_name ,column_name , string_literal , int_const , int_const' , string_literal , string_literal )

Specifies the join attributes, join condition can be repeated as desired. Example: join_condition = „name, table1, field1, table2, field2, [constraint]‟. join_path ::=

„JOINPATH' = ( string_literal , string_literal ) |„JOINPATH‟ = ( string_literal , string_literal ,string_literal ) JOINPATH can be repeated as desired. Example: join_path = „name, join1, join2, [constraint]‟

constraint ::= „CONSTRAINT‟ = ( string_literal , int_const , string_literal , table_name , column_name, string_literal , string_literal [ , int_const , string_literal ] )

Page 52: hana sql

SAP In-Memory Database SQL Reference Manual

48

Example: constraint=‟name,type,location,indexed,attrname,operator,value[,specialConstraintType, defaultValue]‟

index_alias ::= „INDEXALIAS‟ = ( table_name = string_literal ) Species an alias for an index. join_index_type ::= „JOININDEXTYPE‟ = int_const Example: join_index_type =(0 None, 1 fact table, 2 d table, 3 x table, 4 y table, 5 hirearchy, 6

s table, 7 external object, 8 conv table) join_index_estimation ::= „JOININDEXESTIMATION‟ = int_const

join_index_estimation specifies number of estimated documents in an index

view_attribute ::= „VIEWATTRIBUTE‟ = ( string_literal , table_name , column_name , string_literal , string_literal , string_literal ) |‟VIEWATTRIBUTE„ = ( string_literal , table_name , column_name , string_literal , string_literal ,string_literal , string_literal ) |‟VIEWATTRIBUTE‟ = ( string_literal , table_name , column_name , string_literal , string_literal ,string_literal , string_literal , string_literal )

|„VIEWATTRIBUTE‟ = ( string_literal , string_literal ) Example: view_attribute = (name, table, field, joinPath, viewName, type, defaultDefinition, [expression])

view ::= „VIEW‟ = (string_literal , table_name [ , string_literal ]) view = (name, anchor table)

default_view ::= „DEFAULTVIEW‟ = string_literal

Specifies default view name.

semantic_relation ::= „SEMANTICRELATION‟ = ( string_literal , string_literal , string_literal , string_literal )

Example: semantic_relation = name, joinPath, view, type …

key_figure ::= „KEYFIGURE‟ = ( column_name , int_const ) | „KEYFIGURE‟ = ( column_name , int_const , string_literal ) | „KEYFIGURE‟ = ( column_name , string_literal , int_const ) | „KEYFIGURE‟ = ( column_name , string_literal , int_const , string_literal )

| „KEYFIGURE‟ = ( column_name , string_literal , int_const , string_literal , RESTRICTION = string_literal) | „KEYFIGURE‟ = ( column_name , string_literal , int_const , string_literal , string_literal , RESTRICTION= string_literal ) | „KEYFIGURE‟ = ( column_name , int_const , FORMULA = string_literal , DESCRIPTION = string_literal , UNITCONVERSIONNAME = string_literal , EXPRESSION = string_literal , EXPRESSIONFLAGS = int_const )

| „KEYFIGURE‟ = ( column_name , int_const , FORMULA = string_literal , DESCRIPTION = string_literal , UNITCONVERSIONNAME = string_literal , EXPRESSION = string_literal , EXPRESSIONFLAGS = int_const , RESTRICTION = string_literal ) | „KEYFIGURE‟ = ( column_name , int_const , FORMULA = string_literal , DESCRIPTION = string_literal , UNITCONVERSIONNAME = string_literal , EXPRESSION = string_literal , EXPRESSIONFLAGS = int_const , INDEXID = table_ref_trex , ATTRIBUTE = column_name )

Page 53: hana sql

SAP In-Memory Database SQL Reference Manual

49

| „KEYFIGURE‟ = ( column_name , int_const , FORMULA = string_literal , DESCRIPTION = string_literal , UNITCONVERSIONNAME = string_literal , EXPRESSION = string_literal , EXPRESSIONFLAGS = int_const , INDEXID = table_ref_trex , ATTRIBUTE = column_name , RESTRICTION = string_literal , ALIAS = int_const )

Possible key_figure values are as follows: keyFigure,defaulttype keyFigure,defaulttype,description keyFigure,formula,defaulttype keyFigure,formula,defaulttype,restriction=x keyFigure,formula,defaulttype,description

keyFigure,formula,defaulttype,description,restriction=x keyFigure,defaulttype,formula=x,description=x,unitConversionName=x,expression=x,expressionFlags=x keyFigure,defaulttype,formula=x,description=x,unitConversionName=x,expression=x,expressi

onFlags=x,restriction=x keyFigureName,defaulttype,formula=x,description=x,unitConversionName=x,expression=x,ex

pressionFlags=x,indexId=x,attribute=x keyFigureName,defaulttype,formula=x,description=x,unitConversionName=x,expression=x,expressionFlags=x,indexId=x,attribute=x,restriction=x,alias=x

unit_conversion ::= „UNITCONVERSION‟ = ( string_literal , table_name , column_name , string_literal , column_name , string_literal , name ) Example: unitConversion=

unitConversionName,indexId,sourceUnitAttribute,destinationUnit,factorAttribute,joinPathName

optimize_metamodel ::= „OPTIMIZEMETAMODEL‟ = int_const Default value for OPTIMIZEMETAMODEL = 1.

free_style_search_attribute ::= „FREESTYLESEARCHATTRIBUTE‟ = string_literal free_style_search_attribute specifies a free style search relevant variables.

flags ::= „FLAGS‟ = int_const

characteristic ::= „CHARACTERISTIC‟ = ( string_literal characteristic_param_list )

characteristic_param_list ::= SIDATTRIBUTE = column_name

| KEYATTRIBUTE = column_name | TEXTATTRIBUTE = column_name | EXTERNALATTRIBUTE = column_name | HIERARCHYNAME = string_literal | HIERARCHYINDEX = string_literal | string_literal *

Example: characteristic (name, [, sidAttribute, keyAttribute, textAttribute,externalAttribute,

hierarchyName, hierarchyIndex, description])

register_view_for_ap_check ::= 'REGISTERVIEWFORAPCHECK' = int_const Register_view_for_ap_check is required to define that a column view (join, olap, or calculation) is registered for the AnalyticalPrivileges check. hierarchy_definition_type ::= „HIERARCHYDEFINITIONTYPE‟ = string_literal

Switch deciding which hierarchy definition format to take. Currently valid values are

o „POLESTAR‟ (default) – hierarchy definition is taken from all other hierarchy parameters except of HIERARCHYDEFINITION, deprecated.

o „JSON‟ – hierarchy definition is extracted solely from parameter HIERARCHYDEFINITION, the recommended approach when applicable.

hierarchy_definition := „HIERARCHYDEFINITION‟ = string_literal

Page 54: hana sql

SAP In-Memory Database SQL Reference Manual

50

JSON string containing the complete hierarchy definition.

Description: The CREATE COLUMN VIEW statement is used to create a column view.

TYPE clause can be omitted and default type is JOIN_INDEX. SQL expression and PARAMETERS cannot be defined together. SQL expression only, or PARAMETERS only, is allowed. A column view can be created when the kernel has metadata information about all physical indexes of the column view.

Creating a column view referencing row tables, row views or other column views is not allowed. SQL Join with column views is allowed. When a PARAMETERS clause is defined,

Column list can't be defined. Object names of view attributes will be field names. At least one viewAttribute must be defined.

If there is a conflict between TYPE clause and indexType parameter, an error will be thrown. When a column table is dropped, all column views referencing the table are dropped at the same time.

Example 1: Creating a simple JOIN view DROP TABLE CUSTOMER;

DROP TABLE ORDERS;

CREATE COLUMN TABLE CUSTOMER ( ID INT PRIMARY KEY, NAME VARCHAR(30) );

CREATE COLUMN TABLE ORDERS ( ID INT PRIMARY KEY, CID INT, AMOUNT DECIMAL(10,2) );

INSERT INTO CUSTOMER VALUES (1, 'Cust01');

INSERT INTO ORDERS VALUES (1, 1, 10);

INSERT INTO ORDERS VALUES (2, 1, 110);

INSERT INTO ORDERS VALUES (3, 1, 120);

INSERT INTO CUSTOMER VALUES (2, 'Cust02');

INSERT INTO ORDERS VALUES (4, 2, 110);

CREATE COLUMN VIEW CUSTORDERS TYPE JOIN WITH PARAMETERS (

joinIndex=CUSTOMER,joinIndexType=0,

joinIndex=ORDERS,joinIndexType=0,

joinCondition=('JC01', CUSTOMER, ID, ORDERS, CID, '', 0, 0),

joinPath=('JP01', 'JC01'),

view=('V_CUSTORDERS', CUSTOMER),

defaultView='V_CUSTORDERS',

viewAttribute=('NAME', CUSTOMER, NAME, 'JP01', 'default', 'attribute'),

viewAttribute=('AMOUNT', ORDERS, AMOUNT, 'JP01', 'default', 'attribute'),

constraint=('CONSTR1', 0, '', CUSTOMER, ID, 'eq', '$$CID$$'),

optimizemetamodel=1

);

SELECT * FROM CUSTORDERS WITH PARAMETERS ('PLACEHOLDER' = ('$$CID$$' , '1'));

Example 3: Creating a calculation view

Page 55: hana sql

SAP In-Memory Database SQL Reference Manual

51

// The view references node "myNode" of the specified calculation scenario

"myPackage"."myScenario"}

CREATE COLUMN VIEW calculationView TYPE CALCULATION

WITH PARAMETERS ( ['PARENTCALCINDEXPACKAGE ’=’myPackage',]

'PARENTCALCINDEX'='myScenario',

'PARENTCALCNODE'='myNode')

Example 4: Creating a hierarchy view CREATE COLUMN VIEW h17$hli

TYPE hierarchy

WITH PARAMETERS (

hierarchyDefinitionType' = 'JSON',

hierarchyDefinition = '{"sourceType":"recursive", "sourceQuery":"SELECT pred,succ

FROM h17$hli", "rootNode":-1}');

Page 56: hana sql

SAP In-Memory Database SQL Reference Manual

52

CREATE INDEX

SQL Syntax:

CREATE [BTREE | CPBTREE] INDEX index_name ON table_name ( column_name, ... ) [ ASC | DESC ]

Parameters:

BTREE | CPBTREE Used to select the kind of index to use. When column data types are character string types, binary string types, decimal types, or when the constraint is a composite key, or a non-unique constraint, the default index type is CPBTREE; otherwise, BTREE is used.

If neither BTREE nor CPBTREE keyword is specified, then SAP HANA Database chooses the appropriate index type. ASC | DESC Specifies whether the index should be created in ascending or descending order. These keywords can be only used in the btree index.

Description: The CREATE INDEX statement creates an index.

Example:

CREATE INDEX idx ON A ( B );

Page 57: hana sql

SAP In-Memory Database SQL Reference Manual

53

CREATE ROLE SQL Syntax: CREATE ROLE role_name

Description:

A role is a named collection of privileges. If you want to allow several database users to perform the same actions, you can create a role, grant the needed privileges to this role, and grant the role to the different database users. The default role is PUBLIC, every database user has been granted this role implicitly. Users who have system privilege ROLE ADMIN can CREATE, or DROP roles. Example:

CREATE ROLE my_role;

Page 58: hana sql

SAP In-Memory Database SQL Reference Manual

54

CREATE SCHEMA SQL Syntax: CREATE SCHEMA schema_name [OWNED BY] name

Parameters:

OWNED BY Specifies the name of the schema owner. Description:

The CREATE SCHEMA statement creates a schema in the current database.

Example: CREATE SCHEMA my_schema OWNED BY system;

Page 59: hana sql

SAP In-Memory Database SQL Reference Manual

55

CREATE SEQUENCE

SQL Syntax:

CREATE SEQUENCE sequence_name [ <sequence_parameter_list> ] [RESET BY <subquery>]

Parameters: sequence_parameter_list ::= sequence_parameter, ...

sequence_parameter ::=

INCREMENT BY integer

| START WITH integer | MAXVALUE integer | NOMAXVALUE

| MINVALUE integer | NOMINVALUE | CYCLE | NOCYCLE

INCREMENT BY

Defines the amount the next sequence value is incremented from the last value assigned. The default is 1. Specify a negative value to generate a descending sequence. An error is returned if the INCREMENT BY value is 0 START WITH

Defines the starting sequence value. If you do not specify a value for the START WITH clause, MINVALUE is used for ascending sequences and MAXVALUE is used for descending sequences.

MAXVALUE

Defines the largest value generated by the sequence and must be between 0 and (2^63)-1 = 9223372036854775807.

NOMAXVALUE

When MAXVALUE is not specified, the maximum value for an ascending sequence is (2^63)-1 and

the maximum value for a descending sequences is -1.

MINVALUE

The minimum value of a sequence can be specified after MINVALUE and is between 0 and -4611686018427387903. NOMINVALUE When MINVALUE is not specified, the minimum value for an ascending sequence is 1 and the minimum value for a descending is -4611686018427387903.

CYCLE The sequence number will be reused after it reaches its maximum or minimum value. NOCYCLE Default option. The sequence number will not be reused after it reaches its maximum or minimum value.

Page 60: hana sql

SAP In-Memory Database SQL Reference Manual

56

Description: The CREATE SEQUENCE statement is used to create a sequence.

A sequence is used to generate unique integers. CURRVAL is used to get the current value of the sequence and NEXTVAL is used to get the next value of the sequence. Example 1: sequence_name.CURRVAL

sequence_name.NEXTVAL

During the rebooting of the database, database automatically executes the RESET BY statement and

returns the result to assign the sequence value. Therefore, no additional effort is needed to manage a sequence.

Example 2: If the sequence s is used to create a unique key on column A in the table R, then after a database is restarted, a UNIQUE key value can be created by automatically assigning the maximum value of column A to the sequence value using a RESET BY statement as follows: CREATE SEQUENCE s RESET BY SELECT IFNULL(MAX(a), 0) + 1 FROM r;

Page 61: hana sql

SAP In-Memory Database SQL Reference Manual

57

CREATE SYNONYM SQL Syntax: CREATE [PUBLIC] SYNONYM synonym_name FOR name

Description: The CREATE SYNONYM creates an alternate name for a table, view, or sequence.

You can use a synonym to re-point functions and stored procedures to differing tables, views or sequences without needing to re-write the function or stored procedure.

Specify PUBLIC to create a public synonym.

Example: CREATE SYNONYM a_synonym FOR a;

Page 62: hana sql

SAP In-Memory Database SQL Reference Manual

58

CREATE TABLE SQL Syntax:

CREATE [ <table_type> ] TABLE table_name <table_contents_source> [ WITH PARAMETERS (

<parameter_key_value>, ... ) ]

Parameters: table_type:

table_type::= COLUMN | ROW | GLOBAL TEMPORARY COLUMN | LOCAL TEMPORARY COLUMN

ROW, COLUMN

If the majority of access is through a large number of tuples but with only a few selected attributes, COLUMN-based storage should be used. If the majority of access involves selecting

a few records with all attributes selected, ROW-based storage is preferable. The HDB uses a combination to enable storage and interpretation in both forms. You can define the type of organization for each table. The default value is ROW. GLOBAL TEMPORARY COLUMN Table definition is globally available while data is visible only to the current session. The table

is truncated at the end of the session. LOCAL TEMPORARY COLUMN The table definition and data is visible only to the current session. The table is truncated at the end of the session.

table_contents_source:

table_contents_source ::= ( <table_element>, … )|[ (column_name, ...) ]

<as_table_subquery> [ WITH [NO] DATA ] ]

table_element ::=column_definition column_constraint | table_constraint (

column_name, ... ) column_definition ::= column_name data type [<column store data type>]

[<ddic data type>] [DEFAULT default_value] [GENERATED ALWAYS AS

<expression> ]

DEFAULT Default specifies a value to be assigned to the column if an INSERT statement does not provide a value for the column.

DATA TYPE in column definition Available column store data types are CS_ALPHANUM, CS_UNITEDECFLOAT, CS_TEXT, CS_DATE, CS_TIME, CS_FIXEDSTRING. Available DDIC data types are ABAP_CHAR, ABAP_DATE, ABAP_DECFLOAT16, ABAP_DECFLOAT34, ABAP_FLOAT, ABAP_HEX, ABAP_INT, ABAP_INT1,

ABAP_INT2, ABAP_NUM, ABAP_PACKED, ABAP_STRING, ABAP_TIME, ABAP_XSTRING.

GENERATED ALWAYS AS Specifies the expression to generate the column value in runtime. column_constraint ::= NULL | NOT NULL | UNIQUE [BTREE | CPBTREE]

|PRIMARY KEY [BTREE | CPBTREE]

Page 63: hana sql

SAP In-Memory Database SQL Reference Manual

59

NULL | NOT NULL The NOT NULL constraint prohibits a column value from being NULL. If NULL is specified it is not considered a constraint, it represents a column

that may contain a null value. The default is NULL.

UNIQUE Specifies a column as a unique key. A composite unique key enables the specification of multiple columns as a unique key. With a unique constraint, multiple rows cannot have the same value in the same column.

PRIMARY KEY A primary key constraint is a combination of a NOT NULL constraint and a UNIQUE constraint. It prohibits multiple rows from having the same value in

the same column.

BTREE | CPBTREE Specifies the index type. When column data types are character string types, binary string types, decimal types, or when the constraint is a composite key, or non-unique constraint, the default index type is CPBTREE. Otherwise, BTREE is used. BTREE keyword has to be used in order to use B+-tree index and the CPBTREE

keyword has to be used for the CPB+-tree index. If the index type is omitted, the HDB chooses the appropriate index considering the column data types. table_constraint ::=UNIQUE [BTREE | CPBTREE] | PRIMARY KEY [BTREE |

CPBTREE] This defines a table constraint which can be used on one or more columns of a table. There are two kinds of a table constraint. They are: UNIQUE

Specifies a uniqueness constraint for a column. This prevents multiple rows from having the same values in the same column list.

PRIMARY KEY A primary key constraint is a combination of the NOT NULL and UNIQUE constraints. It creates a unique column that can be always be used to locate rows uniquely within a table.

BTREE | CPBTREE Specifies the index type. When column data types are character string types, binary string types, decimal types, or when the constraint is a composite key, or non-unique constraint, the default index type is CPBTREE, BTREE is used in all other cases.

BTREE keyword has to be used in order to use the B+-tree index and the CPBTREE keyword has to be used for the CPB+-tree index. If the index type is omitted, the HDB chooses the appropriate index considering the column data types.

as_table_subquery ::=AS TABLE as_table_name | AS ( <select_query>)

Page 64: hana sql

SAP In-Memory Database SQL Reference Manual

60

Creates a table and fills it with the data from as_table_name or computed by the <select_query>. Only NOT NULL constraints are copied by this clause. If column_names are specified, specified column_names override the column names from as_table_name or select_query.

WITH [NO] DATA

Specifies whether the data is copied from as_table_name or <select_query>. The default value is WITH DATA.

parameter_key_value ::=

<string_literal> = <string_literal> | <identifier> = <string_literal> | <string_literal> = (<string_literal>, ... )

Options that can be used only for column store tables can be passed in using "WITH PARAMETERS" clause. Parameter keys and string values can be any string constant. Duplicate keys are allowed. Keys are automatically mapped into their upper-case form.

parameter_key_value

'AUTO_MERGE' = 'ON' | 'OFF' Default=ON Automatic delta merge triggered by memwatcher. 'SESSION_TYPE' = 'SIMPLE' | 'HISTORY' Default = 'SIMPLE'

Creates a table with a particular transaction session type. Tables with session type HISTORY support time travel. 'COMPRESSION' = ('column_name', 'compression_type'): Sets the compression for the specified column. ('compression_type' = 'PREFIXED' | 'SPARSE' | 'CLUSTERED' | 'INDIRECT' | 'RLE')

'INDEX' = ('column_name', 'index_type') Sets the inverted index for the specified column. ('index_type' 'FULL' | 'SIGNATURE') 'FAST_PREPROCESS' = 'ON' | 'OFF' Turns fast preprocessing on or off. This feature is used for column tables that have attributes that should support text-search on attribute of type 'AETEXT'.

'LOCATION' = 'host:port' Specifies the target node for table creation with host:port. If not provided, the table will be automatically assigned to one node. This option can be used for both row store and column store tables in a distributed environment. 'PARTITION_SPEC' = 'partition spec',

For example 'HASH 2 a, b' where 2 is the number of parts to create and 'a' and 'b' are the columns that are used to create that hash value for each row. 'TREX_FLAGS' = ('column_name','flags'), Flags are the implementation flags, integer value is currently between 0 and 67108864.

Description: The CREATE TABLE statement creates a table. Tables are created without data except when

as_table_subquery is used with the WITH DATA option.

Page 65: hana sql

SAP In-Memory Database SQL Reference Manual

61

Example:

CREATE TABLE A ( A INT PRIMARY KEY, B INT);

Page 66: hana sql

SAP In-Memory Database SQL Reference Manual

62

CREATE TYPE SQL Syntax: CREATE TYPE type_name AS TABLE ( <table_element>, ... )

Parameters:

table_element ::=column_definition column_constraint | table_constraint ( column_name, ... )

Description:

The CREATE TYPE statement creates a user-defined type.

A user can create tables that have the same specifications as a user-defined table type.

Example: CREATE TYPE my_type AS TABLE ( column_a DOUBLE );

Page 67: hana sql

SAP In-Memory Database SQL Reference Manual

63

CREATE USER SQL Syntax: CREATE USER user_name IDENTIFIED BY password CREATE USER user_name IDENTIFIED EXTERNALLY AS [external_identity]

Parameters: password ::= In the HDB there are two kinds of users, internally and externally authenticated users. Internally authenticated users are authenticated using a user name and a password. The password for a user has to be changed regularly.

external_identity ::= External users are authenticated using an external system, e.g. a Kerberos

system. Such users do not have a password. For detailed information about external identities, contact your domain administrator. Description: The CREATE USER statement creates a new database user.

The specified user name must not be identical to the name of an existing user, role, or schema. Password must follow the rules defined for the current database. The password rules include the minimal password length and the definition which of the character types ( lower, upper, digit, special

characters ) that have to be part of the password.

Example:

CREATE USER my_user IDENTIFIED BY Aa123456;

Page 68: hana sql

SAP In-Memory Database SQL Reference Manual

64

CREATE VIEW

SQL Syntax:

CREATE VIEW view_name [ ( column_name, ... ) ] AS <subquery>

Description: The CREATE VIEW statement effectively creates virtual table based on the results of an SQL

statement. It is not a table in a real sense as it does not contain data in itself. When a column name is specified along with the view name, a query result is displayed with that column name. If a column name is omitted, a query result gives an appropriate name to the column automatically. The number of column names has to be the same as the number of columns returned

from select_statement. In the HDB a view cannot be updated.

Example:

CREATE VIEW v_name AS SELECT * FROM a;

Page 69: hana sql

SAP In-Memory Database SQL Reference Manual

65

DELETE SQL Syntax: DELETE FROM table_name [ WHERE <predicate> ]

Description:

The DELETE statement deletes records from a table where the predicates are met. If the WHERE

clause is omitted, then it removes all records from a table.

Example:

DELETE FROM table_a WHERE a = 1;

Page 70: hana sql

SAP In-Memory Database SQL Reference Manual

66

DROP CALCULATION SCENARIO SQL Syntax: DROP CALCULATION SCENARIO name [ <drop_option> ]

Parameters:

drop_option ::= CASCADE

Default = CASCADE Cascaded drop drops the calculation scenario and dependent column views of type calculation.

Non-cascaded drop behavior prevents dropping the scenario if there are any column views of type

calculation referencing the scenario. Description: The DROP CALCULATION SCENARIO statement deletes a calculation scenario.

Example: DROP CALCULATION SCENARIO SYSTEM.DEMO_PROJECTION_OP CASCADE;

Page 71: hana sql

SAP In-Memory Database SQL Reference Manual

67

DROP INDEX

SQL Syntax:

DROP INDEX index_name

Description: The DROP INDEX statement removes an index.

Example:

DROP INDEX idx ;

Page 72: hana sql

SAP In-Memory Database SQL Reference Manual

68

DROP ROLE SQL Syntax: DROP ROLE role_name

Description:

Users with system privilege ROLE ADMIN can DROP roles. If a role was granted to a user, it is revoked when the role is dropped. Revoking a role may lead to making some views inaccessible. This will occur if a view, or procedures using those views, depends on any privilege that the role has.

Example: DROP ROLE my_role;

Page 73: hana sql

SAP In-Memory Database SQL Reference Manual

69

DROP SCHEMA SQL Syntax: DROP SCHEMA schema_name [ <drop_option> ]

Parameters:

drop_option ::= CASCADE | RESTRICT

Default = RESTRICT

Restrict drop behavior will drop the object when there is no dependent object. If there is a dependent

object, an error will be thrown. Cascaded drop drops the object and dependent objects. Non-Cascaded drop option is not supported for dropping SCHEMA.

Description: The DROP SCHEMA statement removes a schema.

Example:

DROP SCHEMA my_schema;

Page 74: hana sql

SAP In-Memory Database SQL Reference Manual

70

DROP SEQUENCE SQL Syntax: DROP SEQUENCE sequence_name [ <drop_option > ]

Parameters:

drop_option ::= CASCADE | RESTRICT

Default = RESTRICT Cascaded drop drops the object and dependent objects. When CASCADE option is not specified, non-

cascaded drop behavior drops the object and does not drop the dependent objects, but invalidates the dependent objects (VIEW, PROCEDURE).

The invalidated object can be revalidated when an object that has same schema and object name is created. Object ID, schema name, and object name pair is reserved for revalidating dependent objects.

Restrict drop behavior will drop the object when there is no dependent object. If there is a dependent object, an error will be thrown. Description: The DROP SEQUENCE statement removes a sequence.

Example: DROP SEQUENCE s;

Page 75: hana sql

SAP In-Memory Database SQL Reference Manual

71

DROP SYNONYM SQL Syntax: DROP SYNONYM synonym_name [ <drop_option> ]

Parameters:

drop_option ::= CASCADE | RESTRICT

Default = RESTRICT

Cascaded drop drops the object and dependent objects. When CASCADE option is not specified, non-

cascaded drop behavior drops the object and does not drop the dependent objects, but invalidates the dependent objects (VIEW, PROCEDURE).

The invalidated object can be revalidated when an object that has same schema and object name is created. Object ID, schema name, and object name pair will be reserved for revalidating dependent objects.

Restrict drop behavior will drop the object when there is no dependent object. If there is a dependent object, an error will be thrown. Description: The DROP SYNONYM statement removes a synonym.

Example: DROP SYNONYM a_synonym;

Page 76: hana sql

SAP In-Memory Database SQL Reference Manual

72

DROP TABLE

SQL Syntax:

DROP TABLE table_name [ <drop_option> ]

Parameters: drop_option ::= CASCADE | RESTRICT

Default = RESTRICT Cascaded drop drops the object and dependent objects. When CASCADE option is not specified, non-cascaded drop behavior drops the object and does not drop the dependent objects, but invalidates the dependent objects (VIEW, PROCEDURE).

The invalidated object can be revalidated when an object that has the same schema and object name is created. The object ID, schema name, and object name pair will be reserved for revalidating dependent objects. Restrict drop behavior drops the object when there is no dependent object. If there is a dependent object, an error is thrown.

Description: The DROP TABLE statement deletes a table.

Example:

DROP TABLE A;

Page 77: hana sql

SAP In-Memory Database SQL Reference Manual

73

DROP TYPE SQL Syntax: DROP TYPE type_name [ <drop_option> ]

Parameters: drop_option ::= CASCADE | RESTRICT

Default = RESTRICT

Cascaded drop drops the object and dependent objects. When CASCADE option is not specified, non-cascaded drop behavior drops the object and does not drop the dependent objects, but invalidates the

dependent objects (VIEW, PROCEDURE).

When a table type is dropped with non-cascaded drop option, the dependent SQLScript procedure will be invalidated but will not be dropped. When the underlying object of SQLScript procedure is recreated, the validity of the procedure is checked again and revalidated.

Restrict drop behavior will drop the object when there is no dependent object. If there is a dependent object, an error will be thrown.

Description: The DROP TYPE statement removes a user-defined table type.

Example: DROP TYPE my_type;

Page 78: hana sql

SAP In-Memory Database SQL Reference Manual

74

DROP TABLE

SQL Syntax:

DROP TABLE table_name [ <drop_option> ]

Parameters: drop_option ::= CASCADE | RESTRICT

Default = RESTRICT Cascaded drop drops the object and dependent objects. When CASCADE option is not specified, non-cascaded drop behavior drops the object and does not drop the dependent objects, but invalidates the dependent objects (VIEW, PROCEDURE).

The invalidated object can be revalidated when an object that has the same schema and object name is created. The object ID, schema name, and object name pair will be reserved for revalidating dependent objects. Restrict drop behavior drops the object when there is no dependent object. If there is a dependent object, an error is thrown.

Description: The DROP TABLE statement deletes a table.

Example:

DROP TABLE A;

Page 79: hana sql

SAP In-Memory Database SQL Reference Manual

75

DROP USER SQL Syntax:

DROP USER user_name [ <drop_option> ]

Parameters: drop_option ::= CASCADE | RESTRICT

Default = RESTRICT If CASCADE is specified (or used as the default), all schemas, synonyms and tables of the user are

dropped, including indexes, privileges, view tables and everything based on these objects, is also deleted along with the user.

If RESTRICT is specified, and the user to be dropped is the owner of synonyms or tables, then the DROP USER statement will fail.

Description: The DROP USER statement deletes a database user. The schema with the user's name and the

schemas belonging to the user, together with all objects in them (even if they are created by different users), are deleted. Objects owned by the user, even if they are part of another schema, are deleted.

Objects that are dependent on deleted objects are deleted. Privileges on these deleted objects are also deleted. It is possible to delete a user even if a there is a current user session existing.

Example: DROP USER my_user;

Page 80: hana sql

SAP In-Memory Database SQL Reference Manual

76

DROP VIEW

SQL Syntax:

DROP VIEW view_name [ <drop_option> ]

Parameter: drop_option ::= CASCADE | RESTRICT

Default = RESTRICT Cascaded drop drops the object and dependent objects. When CASCADE option is not specified, non-cascaded drop behavior drops the object and does not drop the dependent objects, but invalidates the dependent objects (VIEW, PROCEDURE).

The invalidated object can be revalidated when an object that has same schema and object name is created. Object ID, schema name, and object name pair will be reserved for revalidating dependent objects. Restrict drop behavior will drop the object when there is no dependent object. If there is a dependent object, an error will be thrown.

Description: The DROP VIEW statement removes a view.

Example:

DROP VIEW v_name;

Page 81: hana sql

SAP In-Memory Database SQL Reference Manual

77

RENAME INDEX

SQL Syntax:

RENAME INDEX old_index_name TO new_index_name

Description: The RENAME INDEX statement changes the name of an index.

Example:

RENAME INDEX idx TO new_idx;

Page 82: hana sql

SAP In-Memory Database SQL Reference Manual

78

GRANT SQL Syntax: GRANT <system_privilege>,... TO <grantee> [WITH ADMIN OPTION] | GRANT <schema_privilege>,... ON SCHEMA schema_name TO <grantee> [WITH GRANT OPTION]

| GRANT <object_privilege>,... ON object_name TO <grantee> [WITH GRANT OPTION] | GRANT role_name,... TO <grantee> [WITH ADMIN OPTION] | GRANT STRUCTURED PRIVILEGE privilege_name TO <grantee>

Parameters:

system_privilege ::=

AUDIT ADMIN | BACKUP ADMIN | CATALOG READ | CHECKPOINT ADMIN | CHECKPOINT EXEC |

CREATE SCENARIO | CREATE SCHEMA | CREATE STRUCTURED PRIVILEGE | DATA ADMIN | EXPORT |

IMPORT | INIFILE ADMIN | LOGFLUSH ADMIN | MONITOR ADMIN | OPTIMIZER ADMIN | RESOURCE ADMIN | ROLE ADMIN | SCENARIO ADMIN | SERVICE ADMIN | SESSION ADMIN | TENANT ADMIN | TRACE ADMIN | USER ADMIN | VERSION ADMIN schema_privilege ::= CREATE ANY | DELETE | DROP | EXECUTE | INDEX | INSERT | SELECT | UPDATE

object_privilege ::= ALL PRIVILEGES | ALTER | DELETE | DROP | EXECUTE | INDEX | INSERT | SELECT

|UPDATE grantee :: = user_name | role_name

Description:

GRANT is used to grant privileges to users and roles. GRANT is also used to grant roles to users. A number of privileges are available to control the authorization of SQL commands in the HDB. Best practice dictates that database authorizations should follow the least-privileged principle i.e. users should be given only the smallest set of privileges that they require for their work. This document gives a complete overview of the privileges supported at the SQL level so that they can

be assigned appropriately to database users during application development. The SQL privileges can be divided into system and object privileges:

System privileges: These are system-wide privileges and control some general system activities such as creating schemas, creating or changing users and roles.

Object privileges: These privileges are bound to an object and control activities which are possible on this particular object, such as select/update/delete on database tables.

The following information describes all supported privileges in the two groups, together with the list of the SQL commands they authorize. System Privileges

User and Roles USER ADMIN: This privilege authorizes the creation/changing of users via the SQL commands

CREATE USER, ALTER USER, and DROP USER. ROLE ADMIN: This privilege authorizes the creation and deletion of roles via the SQL

commands CREATE ROLE and DROP ROLE. Catalog/Schema Management

CREATE SCHEMA: This privilege authorizes the creation of database schemas via the SQL

command CREATE SCHEMA.

Page 83: hana sql

SAP In-Memory Database SQL Reference Manual

79

DATA ADMIN: This is a very powerful privilege as it authorizes users a) to perform SELECT on all catalog tables and views (in the SYS schema) and b) to execute ALL DDLs (and only DDLs) commands in the HDB, in particular:

o For schemas: CREATE SCHEMA, DROP SCHEMA,

o For tables: CREATE (COLUMN) TABLE, DROP TABLE, ALTER TABLE, o For views: CREATE (COLUMN) VIEW, DROP VIEW, ALTER VIEW, o For indexes: CREATE INDEX, ALTER INDEX, DROP INDEX, o For sequences: CREATE SEQUENCE, DROP SEQUENCE, o For synonyms: CREATE SYNONYM, DROP SYNONYM, o For table types: CREATE TABLE TYPE, DROP TABLE TYPE, o For functions: CREATE FUNCTION, DROP FUNCTION,

o For procedures: CREATE PROCEDURE, DROP PROCEDURE.

CATALOG READ: This privilege authorizes users to perform SELECT on all catalog tables and views (in the SYS schema)

Analytics

CREATE SCENARIO: This privilege controls the creation of calculation scenarios and cubes (CalcEngine) via the following SQL commands:

o ADD SCENARIO, o CREATE CALCULATION SCENARIO.

SCENARIO ADMIN: This privilege authorizes all calculation scenario-related activities (including creation), which can be performed using the following SQL commands:

o ADD SCENARIO, FLATTEN SCENARIO o CREATE CALCULATION SCENARIO, DROP CALCULATION SCENARIO

CREATE STRUCTURED PRIVILEGE: This privilege authorizes the creation of structured

privileges (analytical privileges) via the SQL command ADD STRUCTURED PRIVILEGE. Note

that currently, only the owner of an analytical privilege can drop it. Therefore, there is no additional privilege for dropping structured privileges.

Auditing

AUDIT ADMIN: This privilege controls the execution of auditing-related SQL commands: o CREATE AUDIT POLICY o DROP AUDIT POLICY o ALTER AUDIT POLICY

System Management These privileges authorize the various system activities. Due to the potentially high level of impact on the system, these privileges are not relevant to a normal database user and should only be granted with care (for example, only to a support user/role.)

Data Import and Export Two system privileges are available for authorization of the data import/export in the database:

IMPORT: This privilege authorizes the import activity in the database via the commands IMPORT or LOAD TABLE. Note that beside this privilege, the user still needs the INSERT privilege on the target tables to be imported.

EXPORT: This privilege authorizes the export activity in the database via the commands

EXPORT or LOAD TABLE. Note that beside this privilege, the user still needs the INSERT privilege on the source tables to be exported

Object Privileges Object privileges are bound to objects they provide authorization for. The following table lists the

different object privileges supported by SAP HANA Database and the object types for which the

privileges can be employed (OK: applicable, -: not applicable, ?: dynamically evaluated - see Notes):

Page 84: hana sql

SAP In-Memory Database SQL Reference Manual

80

Table 18: Object privileges supported by SAP HANA Database Privilege Sche

ma Table View Table Type Sequence Synonym Function/Procedure

CREATE ANY OK - - - - - -

ALL PRIVILEGES - OK OK OK - ? -

DROP OK OK OK OK OK ? OK

ALTER OK OK OK OK - ? OK

SELECT OK OK OK OK OK ? -

INSERT OK OK OK OK - ? -

UPDATE OK OK OK OK - ? -

DELETE OK OK OK OK - ? -

INDEX OK OK - OK - ? -

EXECUTE OK - - - - ? OK

CREATE ANY: This privilege allows the creation of all kinds of objects, in particular tables,

views, sequences, synonyms, SQL Script functions, or DB procedures in a schema. Obviously,

this privilege can only be granted on a schema. ALL PRIVILEGES: This is actually a collection of all privileges, which a) the grantor currently

has and is allowed to grant further, and b) can be granted on this particular object. This collection is dynamically evaluated for the given grantor and object. ALL PRIVILEGES is not applicable to a schema, but only a table, view, or table type.

DROP and ALTER are DDL privileges and authorize the DROP and ALTER SQL commands.

While the DROP privilege is valid for all kinds of objects, the ALTER privilege is not valid for

sequences and synonyms as their definitions cannot be changed after creation. INDEX is a special DDL privilege and authorizes the creation/changing/dropping of indexes for

an object via the commands CREATE INDEX, DROP INDEX, and ALTER INDEX. This privilege can only be applied to schema, table, and table type.

SELECT, INSERT, UPDATE and DELETE are DML privileges and authorize respective SQL commands. While SELECT is valid for all kinds of objects, except for functions/procedures, INSERT, UPDATE, and DELETE are valid for schemas, tables, and table types only.

EXECUTE is a special DML privilege and authorizes the execution of a SQL Script function or a DB procedure via the commands CALL.

Notes: All privileges are valid for schemas in the sense that they authorize applicable activities on the

objects created in this schema. Synonyms can be created for tables, views, sequences, and database procedures, but not for schemas

and SQL Script functions. The privileges which can be granted and revoked on a synonym will be

determined by the actual object the synonym stands for.

Page 85: hana sql

SAP In-Memory Database SQL Reference Manual

81

INSERT SQL Syntax: INSERT INTO table_name [ ( column_name, ... ) ] { VALUES (expr, ... ) | <subquery> } [WITH PARAMETERS ( <parameter_key_value>, ... ) ]

Parameters: parameter_key_value::=

<string_literal> = <string_literal> | <identifier> = <string_literal> |

<string_literal> = (<string_literal>, ... ) Description:

The INSERT statement adds records to a table.

A subquery that returns records can be used to insert records into the table. If the subquery does not return any records, then the database will not insert any records into the table.

The column list can be specified with the INSERT statement. If the column list is omitted, the database

inserts all columns in the table. Example: CREATE TABLE table_a (A INT);

INSERT INTO table_a VALUES (1);

Page 86: hana sql

SAP In-Memory Database SQL Reference Manual

82

LOAD SQL Syntax: LOAD table_name { DELTA | ALL | column_name, …}

Description:

The LOAD statement loads the column store table data to memory.

DELTA - DELTA part of the column store table is loaded into memory. Since the column store is read optimized and compressed, deltas are introduced to optimize insert or updates. All insertions are passed to a delta.

ALL – ALL data of the column store table in main and delta is loaded into memory.

column_name, … – Columns specified in the column list are loaded into memory. Example:

LOAD a_table all;

Page 87: hana sql

SAP In-Memory Database SQL Reference Manual

83

MERGE DELTA SQL Syntax:

MERGE [HISTORY] DELTA OF table_name [PART int_const] [WITH PARAMETERS ( <parameter_key_value>,… ) ]

WITH PARAMETERS (parameter_key_value):

Column store-specific options can be passed in using the "WITH PARAMETERS" clause. • Keys and single values can be any string constant • Duplicate keys are allowed • Keys are automatically mapped into their uppercase representation

parameter_key_value ::=

<string_literal> = <string_literal> | <identifier> = <string_literal> | <string_literal> = (<string_literal>, ... ) Current parameters

'SMART_MERGE' = 'ON' | 'OFF' When SMART_MERGE is ON, the database does a smart merge, this means database decides whether to merge or not based on merge criteria specified in automerge section of indexserver configuration

„PASSPORT‟=‟<string>‟

Merge request call tag to identify the request in related traces „MEMORY_MERGE‟=‟ON‟|‟OFF‟ Database merges delta index in memory only, it will not be persisted.

Description The MERGE DELTA statement merges deltas to a main column store table. Since column stores are

read optimized and compressed, deltas are introduced to optimize insert or updates. For this to function, insertions are passed stored in a delta to the original table data. The MERGE DELTA command

can then be used to merge the delta changes back into the main table store.

HISTORY – Can be specified to merge history deltas into the history main on column store history

tables. PART – Can be specified to merge a delta of a partition to main column table.

Example: MERGE DELTA OF A;

MERGE DELTA OF A PART 1;

MERGE HISTORY DELTA OF A;

MERGE HISTORY DELTA OF A PART 1;

Page 88: hana sql

SAP In-Memory Database SQL Reference Manual

84

RENAME COLUMN

SQL Syntax:

RENAME COLUMN table_name.old_column_name TO new_column_name

Description: The RENAME COLUMN statement changes the name of a column.

Example: CREATE TABLE B (A INT PRIMARY KEY, B INT);

RENAME COLUMN B.A TO C;

Page 89: hana sql

SAP In-Memory Database SQL Reference Manual

85

RENAME INDEX

SQL Syntax:

RENAME INDEX old_index_name TO new_index_name

Description: The RENAME INDEX statement changes the name of an index.

Example:

RENAME INDEX idx TO new_idx;

Page 90: hana sql

SAP In-Memory Database SQL Reference Manual

86

RENAME TABLE

SQL Syntax:

RENAME TABLE old_table_name TO new_table_name

Description: The RENAME TABLE statement changes the name of a table to new_table_name in the same schema.

Example: RENAME TABLE A TO B;

RENAME TABLE mySchema.A TO B;

Page 91: hana sql

SAP In-Memory Database SQL Reference Manual

87

REVOKE SQL Syntax: REVOKE <system_privilege>,... FROM <grantee> | REVOKE <schema_privilege>,... ON SCHEMA schema_name FROM <grantee>

| REVOKE <object_privilege>,... ON object_name FROM <grantee>

| REVOKE <column_privilege>,... ( column_name,... ) ON object_name FROM <grantee> | REVOKE role_name,... FROM <grantee>

| REVOKE STRUCTURED PRIVILEGE structured_privilege_name FROM <grantee>

system_privilege ::= CREATE SCHEMA | DATA ADMIN | ROLE ADMIN | USER ADMIN |

BACKUP ADMIN | CHECKPOINT ADMIN | CHECKPOINT EXEC | CREATE SCENARIO | CREATE

STRUCTURED PRIVILEGE | INIFILE ADMIN | LOGFLUSH ADMIN | MONITOR ADMIN | OPTIMIZER

ADMIN | RESOURCE ADMIN | SESSION ADMIN |SERVICE ADMIN | TENANT ADMIN | TRACE ADMIN | VERSION ADMIN | INDEX | ALTER schema_privilege ::= CREATE ANY | DELETE | DROP | EXECUTE | INSERT | SELECT | UPDATE

object_privilege ::= ALL PRIVILEGES | ALTER | DELETE | DROP | EXECUTE | INDEX | INSERT | SELECT

| UPDATE column_privilege ::= INSERT | SELECT | UPDATE

grantee :: = user_name | role_name

Description:

The REVOKE statement revokes the specified privileges or roles for the specified objects from the

specified users or roles. Revoking may cause views, procedures to become inaccessible.

Page 92: hana sql

SAP In-Memory Database SQL Reference Manual

88

SELECT SQL Syntax:

<subquery> [ <order_by_clause>] [ <limit_clause> ] [ <for_update_clause> ]

subquery ::= <select_clause> <from_clause > [<where_clause> ] [<group_by_clause> ] [<having_clause> ] { <set_operator subquery>,… }

select_clause ::=

SELECT [ TOP expr ] [ ALL | DISTINCT ] < select_columns >

select_columns::= {<select_item>, …}

select_item ::=

[ [schema_name.] table_name.]*

| expr [ AS ] column_alias from_clause ::= FROM <table>, …

table::=

table_name [ [AS] table_alias ] | <subquery> [ [AS] table_alias ]

| <joined_table>

joined_table ::= <table> [ <join_type> ] JOIN <table>ON <predicate> | <table> CROSS JOIN <table>

| <joined_table>

join_type ::=INNER | {LEFT | RIGHT | FULL OUTER}

where_clause ::=WHERE <predicate>

group_by_clause ::=GROUP BY <group_by_item_list>

group_by_item_list ::=

GROUPING SETS [BEST n] [LIMIT n][OFFSET n]

[WITH SUBTOTAL] [WITH BALANCE] [WITH TOTAL] [TEXT_FILTER <filterspec> [FILL UP [SORT MATCHES TO TOP]]] [STRUCTURED RESULT [WITH OVERVIEW] [PREFIX value] | MULTIPLE RESULTSET] ( <group_by_expression_list> )

having_clause ::=HAVING <predicate>

set_operator ::= UNION [ALL] | INTERSECT | EXCEPT

order_by_clause ::=ORDER BY {{ expr | position } [ASC | DESC] }, ...

limit_clause ::=LIMIT expr [OFFSET expr]

for_update_clause ::= FOR UPDATE [OF column_name, … ]

Page 93: hana sql

SAP In-Memory Database SQL Reference Manual

89

Description: select_clause ::= SELECT [ TOP expr ] [ ALL | DISTINCT ] < select_columns >

select_columns::= { <select_item> , …}

select_item ::=

[ [schema_name.] table_name.]* | expr [ AS ] column_alias

The SELECT statement retrieves data from one or more tables in the database.

TOP Returns the fist expr records from the SQL statement.

DISTINCT, ALL

DISTINCT returns only one instance per duplicated row in the selected rows. ALL (the default) will return all rows selected including duplicates.

select_columns

With select columns you can specify exactly which columns you wish to return * [asterisk] selects all columns the from all tables or views listed in the FROM clause

column_alias, table_alias Using an alias you can rename an existing column or table name.

from_clause ::= FROM <table>, …

table ::=

table_name [ [AS] table_alias ] | <subquery> [ [AS] table_alias ] | <joined_table>

joined_table ::= <table> [ <join_type> ] JOIN <table> ON <predicate> | <table> CROSS JOIN <table> | <joined_table>

join_type::=INNER | {LEFT | RIGHT | FULL} OUTER

The join_type specifies the type of join to be created. RIGHT indicates a right outer

join, LEFT indicates a left outer join, and FULL indicates a full outer join. The OUTER

keyword may or may not be used when an outer join is being performed.

ON predicate The ON clause specifies a join predicate.

CROSS JOIN You can use a CROSS JOIN to combine rows from each of the tables in the join as a

Cartesian product. where_clause ::=WHERE <predicate>

The WHERE predicate is used to specify a predicate on the records to be selected. By using WHERE you can filter the results set and only retrieve required rows.

Page 94: hana sql

SAP In-Memory Database SQL Reference Manual

90

having_clause::=HAVING <predicate>

You can use the HAVING keyword to select specified groups that satisfy the given predicates.

If this keyword is omitted, all groups are selected. order_by_clause ::=ORDER BY {{ expr | position } [ASC | DESC] }, ...

The ORDER BY keyword sorts the results of a query. The ORDER BY clause can only sort the records by the field specified in SELECT statement. The

ASC keyword sorts the result in ascending order and the DESC keyword sorts the result in descending order. The default value is ASC.

set_operator::= UNION [ALL] | INTERSECT | EXCEPT

Set operators enable more than one select statement to be combined, but only one result set

is returned. UNION ALL – Selects all rows from all select statements.

UNION – Selects all unique rows from all select statements by removing duplicate rows found from different select statements.

INTERSECT – Returns the rows that exist in all select statements in common.

EXCEPT – Returns the rows from the first select statements after removing the duplicates in the following select statements.

for_update_clause::= FOR UPDATE [OF column_name, …]

The FOR UPDATE keyword locks the selected rows so that other users cannot lock or update the rows until end of the current transaction.

limit_clause::=LIMIT n1 [OFFSET n2]

LIMIT - Returns the first n1 records from the SQL statement. When OFFSET n2 is specified, the database skips that n2 rows before returning the results set.

group_by_clause::=GROUP BY <group_by_item_list >

group_by_item_list::= GROUPING SETS [BEST n] [<grouping_limit_clause>]

[WITH SUBTOTAL] [WITH BALANCE] [WITH TOTAL] [TEXT_FILTER filterspec [FILL UP [SORT MATCHES TO TOP]]]

[[STRUCTURED RESULT [WITH OVERVIEW] [PREFIX value]] | MULTIPLE RESULTSETS] ( <group_by_expression_list> )

grouping_limit_clause::= LIMIT expr [OFFSET expr]

group_by_expression_list::= { group_by_expression,…}

The GROUP BY keyword groups the selected rows based on the special value of column.

GROUPING SETS - Generates rows with specified multiple groupings of data in one query. The

result is the same as UNION ALL of the aggregation of each specified group if grouping_set_structured_option is not set. group_by_expression can contain ORDER BY only when the group_by_expression comes with GROUPING SETS option. BEST n – Returns only the top n facets ordered by inverse navigability.

Page 95: hana sql

SAP In-Memory Database SQL Reference Manual

91

LIMIT n1 [OFFSET n2] – LIMIT in grouping_limit_clause returns the first grouped records from each grouping set. When OFFSET n1 is specified, the database skips n2 rows of grouped records before returning the result sets.

STRUCTURED RESULT – When this option is set, the aggregation of each specified group is returned as a temporary table. MULTIPLE RESULTSETS – The aggregation of each specified group is returned in multiple result sets. ( temporary tables ) WITH SUBTOTAL – For each GROUPING SET add a row with the subtotal of the returned

results as controlled by OFFSET or LIMIT. WITH BALANCE – For each GROUPING SET, add a row with the aggregated value of the remaining values not returned as controlled by OFFSET or LIMIT.

WITH TOTAL – For each GROUPING SET, add a row with the aggregated total value.

TEXT FILTER <filterspec> - Peform text filtering or hightlighting on the dimensional values, filterspec is a string in Lucene syntax. Only matching values will be returned. If BEST is specified, the result tables are sorted by number of matches, then navigability. For each filtered attribute, a text_filter ( dimensional_attribute ) clause must be added to the projection. The filter can only be applied to a dimensional value, which is assumed to be the first field in the grouping set.

FILL UP – Fill up the matching values from FILTER with non-matching values, up to LIMIT SORT MATCHES TO TOP – Sort matching values to top, otherwise retain the normal sorting order. This option cannot be used with SUBTOTAL, BALANCE and TOTAL.

WITH OVERVIEW – additionally return the overview in a separate table.

PREFIX value – Specify prefix for the temporary tables, must start with “#”. Default value is “#GN”. The projection clause must include all key figures and facets or view attributes used in the GROUPING SETS specification including text_filter attribute fields.

GROUPING_ID returns a separate column which allows to identify which grouping set each row belongs to. Return Format

If no optional parameters are specified the unioned result of all grouping sets is returned, with NULL values filling up attributes which are not included in a specific

grouping set (see Example below). With the keyword STRUCTURED RESULT, temporary tables are created that can be

queried using “SELECT * FROM <tablename>” in the same session. The name of the tables follows the form :-

o <PREFIX>0 (this table will contain the overview if WITH OVERVIEW is specified) o <PREFIX>1..n n-th grouping set (subject to re-ordering by the BEST

parameter)

In addition to the columns for facets and keyfigures an additional column is returned when text_filter is specified. This column contains the value of the column when the column matches the filter criteria, NULL otherwise.

Example:

SELECT column_name FROM table_name;

Page 96: hana sql

SAP In-Memory Database SQL Reference Manual

92

SELECT brand_name, store_name, promotion_name, sum(unit_sales),

grouping_id(brand_name, store_name, promotion_name) as gid

FROM foodmart

GROUP BY GROUPING SETS LIMIT 5

(brand_name, store_name, promotion_name);

Page 97: hana sql

SAP In-Memory Database SQL Reference Manual

93

SET TRANSACTION SQL Syntax: SET TRANSACTION ISOLATION LEVEL <isolation_level>

Parameters:

isolation_level ::=READ COMMITTED| REPEATABLE READ| SERIALIZABLE

READ COMMITTED

Default.

This isolation level corresponds to the statement level read consistency. With statement level snapshot isolation, multiple statements in a transaction may see different

snapshots of the system. The statement in a transaction sees a consistent snapshot of the system. Each statement sees the changes that were committed when the execution of the statement started. Reading a row does not set any locks. When rows are inserted, updated or deleted, the

system sets exclusive locks on the affected rows for the duration of the transaction. The system releases these locks at the end of the transaction. When rows are inserted, updated or deleted, the system also sets shared locks on the affected tables for the duration of the transaction. This guarantees that the table is not dropped or altered while some rows of the table are being updated.

REPEATABLE READ/ SERIALIZABLE

This isolation level corresponds to transaction level snapshot isolation.

All statements of a transaction see the same snapshot of the database. This snapshot contains all changes that were committed at the time the transaction started with the changes made by the transaction itself.

Reading a row does not set any locks. When rows are inserted, updated or deleted, the system sets exclusive locks on the affected rows for the duration of the transaction. The system releases these locks at the end of the transaction. When rows are inserted, updated or deleted, the system also sets shared locks on the affected tables for the duration of the transaction. This guarantees that the table is not dropped or altered while some rows of the table are being updated.

Description: The system uses multi-version concurrency control (MVCC) to ensure consistent read operations. Concurrent read operations see a consistent view of the system without blocking concurrent write

operations. Updates are implemented not by overwriting existing records, but by inserting new versions.

The isolation level specification determines the lock operation type. The system supports both statement level snapshot isolation and transaction level snapshot isolation. For statement snapshot isolation use level READ COMMITTED. For transaction snapshot isolation use REPEATABLE READ or SERIALIZABLE.

DDL statements always run in READ COMMITTED isolation level.

Page 98: hana sql

SAP In-Memory Database SQL Reference Manual

94

UNLOAD SQL Syntax: UNLOAD table_name

Description The UNLOAD statement unloads the column store table data from memory to disk.

Example:

UNLOAD a_table;

Page 99: hana sql

SAP In-Memory Database SQL Reference Manual

95

UPDATE SQL Syntax:

UPDATE table_name [ [ AS ] name ] <set_clause> [WHERE <predicate>] [ WITH PARAMETERS ( <parameter_key_value>,… ) ]

Parameters:

set_clause::= SET { column_name = expr} , …

parameter_key_value::=

<string_literal> = <string_literal> |

<identifier> = <string_literal> | <string_literal> = (<string_literal>, ... ) Description:

The UPDATE statement changes the values of the records of a table where the predicate is met.

If the WHERE clause predicate is true, the result of expr is assigned to that column.

If the WHERE clause is omitted, then it updates all records of a table. Example:

UPDATE table_a SET a = 2 WHERE a = 1;

Page 100: hana sql

SAP In-Memory Database SQL Reference Manual

96

UPSERT / REPLACE SQL Syntax: UPSERT table_name [ ( column_name, ... ) ] { <values_list_clause> | <subquery> }

REPLACE table_name [ ( column_name, ... ) ] { <values_list_clause> | <subquery> }

values_list_clause ::=

VALUES ( expr, ... ) [ WHERE <predicate> | WITH PRIMARY KEY ]

Description: The UPSERT/REPLACE statement without a subquery is similar to the UPDATE statement. The

difference between UPSERT/REPLACE and UPDATE is when the WHERE clause predicate is false. In this case a new record is addedto the table like the INSERT statement.

In case of a table which has a PRIMARY KEY, the PRIMARY KEY column must be included in the column list. Columns defined with NOT NULL without default specification have to be included in the column list as well. Other columns are filled with default value or NULL if not specified. The UPSERT/REPLACE statement with a subquery works like the INSERT statement, except that if an

old row in the table has the same value as a new row for a PRIMARY KEY, then the old row is changed by values of the returned record from a subquery. If the table does not have a PRIMARY KEY, the UPSERT/REPLACE statement becomes equivalent to INSERT because an index is not available to determine if a new row duplicates another. The UPSERT/REPLACE statement used with the 'WITH PRIMARY KEY' parameter has the same effect

as an UPSERT/REPLACE statement used with a subquery.

Example: CREATE TABLE A (A INT PRIMARY KEY, B INT);

UPSERT A VALUES (1, 1);

UPSERT A SELECT A + 1, B FROM A;