SAP HANA Database - SQL Reference Manual
SAP HANA Database - SQL Reference Manual
Consultants
Administrators
SAP Hardware Partner
Others
1 2012-05-09
Copyright Copyright 2012 SAP AG. All rights reserved
IBM, DB2, DB2 Universal Database, System i, System i5, System p, System
p5, System x, System z, System z10, z10, z/VM, z/OS, OS/390, zEnterprise,
PowerVM, Power Architecture, Power Systems, POWER7, POWER6+,
POWER6, POWER, PowerHA, pureScale, PowerPC, BladeCenter, System
Storage, Storwize, XIV, GPFS, HACMP, RETAIN, DB2 Connect, RACF,
Redbooks, OS/2, AIX, Intelligent Miner, WebSphere, Tivoli, Informix, and Smarter
Planet are trademarks or registered trademarks of IBM Corporation.
Linux is the registered trademark of Linus Torvalds in the United States and other
countries.
Adobe, the Adobe logo, Acrobat, PostScript, and Reader are trademarks or
registered trademarks of Adobe Systems Incorporated in the United States and
other countries.
Oracle and Java are registered trademarks of Oracle and its affiliates.
UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group.
Apple, App Store, iBooks, iPad, iPhone, iPhoto, iPod, iTunes, Multi-Touch,
Objective-C, Retina, Safari, Siri, and Xcode are trademarks or registered
trademarks of Apple Inc.
2 2012-05-09
in Motion Limited.
Google App Engine, Google Apps, Google Checkout, Google Data API, Google
Maps, Google Mobile Ads, Google Mobile Updater, Google Mobile, Google Store,
Google Sync, Google Updater, Google Voice, Google Mail, Gmail, YouTube,
Dalvik and Android are trademarks or registered trademarks of Google Inc.
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.
Crossgate, m@gic EDDY, B2B 360, and B2B 360 Services are registered
trademarks of Crossgate AG in Germany and other countries. Crossgate 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 warranty statements accompanying such products and services, if
any. Nothing herein should be construed as constituting an additional warranty.
3 2012-05-09
Table of Content
Table of Content
Table of Content 4
SAP HANA Database - SQL Reference Manual 8
SQL Reference Ma nua l 9
Nota ti on 10
Introducti on 11
SQL 11
Supported Languages and Code Pages 11
Comment 11
Identifiers 11
Single Quotation Mark 11
Double Quotation Mark 11
SQL Reserved Words 12
Da ta Types 13
Classification of Data Types 13
Datetime Types 13
Date Formats 13
Time Formats 14
Timestamp Formats 14
Additional Formats 14
Supported Functions for Date/Time types 15
Numeric Types 15
Character String Types 16
Binary Types 17
Large Object (LOB) Types 17
Mapping between SQL Data Type and Column Store Data Type 18
Data Type Conversion 18
Typed Constant 20
Predi ca tes 22
Comparison Predicates 22
Range Predicate 22
In Predicate 22
Exists Predicate 22
LIKE Predicate 22
NULL Predicate 22
CONTAINS Predicate 23
Opera tors 25
Unary and Binary Operators 25
Operator Precedence 25
Arithmetic Operators 25
String Operators 26
Comparsion Operators 26
Logical Operators 26
Set Operators 26
Expres s i ons 28
Case Expressions 28
Function Expressions 28
Aggregate Expressions 28
Subqueries in Expressions 28
SQL Functi ons 30
Introduction 30
Data Type Conversion Functions 30
CAST 30
TO_ALPHANUM 30
TO_BIGINT 30
TO_BINARY 31
TO_BLOB 31
TO_CHAR 31
TO_CLOB 31
TO_DATE 32
TO_DATS 32
4 2012-05-09
Table of Content
TO_DECIMAL 32
TO_DOUBLE 33
TO_INT 33
TO_INTEGER 33
TO_NCHAR 33
TO_NCLOB 34
TO_NVARCHAR 34
TO_REAL 34
TO_SECONDDATE 34
TO_SMALLDECIMAL 35
TO_SMALLINT 35
TO_TIME 35
TO_TIMESTAMP 35
TO_TINYINT 36
TO_VARCHAR 36
DateTime Functions 36
ADD_DAYS 36
ADD_MONTHS 37
ADD_SECONDS 37
ADD_YEARS 37
CURRENT_DATE 37
CURRENT_TIME 38
CURRENT_TIMESTAMP 38
CURRENT_UTCDATE 38
CURRENT_UTCTIME 38
CURRENT_UTCTIMESTAMP 39
DAYNAME 39
DAYOFMONTH 39
DAYOFYEAR 39
DAYS_BETWEEN 40
EXTRACT 40
HOUR 40
ISOWEEK 40
LAST_DAY 41
LOCALTOUTC 41
MINUTE 41
MONTH 42
MONTHNAME 42
NEXT_DAY 42
NOW 42
QUARTER 43
SECOND 43
SECONDS_BETWEEN 43
UTCTOLOCAL 43
WEEK 44
WEEKDAY 44
YEAR 44
Number Functions 44
ABS 44
ACOS 45
ASIN 45
ATAN 45
ATAN2 46
BINTOHEX 46
BITAND 46
CEIL 46
COS 47
COSH 47
COT 47
EXP 47
FLOOR 48
GREATEST 48
HEXTOBIN 48
LEAST 48
LN 49
LOG 49
MOD 49
POWER 50
ROUND 50
SIGN 50
SIN 50
SINH 51
SQRT 51
TAN 51
TANH 51
UMINUS 52
5 2012-05-09
Table of Content
String Functions 52
ASCII 52
CHAR 52
CONCAT 53
LCASE 53
LEFT 53
LENGTH 53
LOCATE 54
LOWER 54
LPAD 54
LTRIM 55
NCHAR 55
REPLACE 55
RIGHT 55
RPAD 56
RTRIM 56
SUBSTR_AFTER 56
SUBSTR_BEFORE 57
SUBSTRING 57
TRIM 57
UCASE 58
UNICODE 58
UPPER 58
Miscellaneous Functions 59
COALESCE 59
CURRENT_CONNECTION 59
CURRENT_SCHEMA 59
CURRENT_USER 59
GROUPING_ID 60
IFNULL 61
MAP 61
NULLIF 62
SESSION_CONTEXT 62
SESSION_USER 63
SYSUUID 63
SQL Sta tements 64
Schema Definition and Manipulation Statements 64
ALTER AUDIT POLICY 64
ALTER FULLTEXT INDEX 65
ALTER INDEX 65
ALTER SEQUENCE 66
ALTER TABLE 67
CREATE AUDIT POLICY 70
CREATE CALCULATION SCENARIO 72
CREATE FULLTEXT INDEX 73
CREATE INDEX 73
CREATE SCHEMA 74
CREATE SEQUENCE 74
CREATE SYNONYM 75
CREATE TABLE 76
CREATE TRIGGER 80
CREATE VIEW 82
DROP AUDIT POLICY 82
DROP CALCULATION SCENARIO 83
DROP FULLTEXT INDEX 83
DROP INDEX 84
DROP SCHEMA 84
DROP SEQUENCE 84
DROP SYNONYM 85
DROP TABLE 85
DROP TRIGGER 86
DROP TYPE 86
DROP VIEW 86
RENAME COLUMN 87
RENAME INDEX 87
RENAME TABLE 87
ALTER TABLE ALTER TYPE 88
TRUNCATE TABLE 88
Data Manipulation Statements 89
DELETE 89
EXPLAIN PLAN 89
INSERT 92
LOAD 93
MERGE DELTA 93
REPLACE | UPSERT 93
6 2012-05-09
Table of Content
SELECT 94
UNLOAD 101
UPDATE 101
System Management Statements 102
SET SYSTEM LICENSE 102
ALTER SYSTEM ALTER CONFIGURATION 102
ALTER SYSTEM ALTER SESSION SET 103
ALTER SYSTEM CANCEL [WORK IN] SESSION 104
ALTER SYSTEM CLEAR SQL PLAN CACHE 104
ALTER SYSTEM CLEAR TRACES 104
ALTER SYSTEM DELETE ALL HANDLED EVENTS 105
ALTER SYSTEM DELETE HANDLED EVENT 105
ALTER SYSTEM DISCONNECT SESSION 105
ALTER SYSTEM LOGGING 105
ALTER SYSTEM RECLAIM DATAVOLUME 106
ALTER SYSTEM RECLAIM LOG 106
ALTER SYSTEM RECLAIM VERSION SPACE 106
ALTER SYSTEM RECONFIGURE SERVICE 107
ALTER SYSTEM REMOVE TRACES 107
ALTER SYSTEM RESET MONITORING VIEW 107
ALTER SYSTEM SAVE PERFTRACE 107
ALTER SYSTEM SAVEPOINT 108
ALTER SYSTEM SET EVENT HANDLED 108
ALTER SYSTEM START PERFTRACE 108
ALTER SYSTEM STOP PERFTRACE 108
ALTER SYSTEM STOP SERVICE 108
UNSET SYSTEM LICENSE ALL 109
Session Management Statements 109
CONNECT 109
SET HISTORY SESSION 109
SET SCHEMA 110
SET [SESSION] 110
UNSET [SESSION] 110
Transaction Management Statements 111
COMMIT 111
LOCK TABLE 111
ROLLBACK 111
SET TRANSACTION 112
Access Control Statements 112
ALTER SAML PROVIDER 112
ALTER USER 113
CREATE ROLE 115
CREATE SAML PROVIDER 115
CREATE USER 116
DROP ROLE 117
DROP SAML PROVIDER 117
DROP USER 118
GRANT 118
REVOKE 123
Data Import Export Statements 124
EXPORT 124
IMPORT 125
IMPORT FROM 126
7 2012-05-09
SAP HANA Database - SQL Reference Manual
8 2012-05-09
SAP HANA Database - SQL Reference Manual
9 2012-05-09
SAP HANA Database - SQL Reference Manual
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.
Symbol Description
Angl e bra ckets a re us ed to s urround the na me of a s ynta cti c el ement (BNF nontermi na l ) of the SQL
<>
l a ngua ge.
The defi ni ti on opera tor i s us ed to provi de defi ni ti ons of the el ement a ppea red on the l eft s i de of
::=
the opera tor i n a producti on rul e.
Squa re bra ckets a re us ed to i ndi ca te opti ona l el ements i n a formul a . Opti ona l el ements ma y be
[]
s peci fi ed or omi tted.
Bra ces group el ements i n a formul a . Repeti ti ve el ements (zero or more el ements ) ca n be s peci fi ed
{}
wi thi n bra ce s ymbol s .
The a l terna ti ve opera tor i ndi ca tes tha t the porti on of the formul a fol l owi ng the ba r i s a n
|
a l terna ti ve to the porti on precedi ng the ba r.
The el l i ps i s i ndi ca tes tha t the el ement ma y be repea ted a ny number of ti mes . If el l i ps i s a ppea rs
... a fter grouped el ements s peci fyi ng tha t the grouped el ements encl os ed wi th bra ces a re repea ted.
If el l i ps i s a ppea rs a fter a s i ngl e el ement, onl y tha t el ement i s repea ted.
Introduces norma l Engl i s h text. Thi s i s us ed when the defi ni ti on of a s ynta cti c el ement i s not
!!
expres s ed i n BNF.
10 2012-05-09
SAP HANA Database - SQL Reference Manual
Introduction
This chapter describes the SAP HANA Database implementation of Structured Query Language (SQL). It
explains the characteristics of SQL, also how to manage comments and reserve words.
SQL
SQL stands for Structured Query Language. It is a standardized language for communicating with a relational
database. SQL is used to retrieve, store or manipulate information in the database.
Comment
You can add comments to improve readability and maintainability of your SQL statements. Comments are
delimited in SQL statements as follows:
Double hyphens "--". Everything after the double hyphen until the end of a line is considered by the
SQL parser to be a comment
"/*" and "*\/". This style of commenting is used to place comments on multiple lines. All text between
the opening "/*" and closing "*\/" is ignored by the SQL parser.
Identifiers
Syntax:
Identifiers are used to represent names used in SQL statement including table name, view name, synonym
name, column name, index name, function name, procedure name, user name, role name, and so on. There
are two kinds of identifiers; undelimited identifiers and delimited identifiers.
Undelimited table and column names must start with a letter and cannot contain any symbols other
than digits or an underscore "_".
Delimited identifiers are enclosed in the delimiter, double quotes, then the identifier can contain any
character including special characters. For example, "AB$%CD" is a valid identifier name.
Limitations:
"_SYS_" is reserved exclusively for database engine, hence not allowed at the beginning of
schema object names.
Role name and user name must be specified as undelimited identifiers.
Maximum length for the identifiers is 127 characters.
11 2012-05-09
SAP HANA Database - SQL Reference Manual
Double quotation marks are used to delimit identifiers and double quotation mark itself can be represented
using two double quotation marks.
The following table lists all the current and future reserved words for the SAP HANA Database.
12 2012-05-09
SAP HANA Database - SQL Reference Manual
Data Types
This section describes the data types used in the SAP HANA Database.
Data type specifies the characteristics of a data value. A special value of NULL is included in every data type
to indicate the absence of a value. The following table shows the built-in data types available in the SAP
HANA Database.
In the SAP HANA Database each data type can be classified by its characteristic as follows:
Datetime Types
DATE
The DATE data type consists of year, month, and day information to represent a date value. The
default format for the DATE data type is 'YYYY-MM-DD'. YYYY represents the year, MM represents
the month, and DD represents the day. The range of date value is 0001-01-01 through 9999-12-31.
TIME
The TIME data type consists of hour, minute, and second to represent a time value. The default
format for the TIME data type is 'HH24:MI:SS'. HH24 represents the hour from 0 to 24, MI represents
the minute from 0 to 59, SS represents the second from 0 to 59.
SECONDDATE
The SECONDDATE data type consists of year, month, day, hour, minute and second information to
represent a date with time value. The default format for the SECONDDATE data type is 'YYYY-MM-DD
HH24:MI:SS'. YYYY represents the year, MM represents the month, DD represents the day, HH24
represents hour, MI represents minute, and SS represents seconds. The range of date value is 0001-
01-01 00:00:01 through 9999-12-31 24:00:00.
TIMESTAMP
The TIMESTAMP data type consists of date and time information. Its default format is 'YYYY-MM-DD
HH24:MI:SS.FF7'. FFn represents the fractional seconds where n indicates the number of digits in
fractional part. . The range of the timestamp value is 0001-01-01 00:00:00.0000000 through 9999-12-
31 23:59:59.9999999.
For details on supported formats for datetime types, refer to Table 4, Table 5, Table 6 and Table 7 below.
Date Formats
The following date/time formats can be used when parsing a string into a date/time type and converting a
date/time type value into a string value. Please note that format for Timestamp is the combination of Date
and Time with the additional support for fractional seconds.
13 2012-05-09
SAP HANA Database - SQL Reference Manual
Time Formats
Timestamp Formats
Additional Formats
14 2012-05-09
SAP HANA Database - SQL Reference Manual
ADD_DAYS
ADD_MONTHS
ADD_SECONDS
ADD_YEARS
COALESCE
CURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMP
CURRENT_UTCDATE
CURRENT_UTCTIME
CURRENT_UTCTIMESTAMP
DAYNAME
DAYOFMONTH
DAYOFYEAR
DAYS_BETWEEN
EXTRACT
GREATEST
GREATEST
HOUR
IFNULL
ISOWEEK
LAST_DAY
LEAST
LOCALTOUTC
MINUTE
MONTH
MONTHNAME
NEXT_DAY
NULLIF
QUARTER
SECOND
SECONDS_BETWEEN
TO_CHAR
TO_DATE
TO_DATS
TO_NCHAR
TO_TIME
TO_TIMESTAMP
UTCTOLOCAL
WEEK
WEEKDAY
YEAR
Numeric Types
TINYINT
The TINYINT data type stores an 8-bit unsigned integer. The minimum value is 0 and the maximum
value is 255 for TINYINT.
SMALLINT
The SMALLINT data type stores a 16-bit signed integer. The minimum value is -32,768 and the
maximum value is 32,767 for SMALLINT.
15 2012-05-09
SAP HANA Database - SQL Reference Manual
INTEGER
The INTEGER data type stores a 32-bit signed integer. The minimum value is -2,147,483,648 and the
maximum value is 2,147,483,647 for INTEGER.
BIGINT
The BIGINT data type stores a 64-bit signed integer. The minimum value is -
9,223,372,036,854,775,808 and the maximum value is 9,223,372,036,854,775,807 for BIGINT.
The scale is the number of digits from the decimal point to the least significant digit and can range
from -6,111 to 6,176, which means scale specifies the range of the exponent in the decimal number
from 10-6111 to 106176. If scale is not specified, it defaults to 0. Scale is positive when the number has
significant digits to the right of the decimal point and negative when the number has significant digits
to the left of the decimal point.
Examples: 0.0000001234 (1234 x 10-10) has the precision 4 and the scale 10. 1.0000001234
(10000001234 x 10-10) has the precision 11 and scale 10. 1234000000 (1234x106) has the precision 4
and scale -6.
When precision and scale are not specified, DECIMAL becomes a floating-point decimal number. In
this case, precision and scale can vary within the range described above, 1~34 for precision and -
6,111~6,176 for scale depending on the stored value.
SMALLDECIMAL
The SMALLDECIMAL is a floating-point decimal number. The precision and scale can vary within the
range, 1~16 for precision and -369~368 for scale depending on the stored value. SMALLDECIMAL is
supported only on column store.
DECIMAL and SMALLDECIMAL are floating-point types. For instance, a decimal column can store any
of 3.14, 3.1415, 3.141592 whilst maintaining their precision.
DECIMAL(p, s) is the SQL standard notation for fixed-point decimal. For instance, 3.14, 3.1415,
3.141592 are stored in a decimal(5, 4) column as 3.1400, 3.1415, 3.1416, respectively keeping the
specified precision(5) and scale(4).
REAL
The REAL data type specifies a single-precision 32-bit floating-point number.
DOUBLE
The DOUBLE data type specifies a single-precision 64-bit floating-point number. The minimum value is
-1.79769 x 10308 and the maximum value is 1.79769x10308 . The smallest positive DOUBLE value is
2.2207x10-308 and the largest negative DOUBLE value is -2.2207x10-308.
FLOAT(n)
The FLOAT(n) data type specifies a 32-bit or 64-bit real number, where n specifies the number of
significant bits and can range between 1 and 53.
When you use the FLOAT(n) data type, if n is smaller than 25, it becomes a 32-bit REAL data type. If n
is greater than or equal to 25, it then becomes a 64-bit DOUBLE data type. If n is not declared, it
becomes a 64-bit double data type by default.
VARCHAR
The VARCHAR(n) data type specifies a variable-length ASCII character string, where n indicates the
maximum length and is an integer between 1 and 5000.
NVARCHAR
The NVARCHAR(n) data type specifies a variable-length Unicode character set string, where n
indicates the maximum length and is an integer between 1 and 5000.
ALPHANUM
The ALPHANUM(n) data type specifies a variable-length character string which contains alpha-
numeric characters, where n indicates the maximum length and is an integer between 1 and 127.
SHORTTEXT
The SHORTTEXT(n) data type specifies veriable-length character string which supports textsearch-
16 2012-05-09
SAP HANA Database - SQL Reference Manual
Binary Types
Binary types are used to store bytes of binary data.
VARBINARY
The VARBINARY(n) data type is used to store binary data of a specified maximum length in bytes,
where n indicates the maximum length and is an integer between 1 and 5000.
BLOB
The BLOB data type is used to store large binary data.
CLOB
The CLOB data type is used to store large ASCII character data.
NCLOB
The NCLOB data type is used to store a large Unicode character object.
TEXT
The TEXT data type specifies which supports textsearch-features. This is not a standalone sql-type.
Selecting a TEXT-column yields a column of type NCLOB.
<opt_fulltext_elem_list_text> ::=
<fulltext_elem_text> [... ',' <fulltext_elem_text>]
LOB types are provided for storing and retrieving such large data. LOB types support the following
operations.
17 2012-05-09
SAP HANA Database - SQL Reference Manual
Mapping between SQL Data Type and Column Store Data Type
This section describes the data type conversion allowed in SAP HANA Database.
The type of an expression result, for example a field reference, a function on fields, or literals can be
converted using the following functions: CAST, TO_ALPHANUM, TO_BIGINT, TO_VARBINARY,
TO_BLOB, TO_CLOB, TO_DATE, TO_DATS, TO_DECIMAL, TO_DOUBLE, TO_INTEGER, TO_INT,
TO_NCLOB, TO_NVARCHAR, TO_REAL, TO_SECONDDATE, TO_SMALLINT, TO_TINYINT, TO_TIME,
TO_TIMESTAMP, TO_VARCHAR.
When a given set of operand/argument types does not match what an operator/function expects, a
type conversion is carried out by the SAP HANA Database. This conversion only occurs if a relevant
conversion is available and if it makes the operation/function executable. For instance, a comparison
of BIGINT and VARCHAR is performed by implicitly converting VARCHAR to BIGINT. The entire explicit
conversions can be used for implicit conversion except for the TIME and TIMESTAMP data types. TIME
and TIMESTAMP can be converted to each other using TO_TIME(TIMESTAMP) and
TO_TIMESTAMP(TIME).
Examples
Boxes with "OK" means data type conversions are allowed without any checks.
Boxes with "CHK" means the data type can be converted if the data is valid for the target type.
Boxes with "-" indicates that data type conversion is not allowed.
The rules shown are applicable to both implicit and explicit conversion except for Time to Timestamp
conversion. Only explicit conversions are allowed for converting the Time data type to Timestamp using the
TO_TIMESTAMP or CAST functions.
18 2012-05-09
SAP HANA Database - SQL Reference Manual
smalldecimal
decimal(p,s)
Target/
nvarchar
smallint
decimal
varchar
double
integer
tinyint
Source
bigint
real
tinyint - OK OK OK OK OK OK OK OK OK OK
smallint CHK - OK OK OK OK OK OK OK OK OK
decimal(p,s) CHK CHK CHK CHK CHK CHK CHK CHK CHK CHK OK
varchar CHK CHK CHK CHK CHK CHK CHK CHK CHK - OK
nvarchar CHK CHK CHK CHK CHK CHK CHK CHK CHK CHK -
Table 9a: Data type conversion table
Target/
time date seconddate timestamp varchar nvarchar
Source
time - - - - OK OK
date - - OK OK OK OK
seconddate ti me da te - ti mes ta mp OK OK
timestamp ti me da te s econdda te - OK OK
Target/
varbinary alphanum varchar nvarchar
Source
varbinary - - - -
alphanum - - OK OK
varchar OK OK - OK
nvarchar OK OK CHK -
Table 9c: Data type conversion table
This section describes the data type precedence implemented by the SAP HANA Database. Data type
precedence specifies that the data type with lower precedence is converted to the data type with higher
precedence.
19 2012-05-09
SAP HANA Database - SQL Reference Manual
Highest TIMESTAMP
SECONDDATE
DATE
TIME
DOUBLE
REAL
DECIMAL
SMALLDECIMAL
BIGINT
INTEGER
SMALLINT
TINYINT
NCLOB
NVARCHAR
CLOB
VARCHAR
BLOB
Lowest VARBINARY
Typed Constant
'Brian'
'100'
Unicode string has a similar format to character string but is preceded by an N identifier (N stands for
National Language in the SQL-92 standard). The N prefix must be uppercase.
N'abc'
SELECT 'Brian' "character string 1", '100' "character string 2", N'abc' "unicode st
ring" FROM DUMMY;
Number constant
A number constant is represented by a string of numbers that are not enclosed in quotation marks.
Numbers may contain a decimal point or scientific notation.
123
123.4
1.234e2
A hexadecimal number constant is a string of hexadecimal numbers and has the prefix 0x.
0x0abc
X'00abcd'
x'dcba00'
SELECT X'00abcd' "binary string 1", x'dcba00' "binary string 2" FROM DUMMY;
20 2012-05-09
SAP HANA Database - SQL Reference Manual
00ABCD, DCBA00
Date/Time/Timestamp constant
Date, Time and Timestamp each have the following prefixes.
date'2010-01-01'
time'11:00:00.001'
timestamp'2011-12-31 23:59:59'
21 2012-05-09
SAP HANA Database - SQL Reference Manual
Predicates
A predicate is specified by combining one or more expressions, or logical operators, and returns one of the
following logical/truth values: TRUE, FALSE, or UNKNOWN.
Comparison Predicates
Two values are compared using comparison predicates and the comparison returns true, false, or unknown.
Syntax:
<comparison_predicate> ::=
<expression> { = | != | <> | > | < | >= | <= } [ ANY | SOME| ALL ] { <expression_li
st> | <subquery> }
<expression_list> ::= <expression>, ...
Expressions can be a simple expression such as a character, date, or number. An expression can also be a
scalar subquery.
ANY, SOME - When ANY or SOME are specified, the comparison returns true if at least one value returned by
the subquery or expression_list is true. ALL - When ALL is specified, the comparison returns true if the
comparison of all values returned by the subquery or expression_list is true.
Range Predicate
A value is compared with a list of values within the provided range.
Syntax:
BETWEEN ... AND ... - When a range predicate is used, it returns true if expression1 is within the range
specified by expression2 and expression3. True will only be returned if expression2 has a lesser value than
expression3.
In Predicate
A value is compared with a specified set of values. True will be returned if the value of expression1 is found in
the expression_list (or subquery).
Syntax:
Exists Predicate
Returns true if the subquery returns a result set that is not empty and returns false if the subquery returns an
empty result set.
Syntax:
LIKE Predicate
The LIKE predicate is used for string comparisons. Expression1 is tested for a pattern contained in
expression2. Wildcard characters ( % ) and ( _ ) may be used in the comparison string expression2. LIKE
returns true if the pattern specified by expression2 is found.
The percentage sign (%) matches zero or more characters and underscore (_) matches exactly one
character. To match a percent sign or underscore in the LIKE predicate, an escape character must be used.
Using the optional argument, ESCAPE expression3, you can specify the escape character that will be used
allowing the underscore (_) or percentage sign (%) to be matched.
Syntax:
NULL Predicate
22 2012-05-09
SAP HANA Database - SQL Reference Manual
When the IS NULL predicate is specified, a value can be compared with NULL. IS NULL returns true if the
expression value is NULL. If the IS NOT NULL predicate is specified, it returns true if a value is not NULL.
Syntax:
CONTAINS Predicate
The CONTAINS predicate is used to search for text-matches to a search string in subqueries.
Syntax:
search_string
The freestyle-search-string format is used (eg. Peter "Palo Alto" OR Berlin -"SAP LABS" )
search_specifier
If the search_specifier clause is not specified EXACT is taken as default
EXACT
EXACT returns true for those records where exact matches of the searchterms are found in the search-
attributes
FUZZY
FUZZY returns true for those records where words similar to the searchterms are found in the search-
attributes (e.g. spelling errors will be ignored to a certain extent)
float_const
If float_const is omitted, then 0.8 is the default. This default can be overridden by defining parameter
FUZZINESSTHRESHOLD supported by columnstore join-views
WEIGHT
If a weights list is specified, it must be the same size as the number of (expanded) columns in
<contains_columns>
LANGUAGE
23 2012-05-09
SAP HANA Database - SQL Reference Manual
LANGUAGE is used during preprocessing of the search string and as a pre-search filter. Only documents which
match the search string and the language specified are returned.
LINGUISTIC
LINGUISTIC returns true for those records where word-variants of the searchterms are found in the search-
attributes (e.g. searching for 'cats' will also return records which contain 'cat')
Limitations: If there are multiple CONTAINS predicates specified in the where clause of a select statement,
then only one of the predicates may consist of more than one column in the <contains_columns> list
The CONTAINS-predicate works only on column store tables (simple tables and join-views)
Examples:
Exact search
Fuzzy search
Linguistic search:
Freestyle search:
The freestyle-search is a search mulitple columns.
24 2012-05-09
SAP HANA Database - SQL Reference Manual
Operators
You can perform arithmetic operations in expressions by using operators. Operators can be used for
calculation, value comparison or to assign values.
una ry nega ti on
A una ry opera tor a ppl i es to one opera nd or a
Una ry opera tor opera nd opera tor(-)
s i ngl e va l ue expres s i on.
l ogi ca l
nega ti on(NOT)
mul ti pl i ca ti ve
opera tors ( *, / )
Operator Precedence
An expression can use several operators. If the number of operators is greater than one then the SAP HANA
Database will evaluate them in order of operator precedence. You can change the order of evaluation by
using parentheses, as expressions contained within parentheses are always evaluated first.
If parentheses are not used, the operators have the precedence indicated by the table below. Please note,
the SAP HANA Database will evaluate operators with equal precedence from left to right within an
expression.
Arithmetic Operators
You use arithmetic operators to perform mathematical operations such as adding, subtracting, multiplying,
dividing and negation of numeric values.
25 2012-05-09
SAP HANA Database - SQL Reference Manual
Operator Description
-<expres s i on> Nega ti on. If the expres s i on i s the NULL va l ue, the res ul t i s NULL.
<expres s i on> +
Addi ti on. If ei ther expres s i on i s the NULL va l ue, the res ul t i s NULL.
<expres s i on>
<expres s i on> -
Subtra cti on. If ei ther expres s i on i s the NULL va l ue, the res ul t i s NULL.
<expres s i on>
<expres s i on> *
Mul ti pl i ca ti on. If ei ther expres s i on i s NULL, the res ul t i s NULL.
<expres s i on>
<expres s i on> / Di vi s i on. If ei ther expres s i on i s NULL, or i f the s econd expres s i on i s 0, a n error i s
<expres s i on> returned.
Table 12. Arithmetic operators
String Operators
A concatenation operator combines two items such as strings, expressions or constants into one.
Operator Description
Stri ng conca tena ti on (two verti ca l ba rs ).
<expres s i on> || <expres s i on>
If ei ther s tri ng i s NULL, i t returns NULL.
Table 13. Concatenation operators
For VARCHAR or NVARCHAR type strings, leading or trailing spaces are kept. If either string is of data type
NVARCHAR, the result has data type NVARCHAR and is limited to 5000 characters. The maximum length for
VARCHAR concatenation is also limited to 5000 characters.
Comparsion Operators
Syntax:
Logical Operators
Search conditions can be combined using AND or OR operators. You can also negate them using the NOT
operator.
Set Operators
The operators described in this section perform set operations on the results of two or more queries.
26 2012-05-09
SAP HANA Database - SQL Reference Manual
27 2012-05-09
SAP HANA Database - SQL Reference Manual
Expressions
An expression is a clause that can be evaluated to return values.
Syntax:
<expression> ::=
<case_expression>
| <function_expression>
| <aggregate_expression>
| (<expression> )
| ( <subquery> )
| - <expression>
| <expression> <operator> <expression>
| <variable_name>
| <constant>
| [<correlation_name>.]<column_name>
Case Expressions
A case expression allows the user to use IF ... THEN ... ELSE logic without using procedures in SQL statements.
Syntax:
<case_expression> ::=
CASE <expression>
WHEN <expression> THEN <expression>, ...
[ ELSE <expression>]
{ END | END CASE }
If the expression following the CASE statement is equal to the expression following the WHEN statement,
then the expression following the THEN statement is returned. Otherwise the expression following the ELSE
statement is returned if it exists.
Function Expressions
SQL built-in functions can be used as an expression.
Syntax:
Aggregate Expressions
An aggregate expression uses an aggregate function to calculate a single value from the values of multiple
rows in a column.
Syntax:
Aggregate
Description
name
Counts the number of rows returned by a query. COUNT(*) returns the number of rows , rega rdl es s
COUNT of the va l ue of thos e rows a nd i ncl udi ng dupl i ca te va l ues . COUNT(<expres s i on>) returns the
number of non-NULL va l ues for tha t expres s i on returned by the query.
MIN Returns the mi ni mum va l ue of expres s i on.
MAX Returns the ma xi mum va l ue of expres s i on.
SUM Returns the s um of expres s i on.
AVG Returns the a ri thmeti ca l mea n of expres s i on.
STDDEV Returns the s ta nda rd devi a ti on of gi ven expres s i on a s the s qua re root of VARIANCE functi on.
VAR Returns the va ri a nce of expres s i on a s the s qua re of s ta nda rd devi a ti on.
Subqueries in Expressions
28 2012-05-09
SAP HANA Database - SQL Reference Manual
A subquery is a SELECT statement enclosed in parentheses. The SELECT statement can contain one and only
one select list item. When used as an expression a scalar subquery is allowed to return only zero or one value.
Syntax:
Within the SELECT list of the top level SELECT, or in the SET clause of an UPDATE statement, you can use a
scalar subquery anywhere that you can use a column name. However, scalar_subquery cannot be used inside
GROUP BY clause.
Example:
For example, the following statement returns the number of employees in each department, grouped by
department name:
29 2012-05-09
SAP HANA Database - SQL Reference Manual
SQL Functions
Introduction
This chapter describes SQL Functions that are provided by SAP HANA Database.
Data type conversion functions are used to convert arguments from one data type to another, or to test
whether a conversion is possible.
CAST
Syntax
Syntax Elements
expression - The expression to be converted. data type - The target data type. TINYINT | SMALLINT |
INTEGER | BIGINT | DECIMAL | SMALLDECIMAL | REAL | DOUBLE | ALPHANUM | VARCHAR | NVARCHAR |
DAYDATE | DATE | TIME | SECONDDATE | TIMESTAMP
Description
Example
cast
7
TO_ALPHANUM
Syntax
TO_ALPHANUM (value)
Description
Example
to alphanum
10
TO_BIGINT
Syntax
TO_BIGINT (value)
Description
30 2012-05-09
SAP HANA Database - SQL Reference Manual
Example
to bigint
10
TO_BINARY
Syntax
TO_BINARY (value)
Description
Example
to binary
616263
TO_BLOB
Syntax
TO_BLOB (value)
Description
Converts a value to a BLOB data type. The argument value must be a binary string.
Example
to blob
abcde
TO_CHAR
Syntax
Description
Converts a given value to a CHAR character data type. If the format specifier is omitted, the conversion is
performed using the date format model as explained in Date Formats
Example
to char
2009/12/31
TO_CLOB
Syntax
TO_CLOB (value)
Description
31 2012-05-09
SAP HANA Database - SQL Reference Manual
Example
SELECT TO_CLOB ('TO_CLOB converts the value to a CLOB data type') "to clob" FROM DU
MMY;
to clob
TO_CLOB converts the value to a CLOB data type
TO_DATE
Syntax
TO_DATE (d [, format])
Description
Converts a date string d into a DATE data type. If the format specifier is omitted, the conversion is performed
using the date format model as explained in Date Formats.
Example
to date
2010-01-12
TO_DATS
Syntax
TO_DATS (d)
Description
Converts a date string d into an ABAP DATE string with format 'YYYYMMDD'.
Example
abap date
20100112
TO_DECIMAL
Syntax
Description
The precision is the total number of significant digits and can range from 1 to 34.
The scale is the number of digits from the decimal point to the least significant digit and can range from -
6,111 to 6,176. This means that the scale specifies the range of the exponent in the decimal number from 10-
6111 to 106176. If the scale is not specified, it defaults to 0. Scale is positive when the number has significant
digits to the right of the decimal point, and negative when the number has significant digits to the left of the
decimal point.
When precision and scale are not specified, DECIMAL becomes a floating-point decimal number. In this case,
precision and scale can vary within the range described above, 1~34 for precision and -6,111~6,176 for scale
depending on the stored value.
32 2012-05-09
SAP HANA Database - SQL Reference Manual
Example
to decimal
7654321.889
TO_DOUBLE
Syntax
TO_DOUBLE (value)
Description
Example
to double
45.36
TO_INT
Syntax
TO_INT (value)
Description
Example
to int
10
TO_INTEGER
Syntax
TO_INTEGER (value)
Description
Example
to int
10
TO_NCHAR
Syntax
Description
Converts the value to a NCHAR unicode character data type. If the format specifier is omitted, the conversion
33 2012-05-09
SAP HANA Database - SQL Reference Manual
Example
to nchar
2009/12/31
TO_NCLOB
Syntax
TO_NCLOB (value)
Description
Example
SELECT TO_NCLOB ('TO_NCLOB converts the value to a NCLOB data type') "to nclob" FRO
M DUMMY;
to nclob
TO_NCLOB converts the value to a NCLOB data type
TO_NVARCHAR
Syntax
Description
Converts the value to a NVARCHAR unicode character data type. If the format specifier is omitted, the
conversion is performed using the date format model as explained in Date Formats.
Example
to nchar
09-12-31
TO_REAL
Syntax
TO_REAL (value)
Description
Example
to real
45.36000061035156
TO_SECONDDATE
Syntax
TO_SECONDDATE (d [, format])
34 2012-05-09
SAP HANA Database - SQL Reference Manual
Description
Converts a date string d into a SECONDDATE data type. If the format specifier is omitted, the conversion is
performed using the date format model as explained in Date Formats.
Example
to seconddate
2010-01-11 13:30:00.0
TO_SMALLDECIMAL
Syntax
TO_SMALLDECIMAL (value)
Description
Example
to smalldecimal
7654321.89
TO_SMALLINT
Syntax
TO_SMALLINT (value)
Description
Example
to smallint
10
TO_TIME
Syntax
TO_TIME (t [, format])
Description
Converts a time string t into the TIME data type. If the format specifier is omitted, the conversion is
performed using the time format model as explained in Time Formats.
Example
SELECT TO_TIME ('08:30 AM', 'HH:MI AM') "to time" FROM DUMMY;
to time
08:30:00
TO_TIMESTAMP
35 2012-05-09
SAP HANA Database - SQL Reference Manual
Syntax
TO_TIMESTAMP (d [, format])
Description
Converts a date string d into the TIMESTAMP data type. If the format specifier is omitted, the conversion is
performed using the date format model as explained in Date Formats.
Example
to timestamp
2010-01-11 13:30:00.0
TO_TINYINT
Syntax
TO_TINYINT (value)
Description
Example
to tinyint
10
TO_VARCHAR
Syntax
Description
Converts a given value to a VARCHAR character data type. If the format specifier is omitted, the conversion is
performed using the date format model as explained in Date Formats.
Example
to char
2009/12/31
DateTime Functions
ADD_DAYS
Syntax
ADD_DAYS (d, n)
Description
Example
36 2012-05-09
SAP HANA Database - SQL Reference Manual
SELECT ADD_DAYS (TO_DATE ('2009-12-05', 'YYYY-MM-DD'), 30) "add days" FROM DUMMY;
add days
2010-01-04
ADD_MONTHS
Syntax
ADD_MONTHS (d, n)
Description
Example
add months
2010-01-05
ADD_SECONDS
Syntax
ADD_SECONDS (t, n)
Description
Example
add seconds
2012-01-02 00:00:45.0
ADD_YEARS
Syntax
ADD_YEARS (d, n)
Description
Example
add years
2010-12-05
CURRENT_DATE
Syntax
CURRENT_DATE
Description
37 2012-05-09
SAP HANA Database - SQL Reference Manual
Example
current date
2010-01-11
CURRENT_TIME
Syntax
CURRENT_TIME
Description
Example
current time
17:37:37
CURRENT_TIMESTAMP
Syntax
CURRENT_TIMESTAMP
Description
Example
current timestamp
2010-01-11 17:38:48.802
CURRENT_UTCDATE
Syntax
CURRENT_UTCDATE
Description
Returns the current UTC date. The UTC stands for Coordinated Universal Time, also known as Greenwich
Mean Time (GMT).
Example
CURRENT_UTCTIME
Syntax
CURRENT_UTCTIME
Description
38 2012-05-09
SAP HANA Database - SQL Reference Manual
Example
CURRENT_UTCTIMESTAMP
Syntax
CURRENT_UTCTIMESTAMP
Description
Example
DAYNAME
Syntax
DAYNAME (d)
Description
Example
dayname
MONDAY
DAYOFMONTH
Syntax
DAYOFMONTH (d)
Description
Example
dayofmonth
30
DAYOFYEAR
Syntax
DAYOFYEAR (d)
39 2012-05-09
SAP HANA Database - SQL Reference Manual
Description
Example
dayofyear
150
DAYS_BETWEEN
Syntax
Description
Example
days between
31
EXTRACT
Syntax
Description
Finds and returns the value of a specified datetime field from date d.
Example
SELECT EXTRACT (YEAR FROM TO_DATE ('2010-01-04', 'YYYY-MM-DD')) "extract" FROM DUM
MY;
extract
2010
HOUR
Syntax
HOUR (t)
Description
Example
hour
12
ISOWEEK
Syntax
40 2012-05-09
SAP HANA Database - SQL Reference Manual
ISOWEEK (d)
Description
Returns the ISO year and week numbers of date d. The week number is prefixed by the letter W.
Example
isoweek
2011-W22
LAST_DAY
Syntax
LAST_DAY (d)
Description
Returns the date of the last day of the month that contains the date d.
Example
last day
2010-01-31
LOCALTOUTC
Syntax
Description
Example
localtoutc
2012-01-01 06:00:00.0
MINUTE
Syntax
MINUTE (t)
Description
Example
minute
34
41 2012-05-09
SAP HANA Database - SQL Reference Manual
MONTH
Syntax
MONTH(d)
Description
Example
month
5
MONTHNAME
Syntax
MONTHNAME(d)
Description
Example
monthname
MAY
NEXT_DAY
Syntax
NEXT_DAY (d)
Description
Example
next day
2010-01-01
NOW
Syntax
NOW ()
Description
Example
now
42 2012-05-09
SAP HANA Database - SQL Reference Manual
2010-01-01 16:34:19.894
QUARTER
Syntax
Description
Returns the numerical year quarter of date d. The first quarter starts in the month specified by start_month.
If start_month is not specified the first quarter is assumed to begin in January.
Example
quarter
2011-Q4
SECOND
Syntax
SECOND (t)
Description
Example
second
56
SECONDS_BETWEEN
Syntax
Description
Computes the number of seconds between date arguments d1 and d2, which is semantically equal to d2 - d1.
Example
Seconds between
2678400
UTCTOLOCAL
Syntax
Description
Example
43 2012-05-09
SAP HANA Database - SQL Reference Manual
utctolocal
2011-12-31 20:00:00.0
WEEK
Syntax
WEEK (d)
Description
Example
week
23
WEEKDAY
Syntax
WEEKDAY (d)
Description
Returns an integer representation of the day of the week for date d. The return value ranges from 0 to 6,
representing Monday(0) through to Sunday(6).
Example
week day
4
YEAR
Syntax
YEAR (d)
Description
Example
year
2011
Number Functions
Number functions take numeric values, or strings with numeric characters, as inputs and return numeric
values. When strings with numeric characters are provided as inputs implicit conversion from a string to a
number is performed automatically before results are computed.
ABS
44 2012-05-09
SAP HANA Database - SQL Reference Manual
Syntax
ABS (n)
Description
Example
absolute
1
ACOS
Syntax
ACOS (n)
Description
Example
acos
1.0471975511965979
ASIN
Syntax
ASIN (n)
Description
Example
asin
0.5235987755982989
ATAN
Syntax
ATAN (n)
Description
Returns the arc-tangent, in radians, of the numeric argument n. The range of n is unlimited.
Example
atan
0.4636476090008061
45 2012-05-09
SAP HANA Database - SQL Reference Manual
ATAN2
Syntax
ATAN2 (n, m)
Description
Returns the arc-tangent, in radians, of the ratio of two numbers n and m. This produces the same result as
ATAN(n/m).
Example
atan2
0.4636476090008061
BINTOHEX
Syntax
BINTOHEX (expression)
Description
Example
bintohex
4142
BITAND
Syntax
BITAND (n, m)
Description
Performs an AND operation on the bits of the arguments n and m. Both n and m must be non-negative
integers. The BITAND function returns a result with BIGINT type.
Example
bitand
123
CEIL
Syntax
CEIL (n)
Description
Example
46 2012-05-09
SAP HANA Database - SQL Reference Manual
ceiling
15
COS
Syntax
COS (n)
Description
Example
cos
1.0
COSH
Syntax
COSH (n)
Description
Example
cosh
1.1276259652063807
COT
Syntax
COT (n)
Description
Computes the cotangent of a number n, where the argument is an angle expressed in radians.
Example
cot
-0.8950829176379128
EXP
Syntax
EXP (n)
Description
Returns the result of the base of natural logarithms e raised to the power of the argument n.
Example
47 2012-05-09
SAP HANA Database - SQL Reference Manual
exp
2.718281828459045
FLOOR
Syntax
FLOOR (n)
Description
Returns the largest integer not greater than the numeric argument n.
Example
floor
14
GREATEST
Syntax
Description
Returns the greatest value among the arguments: n1, n2, ...
Example
greatest
bb
HEXTOBIN
Syntax
HEXTOBIN (value)
Description
Example
hextobin
1A
LEAST
Syntax
Description
Example
48 2012-05-09
SAP HANA Database - SQL Reference Manual
least
aa
LN
Syntax
LN (n)
Description
Example
ln
2.1972245773362196
LOG
Syntax
LOG (b, n)
Description
Returns the natural logarithm of a number n base b. Base b must be a positive value greater than 1 and n
must be any positive value.
Example
log
0.30102999566398114
MOD
Syntax
MOD (n, d)
Description
When n is negative this function acts differently to the standard computational modulo operation.
The following explains example of what the MOD function returns as the result.
Example
modulus
49 2012-05-09
SAP HANA Database - SQL Reference Manual
modulus
-3
POWER
Syntax
POWER (b, e)
Description
Example
power
1024.0
ROUND
Syntax
ROUND (n [, pos])
Description
Rounds argument n to the specified pos amount of places after the decimal point.
Example
round
16.2
round
20
SIGN
Syntax
SIGN (n)
Description
Returns the sign (positive or negative) of the numeric argument 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
sign
-1
SIN
Syntax
50 2012-05-09
SAP HANA Database - SQL Reference Manual
SIN (n)
Description
Example
sine
1.0
SINH
Syntax
SINH (n)
Description
Returns the hyperbolic sine of n, where the argument is an angle expressed in radians.
Example
sinh
0.0
SQRT
Syntax
SQRT (n)
Description
Example
sqrt
1.4142135623730951
TAN
Syntax
TAN (n)
Description
Example
tan
0.0
TANH
Syntax
51 2012-05-09
SAP HANA Database - SQL Reference Manual
TANH (n)
Description
Example
tanh
0.7615941559557649
UMINUS
Syntax
UMINUS (n)
Description
Example
uminus
765
String Functions
ASCII
Syntax
ASCII(c)
Description
Example
ascii
65
CHAR
Syntax
CHAR (n)
Description
Example
SELECT CHAR (65) || CHAR (110) || CHAR (116) "character" FROM DUMMY;
character
Ant
52 2012-05-09
SAP HANA Database - SQL Reference Manual
CONCAT
Syntax
Description
Returns a combined string consisting of str1 followed by str2. The concatenation operator (||) is identical to
this function.
Example
concat
Cat
LCASE
Syntax
LCASE(str)
Description
Note:
The LCASE function is identical to the LOWER function.
Example
lcase
test
LEFT
Syntax
LEFT (str, n)
Description
Example
left
Hel
LENGTH
Syntax
LENGTH(str)
Description
Returns the number of characters in string str. For Large Object (LOB) types, this function returns the length
of the object in bytes.
Example
53 2012-05-09
SAP HANA Database - SQL Reference Manual
length
14
LOCATE
Syntax
Description
Returns the position of a substring needle within a string haystack. Returns 0 if needle is not found within
haystack.
Example
Locate
11
Locate
1
Locate
0
LOWER
Syntax
LOWER(str)
Description
Note:
The LOWER function is identical to the LCASE function.
Example
lower
ant
LPAD
Syntax
Description
Pads the start of string str with spaces to make a string of n characters in length. If the pattern argument is
provided string str will be padded using sequences of these characters until the required length is met.
Example
54 2012-05-09
SAP HANA Database - SQL Reference Manual
lpad
123451234512end
LTRIM
Syntax
Description
Returns string str, trimmed of all leading spaces. If remove_set is specified, LTRIM removes all the characters
contained in this set from the start of string str. This process continues until a character not the in
remove_set is reached.
Note:
remove_set is treated as a set of characters and not as a search string.
Example
ltrim
Aabend
NCHAR
Syntax
NCHAR (n)
Description
Example
nchar
A
REPLACE
Syntax
Description
Searches in original_string for all occurrences of search_string and replaces them with replace_string.
Example
replace
UPGRADE UPWARD
RIGHT
55 2012-05-09
SAP HANA Database - SQL Reference Manual
Syntax
RIGHT(str, n)
Description
Example
right
789
RPAD
Syntax
Description
Pads the end of string str with spaces to make a string of n characters in length. If the pattern argument is
provided string str will be padded using sequences of these characters until the required length is met.
Example
right padded
end123451234512
RTRIM
Syntax
Description
Returns string str, trimmed of all trailing spaces. If remove_set is specified, RTRIM removes all the characters
contained in this set from the end of string str. This process continues until a character not the in remove_set
is reached.
Note:
remove_set is treated as a set of characters and not as a search string.
Example
rtrim
endabA
SUBSTR_AFTER
Syntax
Description
Returns a substring of string str that follows the first occurrence of the pattern argument.
If str does not contain the pattern substring, then an empty string is returned.
56 2012-05-09
SAP HANA Database - SQL Reference Manual
Example
substr after
Friend
SUBSTR_BEFORE
Syntax
Description
Returns a substring of string str before the first occurrence of the pattern argument in the target string.
If str does not contain the pattern substring, then an empty string is returned.
If pattern is an empty string, then str is returned.
If str or pattern is NULL, then NULL is returned.
Example
substr before
Hello
SUBSTRING
Syntax
Description
Returns a substring of string str starting from start_position within the string. SUBSTRING can return the
remaining part of a string from the start_position or optionally, a number of characters set by the
string_length parameter.
Example
substring
45
TRIM
Syntax
Description
Returns string str after removing leading and trailing spaces. The trimming operation is carried out either
from the start (LEADING), end (TRAILING) or both(BOTH) ends of string str.
57 2012-05-09
SAP HANA Database - SQL Reference Manual
Example
trim both
123456789
SELECT TRIM (LEADING 'a' FROM 'aaa123456789aa') "trim leading" FROM DUMMY;
trim leading
123456789aa
UCASE
Syntax
UCASE (str)
Description
Note:
The UCASE function is identical to the UPPER function.
Example
ucase
ANT
UNICODE
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
unicode
35
UPPER
Syntax
UPPER (str)
Description
Note:
The UPPER function is identical to the UCASE function.
Example
uppercase
ANT
58 2012-05-09
SAP HANA Database - SQL Reference Manual
ANT
Miscellaneous Functions
COALESCE
Syntax
COALESCE (expression_list)
Description
Returns the first non-NULL expression from a list. At least two expressions must be contained in
expression_list, and all expressions must be comparable. The result will be NULL if all the arguments are
NULL.
Example
ID A B coalesce
1 100.0 80.0 100.0
2 NULL 63.0 69.30000305175781
3 NULL NULL 50.0
CURRENT_CONNECTION
Syntax
CURRENT_CONNECTION
Description
Example
current connection
2
CURRENT_SCHEMA
Syntax
CURRENT_SCHEMA
Description
Example
current schema
SYSTEM
CURRENT_USER
59 2012-05-09
SAP HANA Database - SQL Reference Manual
Syntax
CURRENT_USER
Description
Returns the current user name at the current statement context. This will be user name which is currently at
the top of authorization stack.
Example
current user
SYSTEM
current user
USER_A
current user
USER_B
GROUPING_ID
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
60 2012-05-09
SAP HANA Database - SQL Reference Manual
IFNULL
Syntax
Description
Example
ifnull
diff
ifnull
same
ifnull
NULL
MAP
Syntax
Description
Searches for an expression within a set of search values and returns the corresponding result.
If the expression value is not found and default_result is defined, MAP returns default_result.
If the expression value is not found and default_result is not defined, MAP returns NULL.
61 2012-05-09
SAP HANA Database - SQL Reference Manual
Note:
Search values and corresponding results are always provided in search-result pairs.
Example
SELECT MAP(2, 0, 'Zero', 1, 'One', 2, 'Two', 3, 'Three', 'Default') "map" FROM DUMM
Y;
map
Two
SELECT MAP(99, 0, 'Zero', 1, 'One', 2, 'Two', 3, 'Three', 'Default') "map" FROM DUM
MY;
map
Default
map
NULL
NULLIF
Syntax
Description
NULLIF compares the values of two input expressions. If the first expression equals the second expression,
NULLIF returns NULL.
Example
nullif
diff
nullif
NULL
SESSION_CONTEXT
Syntax
SESSION_CONTEXT(session_variable)
Description
The session_variable accessed can either be predefined or user-defined. Predefined session variables that can
be set by the client are 'APPLICATION', 'APPLICATIONUSER', and 'TRACEPROFILE'.
Session variables can be defined or modified using SET [SESSION] <variable_name> = <value> command, and
unset using UNSET [SESSION] <variable_name>.
Example
62 2012-05-09
SAP HANA Database - SQL Reference Manual
session context
HDBStudio
SESSION_USER
Syntax
SESSION_USER
Description
Example
session user
SYSTEM
session user
USER_B
session user
USER_B
SYSUUID
SYSUUID
SYSUUID
Description
Example
SYSUUID
4DE3CD576C79511BE10000000A3C2220
63 2012-05-09
SAP HANA Database - SQL Reference Manual
SQL Statements
This chapter describes the SQL statements that are supported by the SAP HANA Database.
Syntax
Syntax Elements
ENABLE
Enables the audit policy.
DISABLE
Disables the audit policy.
Description
The ALTER AUDIT POLICY statement enables or disables an audit policy. <policy_name> must specify an
existing audit policy.
Only database users having the system privilege AUDIT ADMIN are allowed to alter an audit policy. Each
database user that has this privilege can alter any audit policy, regardless of if they are the creator of the
policy.
A newly created audit policy is disabled by default and does not cause any auditing to occur. Therefore the
audit policy has to be enabled to make its audit actions take effect.
Configuration Parameters
The following configuration parameters for auditing are stored in global.ini, in the section on auditing
configuration:
default_audit_trail_path
Specifies the file path where the CSVTEXTFILE should be stored.
These parameters can be selected in monitoring view M_INIFILE_CONTENTS if the current user has the
64 2012-05-09
SAP HANA Database - SQL Reference Manual
required system privileges. These parameters will only be seen in the case that they have been explicitly set.
Only database users with system privilege CATALOG READ, DATA ADMIN or INIFILE ADMIN can view the
content of the M_INIFILE_CONTENTS view. For all other database users this view will be empty.
Example
For this example you need to first create an audit policy called priv_audit using the following statement:
CREATE AUDIT POLICY priv_audit AUDITING SUCCESSFUL GRANT PRIVILEGE, REVOKE PRIVILEG
E, GRANT ROLE, REVOKE ROLE LEVEL CRITICAL;
Syntax
Description
The ALTER FULLTEXT INDEX <fulltext_elem_list> statement changes the parameters of an explicit fulltext
index.
The ALTER FULLTEXT INDEX <queue commands>=""> statement changes the queuestate for an
asynchronous explicit fulltext index.
Example
ALTER INDEX
Syntax
Syntax Elements
<index_name>::= <identifier>
Description
65 2012-05-09
SAP HANA Database - SQL Reference Manual
Example
ALTER SEQUENCE
Syntax
Syntax Elements
RESTART WITH
Defines the starting sequence value. If you do not specify a value for the RESTART WITH clause, the current
value of the sequence is used.
INCREMENT BY
Defines the sequence increment.
MAXVALUE
Defines the maximum value that can be generated by the sequence and must be between 0 and
4611686018427387903.
NO MAXVALUE
When the NO MAXVALUE directive is used the maximum value for an ascending sequence will be
4611686018427387903 and the maximum value for a descending sequences will be -1.
MINVALUE
Defines the minimum value that can be generated by the sequence and must be between 0 and
4611686018427387903.
NO MINVALUE
When the NO MINVALUE directive is used, the minimum value for an ascending sequence is 1 and the
minimum value for a descending is -4611686018427387903.
CYCLE
When the CYCLE directive is used the sequence number will be restarted after it reaches its maximum or
minimum value.
NO CYCLE
When the NO CYCLE directive is used the sequence number will not be restarted after it reaches its maximum
or minimum value.
During a restart of the database, the system automatically executes the RESET BY statement and the
sequence value is restarted with the value determined from the RESET BY subquery.
66 2012-05-09
SAP HANA Database - SQL Reference Manual
Description
The ALTER SEQUENCE statement is used to alter the parameters of a sequence generator.
Example
ALTER TABLE
Syntax
Syntax Elements
ALTER
Increasing the length of a column can be done. When modifying column definition is tried in column store, no
error is returned because no check is done inside the database yet. An error may be returned if the data does
not fit in the new data type defined when selecting the column. ALTER does not follow data type conversion
rules yet.
CONSTRAINT
67 2012-05-09
SAP HANA Database - SQL Reference Manual
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.
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').
THREADS <number_of_threads>
Specifies how many threads should be used in parallel for table conversion. The optimal value for number of
threads should set to the number of available CPU cores.
Default: The default value is param_sql_table_conversion_parallelism that is, the number of CPU cores
specified in the indexserver.ini file.
BATCH <batch_size>
Specifies the number of rows inserted in batch, and the default value is 2,000,000 which is the optimal value.
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. However, the batch size more than 2,000,000 might cause high memory consumption, thus it is
not recommended to change this value.
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 moves a table to another location in a distributed environment. The port number is the internal
indexserver port number, 3xx03.
68 2012-05-09
SAP HANA Database - SQL Reference Manual
I you have a partitioned table you can only move individual parts by specifying the optional partition number.
Moving a partitioned table without specifying a partition number will result in an error.
The PHYSICAL keyword is only for column store tables. Row store tables are always moved physical.
If the optional keyword PHYSICAL is specified, the persistence storage is immediately moved to the target
host. Otherwise move will just create a link inside the new host persistence pointing to the old host
persistence. This link will be removed on the next merge or a another move operation without the TO
<host_port> part.
The move PHYSICAL operation without TO <host_port> part will just remove persistence links that might still
exists from previouse move operations.
ADD adds a partition for tables partitioned with RANGE, HASH RANGE, ROUNDROBIN RANGE. When adding
a partition to a table which is partitioned by range and with a rest partition, the rest partition can be
repartitioned if needed.
DROP PARTITION drops a partition for tables partitioned with RANGE, HASH RANGE, ROUNDROBIN RANGE.
<hash_partition> ::=
HASH (<partition_expression>[, ...]) PARTITIONS { <num_partitions> | GET_
NUM_SERVERS() }
DROP PARTITION drops a partition for tables partitioned with RANGE, HASH RANGE, ROUNDROBIN RANGE.
For table partition clause, refer to sql_table_partition(?).
MERGE PARTITIONS merges all parts of a partitioned table into a non-partitioned table.
Changes session type from SIMPLE to HISTORY and creates history-main and history-delta part of a table.
69 2012-05-09
SAP HANA Database - SQL Reference Manual
Changes session type from HISTORY to SIMPLE and drops history-main and history-delta part of a table.
Instruct the merge-manager to use main-memory merges instead of persistent merges for the given table.
Instruct the merge-manager to use persistent merges for the given table (default behaviour).
Enable logging for table. After enabling, you have to perform a savepoint to be sure that all data is persisted
and you have to perfrom a data backup, else you can not recover this data.
Disable logging for table. If logging is disabled, no log entries will be persisted for this table. Changes to this
table will only be written to the data area, when a savepoint is done. This can cause loss of committed
transaction, when the indexserver terminates. In case of termination, you have to truncate this table and
insert all data again.
Syntax
Syntax Elements
<audit_action_name> ::=
GRANT PRIVILEGE | REVOKE PRIVILEGE
| GRANT STRUCTURED PRIVILEGE | REVOKE STRUCTURED PRIVILEGE
| GRANT ROLE | REVOKE ROLE
| GRANT ANY | REVOKE ANY
| CREATE USER | DROP USER
| CREATE ROLE | DROP ROLE
| ENABLE AUDIT POLICY | DISABLE AUDIT POLICY
| CREATE STRUCTURED PRIVILEGE | DROP STRUCTURED PRIVILEGE
| ALTER STRUCTURED PRIVILEGE
| CONNECT
| SYSTEM CONFIGURATION CHANGE
| SET SYSTEM LICENSE | UNSET SYSTEM LICENSE
<audit_level> ::=
EMERGENCY
| ALERT
| CRITICAL
| WARNING
| INFO
Description
The CREATE AUDIT POLICY statement creates a new audit policy. This audit policy can be enabled afterwards
and will then cause the auditing of the specified audit actions to happen.
Only database users having the system privilege AUDIT ADMIN are allowed to create an audit policy.
70 2012-05-09
SAP HANA Database - SQL Reference Manual
The specified audit policy name must not be identical to the name of an existing audit policy.
An audit policy defines which audit actions will be audited. Existing audit policies need to be enabled to make
the auditing happen.
The <audit_status_clause> defines, if only successful or unsuccessful or all executions of the specified audit
actions are audited.
The following audit actions are available. They are grouped in several groups. Audit actions of one group can
be combined in one audit policy. Audit actions of different groups can not be combined in one audit policy.
Group
Audit Policy Description
Number
GRANT PRIVILEGE 1 a udi ts the gra nt of pri vi l eges to us ers or rol es
REVOKE PRIVILEGE 1 a udi ts the revoke of pri vi l eges from us ers or rol es
GRANT STRUCTURED a udi ts the gra nt of s tructured/a na l yti ca l pri vi l eges to us ers or
1
PRIVILEGE rol es
REVOKE STRUCTURED a udi ts the revoke of s tructured/a na l yti ca l pri vi l eges from us ers
1
PRIVILEGE or rol es
GRANT ROLE 1 a udi ts the gra nt of rol es to us ers or rol es
REVOKE ROLE 1 a udi ts the revoke of rol es from us ers or rol es
a udi ts the gra nt of pri vi l eges , s tructured pri vi l eges or rol es to
GRANT ANY 1
us ers or rol es
a udi ts the revoke of pri vi l eges , s tructured pri vi l eges or rol es from
REVOKE ANY 1
us ers or rol es
CREATE USER 2 a udi ts the crea te of us ers
DROP USER 2 a udi ts the drop of us ers
CREATE ROLE 2 a udi ts the crea te of rol es
DROP ROLE 2 a udi ts the drop of rol es
CONNECT 3 a udi ts the connect of us ers to the da ta ba s e
SYSTEM CONFIGURATION
4 a udi ts cha nges to the s ys tem confi gura ti on (e.g. INIFILE)
CHANGE
ENABLE AUDIT POLICY 5 a udi ts the a cti va ti on of a udi t pol i ci es
DISABLE AUDIT POLICY 5 a udi ts the dea cti va ti on of a udi t pol i ci es
CREATE STRUCTURED
6 a udi ts the crea ti on of s tructured/a na l yti ca l pri vi l eges
PRIVILEGE
DROP STRUCTURED
6 a udi ts the des tructi on of s tructured/a na l yti ca l pri vi l ege
PRIVILEGE
ALTER STRUCTURED
6 a udi ts the cha nge of s tructured/a na l yti ca l pri vi l ege
PRIVILEGE
SET SYSTEM LICENSE 7 a udi ts the i ns ta l l a ti on of a l i cens e
UNSET SYSTEM LICENSE 7 a udi ts the del eti on of l i cens es
Each audit policy is assigned to a audit level. Possible levels, in decreasing order of importance, are:
EMERGENCY, ALERT, CRITICAL, WARNING, INFO.
To make auditing happen, audit policies have to be created and enabled and the configuration parameter
global_auditing_state (see below) has to be set to true;
Configuration Parameter
Currently the configuration parameter for auditing are stored in global.ini, section auditing configuration and
are the following:
global_auditing_state ( 'true' / 'false' ) to activate / deactivate the whole auditing, no matter, how many
audit policies are available and enabled. The default is false, meaning: no auditing will happen at all.
default_audit_trail_type ( 'SYSLOGPROTOCOL' / 'CSVTEXTFILE' ) to specify, how to store the auditing results.
SYSLOGPROTOCOL is the default.
CSVTEXTFILE should be used only for testing purposes.
default_audit_trail_path to specify where to store the file, in case CSVTEXTFILE had been selected.
As all configuration parameter, these parameters can be selected in view M_INIFILE_CONTENTS, if the
current user has the needed privilege to do so. But these parameter currently will only be seen in case they
have been set explicitly. This means, they will not be seen with a newly installed database instance.
71 2012-05-09
SAP HANA Database - SQL Reference Manual
Only database users with system privilege CATALOG READ, DATA ADMIN or INIFILE ADMIN can see any info
out of the view M_INIFILE_CONTENTS. For other database users this view will be empty.
Example
A new audit policy named priv_audit is created which will audit successful commands concerning granting
and revoking of privileges and roles. This audit policy has the medium audit level CRITICAL.
This policy has to be enabled explicity (see alter_audit_policy) to make the auditing of the audit policy to
happen.
CREATE AUDIT POLICY priv_audit AUDITING SUCCESSFUL GRANT PRIVILEGE, REVOKE PRIVILEG
E, GRANT ROLE, REVOKE ROLE LEVEL CRITICAL;
Syntax
Syntax Elements
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, a column view of type calculation should be used.
Example
72 2012-05-09
SAP HANA Database - SQL Reference Manual
</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" > 1</filter>
</projection>
</calculationViews>
</calculationScenario>
</cubeSchema>'
;
Syntax
Description
The CREATE FULLTEXT INDEX statement creates an explicit fulltext index on the given table column.
Example
CREATE INDEX
Syntax
Syntax Elements
UNIQUE
Used to create unique indexes. Check for duplicates will occur when an index is created and when a record is
added to the table.
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,
73 2012-05-09
SAP HANA Database - SQL Reference Manual
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, and can be specified only once for each column.
Description
Example
CREATE SCHEMA
Syntax
Syntax Elements
OWNED BY
Specifies the name of the schema owner.
Description
Example
CREATE SEQUENCE
Syntax
Syntax Elements
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
74 2012-05-09
SAP HANA Database - SQL Reference Manual
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 4611686018427387903.
NO MAXVALUE
When MAXVALUE is not specified, the maximum value for an ascending sequence is 4611686018427387903
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.
NO MINVALUE
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.
NO CYCLE
Default option. The sequence number will not be reused after it reaches its maximum or minimum value.
RESET BY
During the restart of the database, database automatically executes the RESET BY statement and the
sequence value is restarted with the specified value from the statement after RESET BY.
If RESET BY is not specified, the sequence value is stored persistently in database. During the restart of the
database, the next value of the sequence is generated from the saved sequence value.
Description
A sequence is used to generate unique integers by multiple users. CURRVAL is used to get the current value
of the sequence and NEXTVAL is used to get the next value of the sequence. CURRVAL is only valid after
calling NEXTVAL in a session.
Example
Example 1:
sequence_name.CURRVAL
sequence_name.NEXTVAL
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 SYNONYM
Syntax
Syntax Elements
Description
The CREATE SYNONYM creates an alternate name for a table, view, procedure or sequence.
You can use a synonym to re-point functions and stored procedures to differing tables, views or sequences
75 2012-05-09
SAP HANA Database - SQL Reference Manual
The optional PUBLIC element allows for the creation of a public synonym.
Example
CREATE TABLE
Syntax
Syntax Elements
table_type:
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 SAP HANA Database 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.
HISTORY COLUMN
Creates a table with a particular transaction session type called 'HISTORY'. Tables with session type HISTORY
support time travel; the execution of queries against historic states of the database is possible.
A database session can be set back to a certain point-in-time. The COMMIT ID variant of the statement takes
a commitid as a parameter. The value of the commitid parameter must occur in COMMIT_ID column of the
system table SYS.TRANSACTION_HISTORY, otherwise an exception will be thrown. The COMMIT ID is useful
when using user defined snapshots. A user defined snapshot can be taken by simply storing the commitid
which is assigned to a transaction during the commit phase. The commitid can be retrieved by executing the
following query directly after a transaction commit:
The TIMESTAMP-variant of the statement takes a timestamp as parameter. Internally, the timestamp is
used to look up a (commit_time,commit_id)-pair inside the system-table SYS.TRANSACTION_HISTORY where
the commit_time is close to the given timestamp (to be more precisely: choose pair where maximal
COMMIT_TIME is smaller or equal to the given timestamp; if no such pair is found an exception will be
raised). The session then will be restored with the determined commit-id as in the COMMIT ID variant.
To terminate a restored session to switch back to the current session, an explicit COMMIT or ROLLBACK has
to be executed on the DB connection.
Statement-level timetravel:
In order to be able to relate the commitid with the commit time, a system table SYS.TRANSACTION_HISTORY
is maintained which stores additional information for each transaction which commits data for history table.
For detailed information on setting session-level timetravel, please refer to SET HISTORY SESSION, and for
76 2012-05-09
SAP HANA Database - SQL Reference Manual
For detailed information on setting session-level timetravel, please refer to SET HISTORY SESSION, and for
details on <subquery>, please refer to sql_command_subquery.
Note:
. Autocommit has to be turned off when a session should be restored (otherwise an exception will be thrown
with an appropriate error message)
. Non-history tables in restored sessions always show their current snapshot
. Only data query statement (select) is allowed inside restored sessions.
. A history table must have a primary key
. The session type can be checked from the column, SESSION_TYPE of the system table SYS.TABLES.
GLOBAL TEMPORARY
Table definition is globally available while data is visible only to the current session. The table is truncated at
the end of the session.
Metadata in a global temporary table is persistent meaning the metadata exists until the table is dropped
and the metadata is shared across sessions. Data in a global temporary table is session-specific meaning only
the owner session of the global temporary table is allowed to insert/read/truncate the data, exists for the
duration of the session and data from the global temporary table is automatically dropped when the session
is terminated. Global temporary table can be dropped only when the table does not have any record in it.
LOCAL TEMPORARY
The table definition and data is visible only to the current session. The table is truncated at the end of the
session.
Metadata exists for the duration of the session and is session-specific meaning only the owner session of the
local temporary table is allowed to see. Data in a local temporary table is session-specific meaning only the
owner session of the local temporary table is allowed to insert/read/truncate the data, exists for the duration
of the session and data from the local temporary table is automatically dropped when the session is
terminated.
table_contents_source:
DEFAULT
Default specifies a value to be assigned to the column if an INSERT statement does not provide a value for the
column.
77 2012-05-09
SAP HANA Database - SQL Reference Manual
Available DDIC data types are DDIC_ACCP, DDIC_ALNM, DDIC_CHAR, DDIC_CDAY, DDIC_CLNT, DDIC_CUKY,
DDIC_CURR, DDIC_D16D, DDIC_D34D, DDIC_D16R, DDIC_D34R, DDIC_D16S, DDIC_D34S, DDIC_DATS,
DDIC_DAY, DDIC_DEC, DDIC_FLTP, DDIC_GUID, DDIC_INT1, DDIC_INT2, DDIC_INT4, DDIC_INT8,
DDIC_LANG, DDIC_LCHR, DDIC_MIN, DDIC_MON, DDIC_LRAW, DDIC_NUMC, DDIC_PREC, DDIC_QUAN,
DDIC_RAW, DDIC_RSTR, DDIC_SEC, DDIC_SRST, DDIC_SSTR, DDIC_STRG, DDIC_STXT, DDIC_TIMS,
DDIC_UNIT, DDIC_UTCM, DDIC_UTCL, DDIC_UTCS, DDIC_TEXT, DDIC_VARC, DDIC_WEEK.
GENERATED ALWAYS AS
Specifies the expression to generate the column value in runtime.
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 SAP HANA Database chooses the appropriate index considering the column
data types.
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 SAP HANA Database chooses the appropriate index considering the column
data types.
Creates a table that has the same definition as like_table_name. All the column definitions with constraints
and default values are copied from like_table_name. Data is filled from the specified table when WITH DATA
option is provided, however, the default value is WITH NO DATA.
78 2012-05-09
SAP HANA Database - SQL Reference Manual
Creates a table and fills it with the data computed by the <sql_select_query>. Only NOT NULL constraints are
copied by this clause. If column_names are specified, specified column_names override the column names
from <sql_select_query>. The default value is WITH DATA.
WITH [NO] DATA Specifies whether the data is copied from <sql_select_query> or <like_table_clause>.
LOGGING | NO LOGGING
LOGGING (default value) specifies that table logging is activated.
NO LOGGING specifies that logging is deactivated. A NO LOGGING table means that the definition of the
table is persistent and globally available, data is temporary and global.
RETENTION
Specifies the retention time in seconds of the column table created by NOLOGGING. After the specified
retention period has elapsed, the table will be dropped if used physical memory of the host reaches above
80%.
It is possible to determine the index servers on which the partitions are created. If you specify the LOCATION,
the partitions will be created on these instances using round robin. Duplicates in the list will be removed. If
you specify exactly the same number of instances as partitions in the partition specification, then each
partition will be assigned to the respective instance in the list. All index servers in the list have to belong to
the same instance.
If no locations are specified, the partitions will be created randomly. If the number of partitions matches the
number of servers - for example by using GET_NUM_SERVERS() - it is ensured that multiple CREATE TABLE
calls distribute the partitions in the same way. In case of a multi-level partitioning, this applies for the number
of partitions of the first level. This mechanism is useful if several tables are to be created which have a
semantic relation to each other.
AT LOCATION
A table can be created in the specified location with host:port. Location list can be specified when creating
partitioned tables that are distributed on multiple instances. When location list is provided without
<partition_clause>, the table is created on the first location specified.
If location information is 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.
Description
The CREATE TABLE statement creates a table. Tables are created without data except when
<as_table_subquery> or <like_table_clause> is used with the WITH DATA option.
Example
79 2012-05-09
SAP HANA Database - SQL Reference Manual
CREATE TRIGGER
Syntax
Syntax Elements
<proc_decl> ::=
<column_name> CONSTANT <proc_data_type> <opt_not_null> <opt_proc_default> '
;'
| <column_name> <proc_data_type> <opt_not_null> <opt_proc_default> ';'
<proc_handler_list> ::=
<proc_handler>
| <proc_handler_list> <proc_handler>
<proc_handler> ::=
DECLARE EXIT HANDLER FOR <proc_condition_value_list> <trigger_stmt>
<proc_condition_value_list>
::= <proc_condition_value>
| <proc_condition_value_list> ',' <proc_condition_value>
<proc_condition_value> ::=
<column_name>
| <sql_error_code>
| NOT_FOUND
<sql_error_code>
::= SQL_ERROR_CODE <int_const>
<trigger_stmt_list> ::=
<trigger_stmt>
| <trigger_stmt_list> <trigger_stmt>
<trigger_stmt> ::=
<proc_block>
| <proc_assign>
| <proc_if>
| <proc_loop>
| <proc_while>
| <proc_for>
| <proc_foreach>
| <proc_signal>
| <proc_resignal>
| <proc_sql>
COMMAND
AFTER
Trigger is executed after the subject table operation.
80 2012-05-09
SAP HANA Database - SQL Reference Manual
Trigger execution is triggered by the operation(INSERT or UPDATE or DELETE) on the subject table.
ROW
The trigger will be called in a row-wise fashion.
Currently statement-wise trigger calling is not supported.
proc_handler
Please refer exception handling for procedure.
trigger_stmt
Trigger_stmt is subset of proc_stmt. Please refer proc_stmt in procedure definition.
The syntax of trigger body complies with that of procedure, which are nested block(proc_block),
scalar parameter assign(proc_assign), if block(proc_if), loop block(proc_loop), for block(proc_for),
for each block(proc_foreach), exception signal(proc_signal), exception resignal(proc_resignal),
all sql statement (proc_sql).
Description
CREATE TRIGGER statement creates a trigger. A trigger is special kind of stored procedure that
automatically executes when an event occurs on a certain table.
CREATE TRIGGER command defines a set of statements that is executed when a given
operation(INSERT/UPDATE/DELETE)
takes place on a given object(subject table)
Only database users having the TRIGGER privilege for the given <table_name> are allowed to create a
trigger for that table.
Current trigger limitation is described below:
Descriptions to Monitoring view related to this command. System view TRIGGERS shows:
SCHEMA_NAME, TRIGGER_NAME, TRIGGER_OID, OWNER_NAME, OWNER_OID,
SUBJECT_TABLE_SCHEMA,
SUBJECT_TABLE_NAME, TRIGGER_ACTION_TIME, TRIGGER_EVENT, TRIGGERED_ACTION_LEVEL,
DEFINITION
Example
81 2012-05-09
SAP HANA Database - SQL Reference Manual
COMMAND
CREATE VIEW
Syntax
Syntax Elements
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 <subquery>.
Update operations on views are supported if the following conditions are met:
. Each column in the view must map to a column of a single table
. If a column in the base table has NOT NULL constraint without default value, the column must be included in
view columns to be an insertable view. Update operation on a view is allowed without this condition.
. Must not contain an aggregate or analytic function in a SELECT list for example, the followings are not
allowed:
. TOP, SET, DISTINCT operator in a SELECT list
. GROUP BY, ORDER BY clause
. Must not contain a subquery in a SELECT list
. Must not contain a sequence value(CURRVAL, NEXTVAL)
. Must not contain a column view as the base view
If base views or tables are updatable, a view on the base views or tables can be updatable if the above
conditions are met.
Example
Syntax
Description
82 2012-05-09
SAP HANA Database - SQL Reference Manual
The DROP AUDIT POLICY statement drops an audit policy. <policy_name> must specify an existing audit
policy.
Only database users having the system privilege AUDIT ADMIN are allowed to drop an audit policy. Each
database user having this privilege is allowed to drop any audit policy, no matter if he created it or not.
Even if an audit policy is dropped, it may happen, that the audit action specified in the dropped audit policy
will be audited further. This will happen, if another audit policy is enabled and specifies that audit action as
well.
To switch off an audit policy temporarily, it can be disabled and need not be dropped.
Only database users with system privilege CATALOG READ, DATA ADMIN or INIFILE ADMIN can see any info
out of the view M_INIFILE_CONTENTS. For other database users this view will be empty.
Example
CREATE AUDIT POLICY priv_audit AUDITING SUCCESSFUL GRANT PRIVILEGE, REVOKE PRIVILEG
E, GRANT ROLE, REVOKE ROLE LEVEL CRITICAL;
Syntax
Syntax Elements
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
Example
Syntax
Syntax Elements
Description
83 2012-05-09
SAP HANA Database - SQL Reference Manual
Example
DROP INDEX
Syntax
Syntax Elements
Description
Example
DROP SCHEMA
Syntax
Syntax Elements
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
Example
DROP SEQUENCE
Syntax
Syntax Elements
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.
84 2012-05-09
SAP HANA Database - SQL Reference Manual
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
Example
DROP SEQUENCE s;
DROP SYNONYM
Syntax
Syntax Elements
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. The optional PUBLIC element allows for the removal of
a public synonym.
Example
DROP TABLE
Syntax
Syntax Elements
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
85 2012-05-09
SAP HANA Database - SQL Reference Manual
Example
DROP TABLE A;
DROP TRIGGER
Syntax
Description
Example
DROP TRIGGER A;
DROP TYPE
Syntax
Syntax Elements
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
Example
DROP VIEW
Syntax
Syntax Elements
Default = RESTRICT
Cascaded drop drops the object and dependent objects. When CASCADE option is not specified, non-cascaded
86 2012-05-09
SAP HANA Database - SQL Reference Manual
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
Example
RENAME COLUMN
Syntax
Syntax Elements
Description
Example
RENAME INDEX
Syntax
Syntax Elements
Description
Example
RENAME TABLE
Syntax
87 2012-05-09
SAP HANA Database - SQL Reference Manual
Syntax Elements
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;
Syntax
Description
THREADS int_const
Specifies how many threads should be used in parallel for table conversion. The optimal value for number of
threads should set to the number of available CPU cores.
Default:
The default value is TABLE_CONVERSION_PARALLELISM which is the number of CPU cores specified in the
indexserver.ini file.
BATCH int_const
Specifies the number of rows inserted in batch, and the default value is 2,000,000 which is the optimal value.
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. However, the batch size more than 2,000,000 might cause high memory consumption, thus it is
not recommended to change this value.
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.
Configuration parameter
Example
TRUNCATE TABLE
Syntax
Description
Deletes all rows from a table. TRUNCATE is faster than DELETE FROM when deleting all records from a table,
but TRUNCATE cannot be rollbacked. To rollback from deleting records, "DELETE FROM <table_name>"
should be used.
HISTORY tables can also be truncated just like normal tables by executing this command. All parts of the
88 2012-05-09
SAP HANA Database - SQL Reference Manual
history table (main, delta, history main and history delta) will be deleted and the content will be lost.
DELETE
Syntax
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.
DELETE HISTORY
DELETE HISTORY will mark the chosen records of the history-part of the history-table for deletion. This means
that after executing this command, timetravel queries referencing the deleted rows may still see these rows.
In order to physically delete these rows the following statements have to be executed:
Please note that in some cases even the execution of the two statements above may not lead to physical
deletion.
To check whether the rows are physically deleted, the following statement can be helpful:
WITH PARAMETERS should be removed from the SQL Reference Manual, please check with developers
...
Example
EXPLAIN PLAN
EXPLAIN PLAN
Syntax
<statement_name> ::= string literal used to identify the name of a specific executi
on plan in the output table for a given SQL statement.
Description
The EXPLAIN PLAN statement is used to evaluate the execution plan that the SAP HANA Database follows to
execute an SQL statement. The result of the evaluation is stored into the EXPLAIN_PLAN_TABLE view for
later user examination. The SQL statement must be data manipulation statement, thus a schema definition
language statement cannot be used with the EXPLAIN PLAN command. You can obtain SQL plan from
EXPLAIN_PLAN_TABLE view. The view is shared by all users. Here is an example of reading an SQL plan from
the view.
89 2012-05-09
SAP HANA Database - SQL Reference Manual
Deta i l s of a n opera tor. Predi ca tes a nd expres s i ons us ed by the opera tor a re s hown
OPERATOR_DETAILS
here.
SCHEMA_NAME Na me of the s chema of the a cces s ed ta bl e.
TABLE_NAME Na me of the a cces s ed ta bl e.
Type of the a cces s ed ta bl e. One of the fol l owi ng opti ons : COLUMN TABLE, ROW TABLE,
TABLE_TYPE
MONITORING VIEW, JOIN VIEW, OLAP VIEW, CALCULATION VIEW a nd HIERARCHY VIEW.
TABLE_SIZE Es ti ma ted number of rows i n the a cces s ed ta bl e
OUTPUT_SIZE Es ti ma ted number of rows produced by a n opera tor
Es ti ma ted cos t of executi ng the s ubtree s ta rti ng from a n opera tor. Thi s va l ue i s onl y for
SUBTREE_COST
rel a ti ve compa ri s on.
OPERATOR_ID ID of a n opera tor uni que i n a pl a n. IDs a re i ntegers s ta rti ng from 1.
OPERATOR_ID of the pa rent of a n opera tor. The s ha pe of a n SQL pl a n i s a tree a nd the
PARENT_OPERATOR_ID topol ogy of the tree ca n be recons tructed us i ng OPERATOR_ID a nd
PARENT_OPERATOR_ID. PARENT_OPERATOR_ID of the root opera tor i s s hown a s NULL.
Level from the root opera tor. Level of the root opera tor i s 1, l evel of a chi l d of the root
LEVEL
opera tor i s 2 a nd s o on. Thi s ca n be uti l i zed for output i ndenta ti on.
Pos i ti on i n the pa rent opera tor. Pos i ti on of the fi rs t chi l d i s 1, pos i ti on of the s econd
POSITION
chi l d i s 2 a nd s o on.
HOST The hos tna me where a n opera tor wa s executed
PORT The TCP/IP port us ed to connect to the hos t
TIMESTAMP Da te a nd ti me when the EXPLAIN PLAN comma nd wa s executed.
CONNECTION_ID ID of the connecti on where the EXPLAIN PLAN comma nd wa s executed.
EXECUTION_ENGINE Type of the executi on engi ne where a n opera tor i s executed: COLUMN or ROW
OPERATOR_NAME column in EXPLAIN_PLAN_TABLE view: Table 2. List of column engine operators shown
in the OPERATOR_NAME column.
Opera tor
Des cri pti on
Na me
ROW SEARCH Sta rti ng pos i ti on of row engi ne opera tors . OPERATOR_DETAILS l i s ts projected col umns .
LIMIT Opera tor for l i mi ti ng number of output rows
ORDER BY Opera tor for s orti ng output rows
HAVING Opera tor for fi l teri ng wi th predi ca tes on top of groupi ng a nd a ggrega ti on
GROUP BY Opera tor for groupi ng a nd a ggrega ti on
MERGE
Opera tor for mergi ng the res ul ts of mul ti pl e pa ra l l el groupi ng a nd a ggrega ti ons
AGGREGATION
DISTINCT Opera tor for dupl i ca te el i mi na ti on
FILTER Opera tor for fi l teri ng wi th predi ca tes
UNION ALL Opera tor for produci ng uni on-a l l of i nput rel a ti ons
MATERIALIZED
Opera tor for produci ng uni on-a l l of i nput rel a ti ons wi th i ntermedi a te res ul t ma teri a l i za ti on
UNION ALL
Opera tor for joi ni ng i nput rel a ti ons through B-tree i ndex s ea rches . Joi n type s uffi x ca n be
BTREE INDEX
a dded. For exa mpl e, B-tree i ndex joi n for l eft outer joi n i s s hown a s BTREE INDEX JOIN (LEFT
JOIN
OUTER). Joi n wi thout joi n type s uffi x mea ns i nner joi n.
CPBTREE Opera tor for joi ni ng i nput rel a ti ons through CPB-tree i ndex s ea rches . Joi n type s uffi x ca n be
INDEX JOIN a dded.
Opera tor for joi ni ng i nput rel a ti ons through probi ng ha s h ta bl e bui l t on the fl y. Joi n type s uffi x
90 2012-05-09
SAP HANA Database - SQL Reference Manual
Opera tor for joi ni ng i nput rel a ti ons through probi ng ha s h ta bl e bui l t on the fl y. Joi n type s uffi x
HASH JOIN
ca n be a dded.
NESTED LOOP
Opera tor for joi ni ng i nput rel a ti ons through nes ted l oopi ng. Joi n type s uffi x ca n be a dded.
JOIN
MIXED
Opera tor for joi ni ng a n i nput rel a ti on of row s tore forma t wi th a col umn ta bl e wi thout forma t
INVERTED
convers i on us i ng a n i nverted i ndex of the col umn ta bl e. Joi n type s uffi x ca n be a dded.
INDEX JOIN
BTREE INDEX
Ta bl e a cces s through B-tree i ndex s ea rch
SEARCH
CPBTREE
Ta bl e a cces s through CPB-tree i ndex s ea rch
INDEX SEARCH
TABLE SCAN Ta bl e a cces s through s ca nni ng
AGGR TABLE Opera tor for a ggrega ti ng ba s e ta bl e di rectl y
MONITOR
Moni tori ng vi ew a cces s through s ea rch
SEARCH
MONITOR
Moni tori ng vi ew a cces s through s ca nni ng
SCAN
COLUMN SEARCH is a mark for the starting position of column engine operators and ROW SEARCH is a mark
for the starting position of row engine operators. In the example below, the intermediate result produced by
a COLUMN SEARCH (ID 10) is consumed by a ROW SEARCH (ID 7), and the intermediate result produced by
the ROW SEARCH (ID 7) is consumed by another COLUMN SEARCH (ID 1). The operators below the lowest
COLUMN SEARCH (ID 10) explain how the COLUMN SEARCH (ID 10) is executed. The operators between the
ROW SEARCH (ID 7) and the COLUMN SEARCH (ID 10) explain how the ROW SEARCH (ID 7) processes the
intermediate result produced by the COLUMN SEARCH (ID 10). The operators between the top COLUMN
SEARCH (ID 1) and the ROW SEARCH (ID 7) explain how the top COLUMN SEARCH (ID 1) processes the
intermediate result produced by the ROW SEARCH (ID 7). Table 4. Operators
Example of SQL plan explanation Here is an example of SQL plan explanation of a query. The query is from
TPC-H Benchmark. In the example, all tables are located on row store.
91 2012-05-09
SAP HANA Database - SQL Reference Manual
TABLE SCAN FILTER CONDITION: ORDERS.O_ORDERDATE < '1994-01-01' AND ORDERS.O_ORDERDATE >= '1993-10-01' ORDERS
INSERT
Syntax
Syntax Elements
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
92 2012-05-09
SAP HANA Database - SQL Reference Manual
LOAD
Syntax
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
MERGE DELTA
Syntax
Syntax Elements
Column store-specific options can be passed in using the "WITH PARAMETERS" clause.
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
'MEMORY_MERGE' = 'ON' | 'OFF' Database merges delta index in memory only, it will not be persisted.
Description
The MERGE DELTA statement merges deltas to main column store table. Since the column store is read
optimized and compressed, deltas are introduced to optimize insert or updates in the optimized way. All
insertions are passed to a delta. At a certain point in time, deltas can be merged into the main column table.
Deltas will be merged into main column table.
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;
REPLACE | UPSERT
Syntax
93 2012-05-09
SAP HANA Database - SQL Reference Manual
TH PRIMARY KEY ]
Syntax Elements
Description
The UPSERT or REPLACE statement without a subquery is similar to the UPDATE statement. The only
difference is when the WHERE clause predicate is false, it adds a new record to 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 or 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. Unless the table has a PRIMARY KEY, it becomes equivalent to
INSERT because there is no index to be used to determine whether or not a new row duplicates another.
The UPSERT or REPLACE statement with a 'WITH PRIMARY KEY' is same as one with the subquery. It works
based on the PRIMARY KEY.
Example
SELECT
Syntax
SELECT clause
The select clause specifies an output to be returned either to users or to an outer select clause if exists.
TOP
TOP can be used to return the first n records from the SQL statement.
select_list
The select list allows users to specify columns they want to retrieve from tables.
asterisk
Asterisk (*) can be used to select all columns from all tables or views listed in the FROM clause. If a schema
name and a table name or a table name is provided with asterisk(*), it is used to limit the scope of the result
set to the specified table.
column_alias
94 2012-05-09
SAP HANA Database - SQL Reference Manual
FROM clause
The from clause specifies inputs such as tables, views, and subqueries to be used in the select statement.
The join_type specifies the type of join being performed. LEFT indicates a left outer join, RIGHT indicates a
right outer join, and FULL indicates a full outer join. OUTER may or may not be used when an outer join is
being performed.
ON <predicate>
The ON clause specifies a join predicate.
CROSS JOIN
CROSS indicates that a cross join is being performed. A cross join produces the cross-product of two tables.
WHERE clause
The WHERE clause is used to specify predicates on inputs in the FROM clause, so users can retrieve the
desired records.
<condition> ::=
<condition> OR <condition>
| <condition> AND <condition>
| NOT <condition>
| ( <condition> )
| <predicate>
GROUP BY clause
<group_by_clause> ::=
95 2012-05-09
SAP HANA Database - SQL Reference Manual
( <grouping_expression_list> )
The GROUP BY clause is used to group the selected rows based on the values in the specified columns.
GROUPING SETS
Generates results with specified multiple groupings of data in a single statement. If no additional options such
as best and limit are set, the result is the same as UNION ALL of the aggregation of each specified group. For
example, "select col1, col2, col3, count(*) from t group by grouping sets ( (col1, col2), (col1, col3) )" is
equivalent to "select col1, col2, NULL, count(*) from t group by col1, col2 union all select col1, NULL, col3,
count(*) from t group by col1, col3". In the grouping-sets query each of (col1, col2) and (col1, col3) specifies
the grouping.
ROLLUP
Generates results with multiple levels of aggregation in a single statement. For example, "rollup (col1, col2,
col3)" is equivalent to "grouping sets ( (col1, col2, col3), (col1, col2), (col1) )" with an additional aggregation
without grouping. Thus, the number of grouping that result set contains is the number of columns in ROLLUP
list plus one for last aggregation if there is no additional option.
CUBE
Generates results with multiple levels of aggregations in a single statement. For example, "cube (col1, col2,
col3)" is equivalent to "grouping sets ( (col1, col2, col3), (col1, col2), (col1, col3), (col2, col3), (col1), (col2),
(col3) )" with an additional aggregation without grouping. Thus, the number of grouping that result set
contains is the same as all possible permutations of columns in the CUBE list plus one for the last aggregation
if there is no additional option.
BEST n
Returns only the top-n grouping sets sorted in descending order of the number of rows aggregated in each
grouping set. n can be any of zero, positive, and negative. When n is zero, it is the same with no BEST option.
When n is negative, it means sorting in ascending order.
WITH SUBTOTAL
Returns for each grouping set an additional subtotal of the returned results as controlled by OFFSET or LIMIT.
Unless OFFSET and LIMIT is set, the value is the same as the one for WITH TOTAL.
WITH BALANCE
Returns for each grouping set an additional aggregated value of the remaining values not returned as
controlled by OFFSET or LIMIT.
WITH TOTAL
Returns for each grouping set an additional row that is the aggregated total value. OFFSET and LIMIT options
cannot change this value.
TEXT_FILTER <filterspec>
Performs text filtering or highlighting on the grouping columns with <filterspec>, which is a single-quoted
string that follows the below syntax.
A filter defined by <filterspec> is a token/phrase or tokens/phrases connected with logical operators such as
AND, OR and NOT. A token matches a string that contains its corresponding word case-insensitively. For
example, 'ab' matches 'ab cd' and 'cd Ab' but does not match 'abcd' A token can contain wildcard characters '
that matches any string and ' that matches any character. Inside phrase, however, ' and ' do not work as
wildcard characters. With tokens and phrases logical operators AND, OR and NOT may be used together.
Since OR is the default operator, 'ab cd' is the same as 'ab OR cd' Note that logical operators should be
written in uppercase characters. As a kind of logical operators, prefixes '+' and '-' mean inclusion (AND) and
exclusion (AND NOT), respectively. For example, 'ab -cd' is the same as 'ab AND NOT cd' If there is no FILL UP
option, only grouped records that have matching values are returned. Note that a filter is applied to only the
96 2012-05-09
SAP HANA Database - SQL Reference Manual
FILL UP
Returns not only matched grouped records, but also non-matched ones. Function text_filter is useful to
identify which one is matched. Refer to 'Related Functions' below.
STRUCTURED RESULT
Returns results as temporary tables. For each grouping set a single temporary table is created. If WITH
OVERVIEW option is set, an additional temporary table is created for the overview of grouping sets. The
names of temporary tables are specified by PREFIX option.
WITH OVERVIEW
Returns the overview in a separate table additionally.
PREFIX value
Specifies a prefix for naming the temporary tables. It must start with "#", which means the temporary table.
If omitted, the default prefix is "#GN". Then, the concatenation of this prefix value and a nonnegative integer
number is used as the name of temporary tables; for example, "#GN0", "#GN1" and "#GN2". Refer to
'Return Format' below.
MULTIPLE RESULTSETS
Returns results in multiple result sets.
The projection clause must include all grouping columns used in the GROUPING SETS specification.
Related Functions
grouping_id ( <grouping_column1, ..., grouping_columnn> ) function returns an integer number to identify
which grouping set each grouped record belongs to. text_filter ( <grouping_column> ) function, which is used
with TEXT_FILTER, FILL UP, and SORT MATCHES TO TOP, displays matching values or NULL. NULL is displayed
for non-matching values when FILL UP option is specified.
Return Format
If neither STRUCTURED RESULT nor MULTIPLE RESULTSETS is set, the unioned result of all grouping sets is
returned, with NULL values filling up attributes that are not included in a specific grouping set. With
STRUCTURED RESULT, temporary tables are created additionally which can be queried using "SELECT *
FROM <table name>" in the same session. The name of the tables follows the form
<PREFIX>0: this table will contain the overview if WITH OVERVIEW is specified
<PREFIX>n: n-th grouping set subject to re-ordering by the BEST parameter
With MULTIPLE RESULTSETS, multiple result sets are returned. Grouped records for each grouping set
are in a single result set.
Example
Here is t1 table.
create column table t1 ( id int primary key, customer varchar(5), year int, product
varchar(5), sales int );
insert into t1 values(1, 'C1', 2009, 'P1', 100);
insert into t1 values(2, 'C1', 2009, 'P2', 200);
insert into t1 values(3, 'C1', 2010, 'P1', 50);
insert into t1 values(4, 'C1', 2010, 'P2', 150);
insert into t1 values(5, 'C2', 2009, 'P1', 200);
insert into t1 values(6, 'C2', 2009, 'P2', 300);
insert into t1 values(7, 'C2', 2010, 'P1', 100);
insert into t1 values(8, 'C2', 2010, 'P2', 150);
The following GROUPING SETS query is equivalent to the second below group-by query. Note that two groups
inside grouping sets in the first query are specified at each group by in the second query.
97 2012-05-09
SAP HANA Database - SQL Reference Manual
ROLLUP and CUBE are concise representations of grouping sets that are used frequently. The following
ROLLUP query is equivalent to the second below grouping-set query.
The following CUBE query is equivalent to the second below grouping-set query.
BEST 1 specifies that the following query returns only top-1 best group. In this example, 4 records exist for
(customer, year) group and 2 records exist for (product) group, so the former 4 records are returned. For
'BEST -1' instead of 'BEST 1', the latter 2 records are returned.
LIMIT 2 limits the number of records to maximum 2 for each group. For (customer, year) group, the number
of its records are 4, then only first 2 records will be returned. For (product) group, the number of its records
are 2, so all the records will be returned.
WITH SUBTOTAL produces additional one record for each group to display subtotal of returned records.
These subtotal records get NULL for each of customer, year, product columns and the sum of sum(sales)
values in the select list.
98 2012-05-09
SAP HANA Database - SQL Reference Manual
(customer, year),
(product)
);
WITH BALNACE produces additional one record for each group to display subtotal of unreturned records.
WITH TOTAL produces additional one record for each group to display total of all grouped records without
regard that the records are returned or not.
TEXT_FILTER allows users to retrieve the first column of each group with a given <filterspec>. The following
query will search columns ending with '2': customers for the first grouping set and products for the second
one. Only matched three records will be returned. TEXT_FILTER function in the select list is useful to see
which values are matched.
FILL UP is used to return both matched and non-matched records with <filterspec>. Therefore, the following
query returns six records whereas the previous query does three ones.
SORT MATCHES TO TOP is used to raise matched records up. For each grouping set, its grouped records will
be sorted.
STRUCTURED RESULT creates temporary tables: one for each grouping set and one more for the overview
table optionally. "#GN1" table is for (customer, year) grouping set and "#GN2" table is for (product) one.
Note that each table contains only related columns. That is, "#GN1" table does not have "product" column
and "#GN2" table does not have "customer" and "year" columns.
99 2012-05-09
SAP HANA Database - SQL Reference Manual
);
WITH OVERVIEW creates a temporary table "#GN0" for the overview table.
Users can change the names of temporary tables by using PREFIX keyword. Note that the names still must
start with '#', which is the prefix of temporary tables.
Temporary tables are dropped when the corresponding session is closed or when a user executes a drop
command. A list of temporary tables are seen in m_temporary_tables.
MULTIPLE RESULTSETS returns resultsets as multiple resultsets. In SAP HANA Studio, the following query will
return three resultsets: one is for the overview table and two are for grouping sets.
HAVING clause
The HAVING clause is used to select the specified groups that satisfy the predicates. If this clause is omitted,
all groups are selected.
SET OPERATORS
The set operators enable more than one select statements to be combined and only one result set is
returned.
UNION ALL
Selects all records from all select statements. Duplicates are not removed.
UNION [DISTINCT]
Selects all unique records from all select statements by removing duplicates found from different select
statements. UNION is the same as UNION DISTINCT.
100 2012-05-09
SAP HANA Database - SQL Reference Manual
INTERSECT [DISTINCT]
Returns all unique records that exist in all select statements in common.
EXCEPT [DISTINCT]
Returns all unique records from the first select statements after removing the duplicates in the following
select statements.
ORDER BY clause
The ORDER BY clause is used to sort records by expressions or positions. A position means the index of the
select list. For "select col1, col2 from t order by 2", 2 indicates col2 as the second expression used in the
select list. ASC is used to sort records in ascending order and DESC is used to sort records in descending order.
The default value is ASC.
LIMIT
FOR UPDATE
FOR UPDATE keywords lock the selected records so that other users cannot lock or change the records until
end of this transaction.
TIME TRAVEL
Keywords related wtih time travel can be used for statement-level time travel to go back to the snapshot
specified by commit_id or timestamp.
Example
UNLOAD
Syntax
UNLOAD <table_name>
Description
The UNLOAD statement unloads the column store table data from memory to disk.
Example
UNLOAD a_table;
UPDATE
Syntax
Syntax Elements
Description
101 2012-05-09
SAP HANA Database - SQL Reference Manual
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 expression is assigned to that column. If the WHERE clause is
omitted, then it updates all records of a table.
Example
Syntax
Description
Install a license key to the database instance. The license key (<license key>="">) is to be copied and pasted
from the license key file. The system privilege LICENSE ADMIN is required to execute this command.
Example
Syntax
Syntax Elements
The filename is 'indexserver.ini' in the case of row-store engine configuration. The filename used must be one
of the ini files located on the 'DEFAULT' layer. If the file selected by filename does not exist on the required
layer, the file will be created in the case of a SET command.
Sets the target layer for the configuration change. This parameter can be either 'SYSTEM' or 'HOST'. The
SYSTEM layer is the recommended layer for customer settings. The HOST layer should generally only be used
for minor configuration, for example parameters contained in daemon.ini.
If the layer parameter above is set to 'HOST', layer_name is used to target either a tenant name or a target
host name. For example, 'selxeon12' would target the 'selxeon12' host.
SET
The SET command updates the value of a key if the key already exists, or inserts it if required.
UNSET
The UNSET command removes a key and its associated value.
parameter_key_value_list ::=
102 2012-05-09
SAP HANA Database - SQL Reference Manual
{(<section_name>,<parameter_name>) = <parameter_value>},...
Specifies the section, key and value of the ini file parameter to be altered as follows:
WITH RECONFIGURE
When WITH RECONFIGURE is specified the configuration changes will be directly applied to the running SAP
HANA Database instance.
When WITH RECONFIGURE is not specified the new configuration will be written to the ini file, however the
new value is not applied to the current running system and will only be applied at the next startup of the
database. This means that there can be inconsistencies between the ini file contents and the actual
configuration value that the SAP HANA Database is currently using.
Description
Sets or removes configuration parameters in an ini file. Ini file configuration is used for the layered
configuration for DEFAULT, SYSTEM, HOST layers.
Note:
The DEFAULT layer configuration cannot be changed or removed using this command.
DEFAULT: /usr/sap/<SYSTEMNAME>/HDB<INSTANCENUMBER>/exe/config/indexserver.ini
SYSTEM: /usr/sap/<SYSTEMNAME>/SYS/global/hdb/custom/config/indexserver.ini
HOST: /usr/sap/<SYSTEMNAME>/HDB<INSTANCENUMBER>/<HOSTNAME>/indexserver.ini
The priority of the configuration layers is as follows: DEFAULT < SYSTEM < HOST.
This means that the layer that has the highest priority is the HOST layer, followed by the SYSTEM layer and
finally the DEFAULT layer. The configuration with the highest priority will be applied to the running
environment. If the highest priority level configuration is removed, then the configuration with the next
highest priority will be applied.
Currently available ini files are listed in the M_INIFILES system table and the current configuration is available
in M_INIFILE_CONTENTS system table.
Example
ALTER SYSTEM ALTER CONFIGURATION ('filename', 'layer') SET ('section1', 'key1') = '
value1', ('section2', 'key2') = 'value2', ... [WITH RECONFIGURE];
Syntax
Syntax Elements
103 2012-05-09
SAP HANA Database - SQL Reference Manual
If you have session administration privileges, you can change session variables of other sessions by specifying
the session_id parameter.
The desired value of a session variable. The maximum length of value is 512 characters.
Description
With this command you can set session variables of your own session by providing key and value pairs. Also if
you have session administration privileges, you can change session variables of other sessions by specifying
the session_id parameter.
Note:
There are several available read-only session variables that you cannot change with this command:
APPLICATION, APPLICATIONUSER, TRACEPROFILE.
Session variables can be retrieved using SESSION_CONTEXT function and unset using the UNSET [SESSION]
command.
Example
Syntax
Syntax Elements
Description
Cancels the currently executed operation by the specified session, however, the session is not disconnected.
Syntax
Description
Resets SQL Plan Cache. It removes all the plans that are not currently running.
Syntax
Syntax Elements
Description
104 2012-05-09
SAP HANA Database - SQL Reference Manual
Clears trace contents from trace files and all files that were opened by a service will be removed or reset to
size 0. On distributed system, the command will clear all traces on all hosts. It can clear different types of
files:
Type Files
ALERT *a l ert_*.trc
CLIENT l oca l cl i ent_*.trc
CRASHDUMP *.cra s hdump.*
EMERGENCYDUMP *.emergencydump.*
* a l l *.trc fi l es of s ervi ces l i s ted bel ow
INDEXSERVER,NAMESERVER,...,DAEMON open *.trc fi l es of a s i ngl e s ervi ce type
The trace files can be monitored using M_TRACEFILES and trace file contents can be monitored using
M_TRACEFILE_CONTENTS.
Syntax
Description
Syntax
Syntax Elements
Description
Syntax
Syntax Elements
Description
Disconnects the specified session from the database. The specified session will be disconnected but the
current operation will be continued until it is completed.
Syntax
Syntax Elements
105 2012-05-09
SAP HANA Database - SQL Reference Manual
Description
While logging is disabled, no log entries are persisted. Only the data area will be writtten, when a savepoint is
done. This can cause loss of committed transactions, when the indexserver terminated in the middle of a
load. In case of termination, you have to truncate and insert all data again.
After enable logging you have to perform a savepoint to be sure that all data is persisted and you have to
perfrom a data backup, else you can not recover this data.
You can also do this for single column tables with ALTER TABLE ... ENABLE/DISABLE DELTA LOG
Syntax
Syntax Elements
Description
Reduces data volume size to a N% of overload size; it works like defragmenting a hard disk, pages scattered
around the data volume will be moved to the front of the data volume and the free space at the end of the
data volume will be truncated.
Example
Syntax
Syntax Elements
Description
Example
Syntax
Description
Example
106 2012-05-09
SAP HANA Database - SQL Reference Manual
Syntax
Syntax Element
Description
Example
Syntax
Description
Deletes the trace files on specified hosts. When a service has a trace file open, then it cannot be deleted, so
"CLEAR" command should be used in that case.
Syntax
Syntax Element
Description
Example
Syntax
Description
Collect performance trace data and save the information into a file. The file is located on the server in the
trace directory. If no file name is specified, then 'perftrace.tpt' is used. The file can be downloaded from 'SAP
HANA Computing Studio'->Diagnosis-Files and then the performance trace can be loaded and analyzed with
HDBAdmin in any HDB instance.
Monitoring View
Example
107 2012-05-09
SAP HANA Database - SQL Reference Manual
Description
Executes a savepoint on the persistence manager. A savepoint is a point in time when a complete consistent
image of the database is persisted on the disk. The consistent image can be used to restart the database.
Example
Description
Example
Syntax
Syntax Element
Description
Start Performance Trace. It can be restricted to a specific SQL and application user. Optionally plan execution
and function profiler details can be recorded. If duration is specified it automatically stops after the specified
duration in seconds.
Example
Syntax
Description
Example
Syntax
Syntax Element
Description
STOP SERVICE stops the service. HOST and PORT information should be specified to stop a service.
108 2012-05-09
SAP HANA Database - SQL Reference Manual
STOP SERVICE with IMMEDIATE option kills the running service. HOST and PORT information should be
specified to kill a running service.
Example
Syntax
Description
Deletes all currently installed license keys. After using this command the system will be locked down
immediately and will require a new valid license key before it can be used further. The system privilege
LICENSE ADMIN is required to execute this command.
Example
CONNECT
Syntax
CONNECT <connect_option>
Syntax Elements
<connect_option> ::=
<user_name> PASSWORD <password>
| WITH SAML ASSERTION '<xml>'
Description
Connect to the database instance by specifying user_name and password or by specifying a SAML assertion.
Example
Syntax
Elements
<when>:
SET HISTORY SESSSION makes current session to see a previous version of history tables. User may specify the
version in COMMIT ID or UTCTIMESTAMP format, or may get back to current version by specify NOW. After
SET HISTORY SESSION command with a COMMIT ID or UTCTIMESTAMP is issued, current session sees an old
version of history tables, and cannot write anything to the system. If NOW option is given, current session
gets back to a normal session, and sees current version of history tables and be able to write to the system.
This command only works for history tables, and visibility on normal tables is not affected.
109 2012-05-09
SAP HANA Database - SQL Reference Manual
Example
SET SCHEMA
Syntax
Syntax Elements
Schema_name
schema name string
Description
You can change the current schema of the session. The current schema is used when database object names
such as table names are not prefixed with the schema name.
SET [SESSION]
Syntax
Syntax Elements
Key
key of a session variable
Value
value of a session variable
Description
You can set session variables by providing key and value pairs. With this command, session variables of the
current session can be set. If you have session administration privileges, you can change session variables of
other sessions by specifying the session ID using ALTER SYSTEM ALTER SESSION [session_id] SET command.
There are several available predefined session variables and they are APPLICATION, APPLICATIONUSER,
TRACEPROFILE.
The maximum length of key is 32 characters and the maximum length of value is 512 characters.
Session variables can be retrieved using SESSION_CONTEXT() function.
Session variables can be unset using UNSET command.
Example
UNSET [SESSION]
Syntax
Syntax Elements
Key
key of a session variable
Description
110 2012-05-09
SAP HANA Database - SQL Reference Manual
You can unset session variables by providing key. With this command, session variables of the current session
can be unset. If you have session administration privileges, you can change session variables of other sessions
by specifying the session ID using ALTER SYSTEM ALTER SESSION [session_id] UNSET command.
There are several available read-only session variables and they are APPLICATION, APPLICATIONUSER,
TRACEPROFILE.
Session variables can be retrieved using SESSION_CONTEXT() function.
Example
COMMIT
Syntax
COMMIT
Description
The system supports transactional consistency which guarantees current job to be either completely applied
to the system or disposed. If a user wants to apply current job to the system persistently, the user should
issue COMMIT command. If COMMIT command is issued and successfully processed, any change on the
system which current transaction has done is applied to the system and the change will be visible to other
jobs which will start in the future. The job which has already committed via COMMIT command cannot be
reverted. In a distributed system, standard 2-phase-commit protocol is complied. In the first phase,
transaction coordinator consults every participant whether if it is ready to commit, and sends the result to
the participants in the second phase. COMMIT command only works with 'autocommit' disabled session.
Example
COMMIT
LOCK TABLE
Syntax
Description
LOCK TABLE command explicitly tries to acquire an exclusive lock for a table. If NOWAIT option is specified, it
just tries to acquire lock for the table. If it fails to acquire lock with NOWAIT option specified, an error code is
returned, but current transaction is not rolled-back.
Example
ROLLBACK
Syntax
ROLLBACK
Description
The system supports transactional consistency which guarantees current job to be either completely applied
to the system or disposed. In the middle of a transaction, it can be explicitly reverted as it has not been
performed via ROLLBACK command. After ROLLBACK command is issued, any change on the system which
current transaction has done is completely reverted and current session is to be in an idle state. ROLLBACK
command only works with 'autocommit' disabled session.
111 2012-05-09
SAP HANA Database - SQL Reference Manual
Example
ROLLBACK
SET TRANSACTION
Syntax
Syntax Elements
READ COMMITTED
Default This isolation level corresponds to the statement level read consistency. With statement level
snapshot isolation, different statements in a transaction may see different snapshots of the system. The
statement in a transaction sees consistent snapshots 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.
READ WRITE
Default An SQL-transaction access mode may be explicitly set by a SET TRANSACTION statement; otherwise,
it is implicitly set to the default access mode.
READ ONLY
When read only access mode is set, then only read operation with SELECT statement is allowed and
exceptions will be thrown if any update is tried.
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.
Example
Description
112 2012-05-09
SAP HANA Database - SQL Reference Manual
The ALTER SAML PROVIDER statement changes the property of a SAML provider known to the SAP HANA
database. <saml_provider_name> has to be an existing SAML provider.
Only database users having the system privilege USER ADMIN are allowed to change a SAML provider.
The <subject_name> and the <issuer_distinguished_name> are the corresponding names provided in the
certificate of the SAML identity provider.
SAML_PROVIDERS: shows all SAML providers with their subject name and issuer_name.
Syntax
ALTER USER
Syntax
Syntax Elements
<alter_user_option> ::=
PASSWORD <password> [<user_parameter_option>]
| <user_parameter_option>
| IDENTIFIED EXTERNALLY AS <external_identity> [<user_parameter_option>]
| RESET CONNECT ATTEMPTS
| DROP CONNECT ATTEMPTS
| DISABLE PASSWORD LIFETIME
| FORCE PASSWORD CHANGE
| DEACTIVATE [USER NOW]
| ACTIVATE [USER NOW]
| DISABLE <authentication_mechanism>
| ENABLE <authentication_mechanism>
| ADD IDENTITY <provider_identity>...
| ADD IDENTITY <external_identity> FOR KERBEROS
| DROP IDENTITY <provider_info>...
| DROP IDENTITY FOR KERBEROS
<user_parameter_option> ::=
<set_user_parameters> [<clear_user_parameter_option>]
| <clear_user_parameter_option>
<clear_user_parameter_option> ::=
CLEAR PARAMETER CLIENT
| CLEAR ALL PARAMETERS
Description
The ALTER USER statement modifies the database user. <user_name> must specify an existing database
user.
Each user can do the ALTER USER statement for his own. But not all of the <alter_user_option>s can be
specified by the user himself. The ALTER USER statement for other users with all <alter_user_option>s can
only be done by users having the system privilege USER ADMIN.
Users created with PASSWORD cannot be changed to EXTERNALLY and vice versa: the users created with
EXTERNALLY cannot be changed to PASSWORD. But their <password> or their <external_identity> can be
changed.
You can change a user's password with this command. 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 ) have to be part of the password. The password for a user has
to be changed regularly according to the password policy specified for the database instance or changed by
the user himself when first connecting to the database instance.
You can change the external authentication. External users are authenticated using an external system, e.g.
a Kerberos system. Such users do not have a password, but , e.g. a Kerberos principal name. For detailed
information about external identities, contact your domain administrator.
113 2012-05-09
SAP HANA Database - SQL Reference Manual
<user_parameter_option> can be used to set, change or clean the user parameter CLIENT. When using
reports this user parameter CLIENT can be used to restrict the access rights of user <user_name> to info
concerning the specified client.
The <user_parameter_option> can not be specified by the user himself.
Information on invalid connect attempts having happened can be checked in system view
INVALID_CONNECT_ATTEMPTS. With the command
ALTER USER <user_name> DROP CONNECT ATTEMPTS
a user with system privilege USER ADMIN or the user himself can delete the information of invalid connect
attempts having happened.
Configuration Parameter
Conguration parameters concerning the password can be checked with the monitoring view
M_PASSWORD_POLICY. These parameter are stored in indexserver.ini, section 'password policy'.
The description of the parameters concerned can be found in SAP HANA Security Guide, Appendix, Password
Policy Parameters.
USERS: shows all users, their creator, creation date and some info about their current states.
USER_PARAMETERS: shows the defined user_parameters; currently only CLIENT is available.
INVALID_CONNECT_ATTEMPTS: shows how many invalid connect attempts were made for each user.
LAST_USED_PASSWORDS: shows info about dates of last password-changes per user.
M_PASSWORD_POLICY: shows configuration parameters describing the allowed layout of the password and
its lifetimes.
Example
A user with user_name NEW_USER had been created before with the possibility to connect using the given
password and with an assertion of the existing SAML provider OUR_PROVIDER. The <mapped_user_name>
was set to ANY as the assertion will provide the database user name.
CREATE USER new_user PASSWORD Password1 WITH IDENTITY ANY FOR SAML PROVIDER OUR_PRO
VIDER;
Now this user shall be forced to change his password. And to force him really hard, his possibility to connect
using SAML is disabled.
114 2012-05-09
SAP HANA Database - SQL Reference Manual
CREATE ROLE
Syntax
Description
A role is a named collection of privileges and can be granted to either a user or a role. 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.
Every user is allowed to grant privileges to an existing role, but only users having system privilege ROLE
ADMIN are allowed to grant roles to roles and users.
There are 4 roles, which are delivered with the SAP HANA database:
PUBLIC
Every database user has been granted this role implicitly.
This role contains read-only access to system views, monitoring views and execute privilege for some
procedures. These privileges can not be revoked.
This role can be granted further privileges which can be revoked afterwards.
MODELING
This role contains all privileges required for using the information modeler in the SAP HANA studio.
CONTENT_ADMIN
This role contains the same privileges as the MODELING role, but with the extension that this role is allowed
to grant these privileges to other users. In addition, it contains the repository privileges to work with
imported objects.
MONITORING
This role contains privileges for full read-only access to all meta data, the current system status in system and
monitoring views, and the data of the statistics server.
Example
Description
The CREATE SAML PROVIDER statement defines a SAML provider known to the SAP HANA database.
<saml_provider_name> has to be different to any existing SAML provider.
Only database users having the system privilege USER ADMIN are allowed to create a SAML provider. Each
user having this privilege is allowed to drop any SAML provider.
An existing SAML provider is needed to be able to specify SAML connection possibility for users.
The <subject_name> and the <issuer_distinguished_name> are the corresponding names provided in the
certificate of the SAML identity provider.
115 2012-05-09
SAP HANA Database - SQL Reference Manual
SAML_PROVIDERS: shows all SAML providers with their subject name and issuer_name.
Syntax
CREATE USER
Syntax
Syntax Elements
<provider_identity> ::=
<mapped_user_name> FOR SAML PROVIDER <provider_name>
| <external_identity> FOR KERBEROS
<mapped_user_name> ::=
ANY
| <string_literal>
<set_user_parameters> ::=
SET PARAMETER CLIENT = <string_literal>
Description
Users in the database can be authenticated by different mechanism, the internal authentication mechanism
using password and by external mechanism, like Kerberos or SAML. One user can be authenticated by more
than one mechanism at one time, but only one password and one external_identity can be valid at one time.
In opposite to this, more than one <provider_identity> can exist for one user at one time. At least one
authentication mechanism has to be specified to allow the user to connect and work with the database
instance.
For compatibility reasons the syntax IDENTIFIED EXTERNALLY AS <external_identity> will stay alive and do
the same as the syntax <external_identity> FOR KERBEROS.
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 )
have to be part of the password. The password for a user has to be changed regularly according to the
password policy specified for the database instance.
The password provided during CREATE USER command will be taken as provided, whereas the <user_name>
will be changed to upper_case as every <simple_identifier>.
External users are authenticated using an external system, e.g. a Kerberos system. Such users do not have a
password, but , e.g. a Kerberos principal name. For detailed information about external identities, contact
your domain administrator.
If ANY is given as mapped user name, the SAML assertion will contain the name of the database user, the
assertion is valid for.
<provider_name> must specify an existing SAML provider.
<set_user_parameters> can be used to set the user parameter CLIENT when a user is created in the
database. When using reports this user parameter CLIENT can be used to restrict the access rights of user
<user_name> to info concerning the specified client.
For each database user a schema with the user's name is created implicitly. This can not be dropped
explicitly. It will be dropped when the user is dropped. The database user owns that schema and uses it as his
default schema, when he does not specify a schema name explicitly.
116 2012-05-09
SAP HANA Database - SQL Reference Manual
Configuration Parameter
Conguration parameters concerning the password can be checked with the monitoring view
M_PASSWORD_POLICY. These parameter are stored in indexserver.ini, section 'password policy'.
The description of the parameters concerned can be found in SAP HANA Security Guide, Appendix, Password
Policy Parameters.
USERS: shows all users, their creator, creation date and some info about their current states.
USER_PARAMETERS: shows the defined user_parameters; currently only CLIENT is available.
INVALID_CONNECT_ATTEMPTS: shows how many invalid connect attempts were made for each user.
LAST_USED_PASSWORDS: shows info about dates of last password-changes per user.
M_PASSWORD_POLICY: shows configuration parameters describing the allowed layout of the password and
its lifetimes.
SAML_PROVIDERS: shows the existing SAML provider SAML_USER_MAPPING: shows the user's mapping
names for each SAML provider
Example
A user with user_name NEW_USER shall be created with the possibility to connect using the given password
and with an assertion of the existing SAML provider OUR_PROVIDER. The <mapped_user_name> is set to
ANY as the assertion will provide the database user name.
CREATE USER new_user PASSWORD Password1 WITH IDENTITY ANY FOR SAML PROVIDER OUR_PRO
VIDER;
DROP ROLE
Syntax
Description
The DROP ROLE statement drops a role. <drop_name> must specify an existing role.
Only database users having the system privilege ROLE ADMIN are allowed to drop a role. Each user having
this privilege is allowed to drop any role. Only those roles which are delivered with the SAP HANA database
can not be dropped: PUBLIC, CONTENT_ADMIN, MODELING and MONITORING.
If a role was granted to a user or role, it is revoked when the role is dropped. Revoking a role may lead to
making some views inaccessible or making procedures not executable any more. This will occur if a view or
procedures depends on any privilege that the role had.
Example
Description
The DROP SAML PROVIDER statement drops the specified SAML provider. <saml_provider_name> has to be
an existing SAML provider. If the SAML provider specified is used by a SAP HANA database user, the SAML
provider cannot be dropped.
Only database users having the system privilege USER ADMIN are allowed to drop a SAML provider.
117 2012-05-09
SAP HANA Database - SQL Reference Manual
SAML_PROVIDERS: shows all SAML providers with their subject name and issuer_name.
Syntax
DROP USER
Syntax
Syntax Elements
Default = RESTRICT
Description
The DROP USER statement deletes a database user. <user_name> must specify an existing database user.
Only database users having the system privilege USER ADMIN are allowed to drop a database user. Each user
having this privilege is allowed to drop any user. Only those users which are delivered with the SAP HANA
database can not be dropped: SYS, SYSTEM, _SYS_REPO, _SYS_STATISTICS.
If the <drop_option> RESTRICT is specified implicitly or explicitly then the user will not be dropped in case he
is the owner of any other object than the schema with his name and other schemas created by him or in case
there is an object stored in one of his schemas which was not created by him.
If the <drop_option> CASCADE is specified, the schema with the user's name and the schemas belonging to
the user, together with all objects stored in them (even if they are created by other 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. Even public synonyms owned by the deleted user are deleted.
Privileges on deleted objects are revoked. Privileges granted by the deleted user are revoked. Revoke
privileges may cause further revokes if they had been granted further.
Users created by the deleted user and roles created by him are not deleted.
Audit policies created by the deleted user are not deleted.
* The deletion of objects may influence all of the system views describing objects, like TABLES, VIEWS,
PROCEDURES, ... .
The deletion of objects may influence the view describing privileges like GRANTED_PRIVILEGES and all of the
monitoring views like M_RS_TABLES, M_TABLE_LOCATIONS, ...
Example
A user with user_name NEW_USER was created before and will now be dropped, together with all of his
objects;
GRANT
Syntax
118 2012-05-09
SAP HANA Database - SQL Reference Manual
Syntax Elements
\anchor system_privilege
<system_privilege> ::=
AUDIT ADMIN | BACKUP ADMIN
| CATALOG READ | CREATE SCENARIO
| CREATE SCHEMA | CREATE STRUCTURED PRIVILEGE
| DATA ADMIN | EXPORT
| IMPORT | INIFILE ADMIN
| LICENSE ADMIN | LOG ADMIN
| MONITOR ADMIN | OPTIMIZER ADMIN
| RESOURCE ADMIN | ROLE ADMIN
| SAVEPOINT ADMIN | SCENARIO ADMIN
| SERVICE ADMIN | SESSION ADMIN
| STRUCTUREDPRIVILEGE ADMIN | TRACE ADMIN
| USER ADMIN | VERSION ADMIN
| <identifier>.<identifier>
<schema_privilege> ::=
CREATE ANY
| DEBUG
| DELETE
| DROP
| EXECUTE
| INDEX
| INSERT
| SELECT
| TRIGGER
| UPDATE
<object_privilege> ::=
ALL PRIVILEGES
| ALTER
| DEBUG
| DELETE
| DROP
| EXECUTE
| INDEX
| INSERT
| SELECT
| TRIGGER
| UPDATE
| <identifier>.<identifier>
<grantee> :: =
<user_name>
| <role_name>
<object_name> ::=
<table_name>
| <synonym_name>
| <view_name>
| <procedure_name>
| <sequence_name>
Description
GRANT is used to grant privileges and structured privileges to users and roles. GRANT is also used to grant
roles to users and other roles.
The specified users, roles, objects, and structured privileges have to exist before they can be used in the
GRANT command.
Only users having a privilege and being allowed to grant that privilege any further can grant a privilege. Each
user having ROLE ADMIN system privilege is allowed to grant roles to other roles and users.
Although user SYSTEM has many privileges, he is not able to select or change data in other user's tables if he
is not granted the privilege to do so explicitly.
User SYSTEM and all other users do have the privilege to create objects in their own default schema, which
has the same name as the user itself.
For tables created by themselves, users have all privileges and may grant all of them to users and roles.
119 2012-05-09
SAP HANA Database - SQL Reference Manual
For other objects which are dependent on objects like views being dependent on tables, it may happen, that
even the owner of the dependent object does not have all privileges if he does not have them on the
underlying objects. Or it may happen, that he has privileges, but is not allowed to grant them any further.
Then he cannot grant those privileges.
WITH ADMIN OPTION and WITH GRANT OPTION specifies that the granted privileges can be granted further
by the specified user or by those user having the specified role.
The grantee can be a user or a role. In case a privilege or role is granted to a role, then all user being granted
that role, will have the specified privilege or role.
System privileges are used to restrict administrative tasks. The following system privileges are defined:
AUDIT ADMIN
This privilege controls the execution of the following auditing-related commands: CREATE AUDIT POLICY,
DROP AUDIT POLICY and ALTER AUDIT POLICY.
BACKUP ADMIN
This privilege authorizes the ALTER SYSTEM BACKUP command to define and initiate a backup process or to
perform a recovery process.
CATALOG READ
This privilege authorizes all users to have unfiltered read-only access to all system and monitoring views.
Normally, the content of those views is filtered based on the privileges of the accessing user. The CATALOG
READ privilege enables users to have read-only access to the full content of all system and monitoring views.
CREATE SCENARIO
This privilege controls the creation of calculation scenarios and cubes (calculation database).
CREATE SCHEMA
This privilege authorizes the creation of database schemas using the CREATE SCHEMA command. Each user
owns one schema. With this privilege he is allowed to create further ones.
DATA ADMIN
This powerful privilege authorizes to read all data in the system and monitoring views as well as execute all
DDL (Data Definition Language) and only DDL commands in the SAP HANA database. This means, that
a user having this privilege can not select or change data stored in other user's tables, but can modify the
table definition or even drop the table.
EXPORT
This privilege authorizes the export activity in the database via the EXPORT TABLE commands. Note that,
beside this privilege, the user still needs the SELECT privilege on the source tables to be exported.
IMPORT
This privilege authorizes the import activity in the database using the IMPORT commands. Note that, beside
this privilege, the user still needs the INSERT privilege on the target tables to be imported.
INIFILE ADMIN
This privilege authorizes different methods to change system settings.
LICENSE ADMIN
This privilege authorizes the SET SYSTEM LICENSE command install a new license.
LOG ADMIN
This privilege authorizes the ALTER SYSTEM LOGGING [ON|OFF] commands to enable or disable the log flush
mechanism.
MONITOR ADMIN
This privilege authorizes monitoring all activities done using the various ALTER SYSTEM MONITOR commands
as well as the ALTER SYSTEM SET MONITOR LEVEL <level> command.
OPTIMIZER ADMIN
This privilege authorizes the ALTER SYSTEM commands concerning SQL PLAN CACHE and ALTER SYSTEM
UPDATE STATISTICS commands, which influence the behavior of the query optimizer.
120 2012-05-09
SAP HANA Database - SQL Reference Manual
RESOURCE ADMIN
This privilege authorizes different commands concerning resources, like ALTER SYSTEM RECLAIM
DATAVOLUME and ALTER SYSTEM RESET MONITORING VIEW and it authorizes many of the commands in
the Management Console.
ROLE ADMIN
This privilege authorizes the creation and deletion of roles using the CREATE ROLE and DROP ROLE
commands. It also authorizes the granting and revocation of roles using the GRANT and REVOKE commands.
SAVEPOINT ADMIN
This privilege authorizes the execution of a savepoint process using the ALTER SYSTEM SAVEPOINT
command.
SCENARIO ADMIN
This privilege authorizes all calculation scenario-related activities (including creation).
SERVICE ADMIN
This privilege authorizes the ALTER SYSTEM [START|CANCEL|RECONFIGURE] commands, intended for
administering system services of the database.
SESSION ADMIN
This privilege authorizes the ALTER SYSTEM commands concerning sessions to stop or disconnect a user
session or to change session variables.
STRUCTUREDPRIVILEGE ADMIN
This privilege authorizes the creation, reactivation, and dropping of structured privileges.
TRACE ADMIN
This privilege authorizes the ALTER SYSTEM [CLEAR|REMOVE] TRACES commands for operations on database
trace files.
USER ADMIN
This privilege authorizes the creation and changing of users using the CREATE USER, ALTER USER, and DROP
USER commands.
VERSION ADMIN
This privilege authorizes the ALTER SYSTEM RECLAIM VERSION SPACE command of the multi-version
concurrency control (MVCC) mechanism.
<identifier>.<identifier>
Components of the SAP HANA database may create privileges for their own needs. Those use the component-
name as first identifier of the system privilege and the component-privilege-name as the second identifier.
Currently, the repository uses this feature. For description of the privileges named REPO.<identifier>, please
see the manual of the repository.
Schema privileges are used to restrict the access and modifications on a schema and the objects stored in
this schema. The following schema privileges are defined:
CREATE ANY
This privilege allows the creation of all kinds of objects, in particular, tables, views, sequences, synonyms, SQL
Script functions, or database procedures in a schema.
Object privileges are used to restrict the access and modifications on database objects like tables, views,
sequences, procedures and the like. Not all of these privileges are applicable to all kinds of database objects.
For object types allowing which privilege, see table below.
The following object privileges are defined:
ALL PRIVILEGES
This privilege is a collection of all DDL (Data Definition Language) and DML (Data Manipulation Language)
privileges that on the one hand, the grantor currently has and is allowed to grant further and on the other
hand, can be granted on this particular object. This collection is dynamically evaluated for the given grantor
and object. ALL PRIVILEGES is applicable to a table or view.
121 2012-05-09
SAP HANA Database - SQL Reference Manual
ALTER
This DDL privilege authorizes the ALTER command for that object.
DEBUG
This DML privilege authorizes the debug-functionality for that procedure or calculation view or for the
procedures or calculation views in that schema.
DELETE
This DML privilege authorizes the DELETE and TRUNCATE commands for that object.
DROP
This DDL privilege authorizes the DROP commands for that object.
EXECUTE
This DML privilege authorizes the execution of a SQL Script function or a database procedure using the CALLS
or CALL command, respectively.
INDEX
This DDL privilege authorizes the creation, changing, or dropping of indexes for that object.
INSERT
This DML privilege authorizes the INSERT command for that object. The INSERT and the UPDATE privilege
together are needed for one object to allow the REPLACE and UPSERT command for that object.
SELECT
This DML privilege authorizes the SELECT command for that object or the usage of the sequence,
respectively.
TRIGGER
This DDL privilege authorizes the CREATE TRIGGER / DROP TRIGGER command for the specified table or the
tables in the specified schema.
UPDATE
This DML privilege authorizes the UPDATE command for that object. The INSERT and the UPDATE privilege
together are needed for one object to allow the REPLACE and UPSERT command for that object.
<identifier>.<identifier>
Components of the SAP HANA database may create privileges for their own needs. Those use the component-
name as first identifier of the privilege name and the component-privilege-name as the second identifier.
Currently, the repository uses this feature. For description of the privileges named REPO.<identifier>, please
see the manual of the repository.
DELETE, INSERT and UPDATE on views are valid for updatable views only, meaning such views complying to
some restrictions as there are: no join included, no UNION included, no aggregation and some further
restrictions.
DEBUG is only valid for calculation views, not for other kinds of views.
For synonyms those restrictions are valid, which are valid for the object this synonym stands for.
122 2012-05-09
SAP HANA Database - SQL Reference Manual
A role is a named collection of privileges and can be granted to either a user or a role.
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.
When granting roles to roles, a tree of roles can be build. When granting one role (R) to a role or user (G), G
will have all privileges directly granted to R and all privileges granted to roles which had been granted to R.
USERS: shows all users, their creator, creation date and some info about their current states.
ROLES: shows all roles, their creator and creation date.
GRANTED_ROLES: shows which roles are granted to which user or role.
GRANTED_PRIVILEGES: shows which privileges are granted to which user or role.
Example
Assuming a user owning schema myschema is connected. He has the privilege to create roles and users.
He creates one new role and one user. Then he grants the privilege to SELECT on any object in his schema to
this new role. Additionally he grants the privilege to INSERT into one specific table to this new role.
Afterwards he grants this role to that new user.
The currently connected user has the privilege TRACE ADMIN with the possibility to grant further. He grants
it to the new user with the option to let him grant it further. At least the user worker is granted the privilege
to DELETE in table myschema.work_done with the option to grant this privilege further.
REVOKE
Syntax
Syntax Elements
Description
The REVOKE statement revokes the specified roles or structured privileges or the privileges for the specified
objects from the specified users or roles.
Only users having granted a privilege can revoke that privilege. This is true even for users having ROLE
ADMIN and the revoke of roles.
User SYSTEM has at least all system privileges and the role PUBLIC. All other users have the role PUBLIC.
These privileges and roles can not be revoked from them.
If a user was granted a role, it is not possible to revoke some of the privileges belonging to that role. In this
case, the whole role has to be revoked and those privileges needed by that user granted to him.
Revoking a privilege or role may lead to making some views inaccessible or making procedures not
executable any more. This will occur if a view or procedures depends on the privilege revoked or on one of
the privileges the role had.
123 2012-05-09
SAP HANA Database - SQL Reference Manual
Revoking a privilege which had been granted with WITH GRANT OPTION or with WITH ADMIN OPTION will
result in revoking that privilege not only from the user specified in the command, but from all the users and
roles having been granted that privilege by this user directly and indirectly.
As privileges can be granted to one user or role by different users, revoking of this privilege by one user does
not necessarily mean, that this user will loose that privilege. For the description of syntax elements and
privileges, please refer to GRANT.
USERS: shows all users, their creator, creation date and some info about their current states.
ROLES: shows all roles, their creator and creation date.
GRANTED_ROLES: shows which roles are granted to which user or role.
GRANTED_PRIVILEGES: shows which privileges are granted to which user or role.
Example
Assuming that the following statements had been executed by the user currently connected.
The user having granted privileges is allowed to revoke those privileges. He revokes the privilege from the
role and therefore implicitly revokes it from all users being granted that role. Additionally the user worker
should not have the privilege TRACE ADMIN any more. It is revoked causing the revocation to occur for all
the users, worker had granted this privilege to.
EXPORT
Syntax
Syntax Elements
WITH <export_option_list>:
Description
The EXPORT command exports tables, views, column views, synonyms, sequences, or procedures in the
specified format as BINARY or CSV. Data for temporary tables and no logging tables cannot be exported
using EXPORT.
REPLACE With REPLACE option, previously exported data will be removed and newly exported data will be
124 2012-05-09
SAP HANA Database - SQL Reference Manual
saved. If REPLACE option is not specified, an error will be thrown if there exists a previously exported data
already in the specified directory.
CATALOG ONLY With CATALOG ONLY option, only database catalog will be exported without data.
NO DEPENDENCIES With NO DEPENDENCIES option, it will not export underlying objects of an object to be
exported.
SCRAMBLE Export in CSV format has an additional option to scramble sensitive customer data using
SCRAMBLE [BY '<password>']. When the optional password is not specified, a default scramble password is
used. Only character string data can be scrambled. When imported, scrambled data will be imported as
scrambled so that end users cannot read the data and it is not possible to unscramble the data.
THREADS Indicates the number of threads that can be used for concurrent export.
To export all tables you should use the keyword ALL. If you want to export/import tables of a specific schema,
you should use the schema name with the asterisk:
You can monitor the progress of the export using M_EXPORT_BINARY_STATUS system views.
You can abort the export session using the connection ID from the corresponding view in the following
command:
The detailed result of the export is stored in session-local temporary tables. #EXPORT_BINARY_RESULT.
Example
IMPORT
Syntax
Syntax Elements
WITH <import_option_list>:
Description
The IMPORT statement imports tables, views, column views, synonyms, sequences, or procedures. Data for
temporary tables and no logging tables cannot be imported using IMPORT command.
REPLACE With REPLACE option, the specified table will be dropped and created and data will be imported. If
REPLACE option is not specified, an error will be thrown if there exists a table with the same name in the
same schema.
CATALOG ONLY With CATALOG ONLY option, only database catalog will be imported without data.
NO DEPENDENCIES With NO DEPENDENCIES option, it will not import underlying objects of an object to be
imported.
THREADS Indicates the number of threads that can be used for concurrent import.
To import all tables you should use the keyword ALL. If you want to import tables of a specific schema, you
should use the schema name with the asterisk:
125 2012-05-09
SAP HANA Database - SQL Reference Manual
You can monitor the progress of the import using M_IMPORT_BINARY_STATUS system views.
Also, you can abort the import session using the connection ID from the corresponding view in the following
command:
The detailed result of the import is stored in session-local temporary tables. #IMPORT_BINARY_RESULT.
Example
IMPORT FROM
Syntax
Syntax Elements
WITH <import_from_option_list>:
Description
The IMPORT FROM statements imports external data from a csv file into an existing table.
THREADS Indicates the number of threads that can be used for concurrent import. Default value is 1 and
maximum allowed value is 256.
THREADS and BATCH can be used to achieve high loading performance by enabling parallel loading and
committing many records at once. In general, for column tables, a good setting is to use 10 parallel loading
threads, with a commit frequency of 10.000 records or greater.
TABLE LOCK Locks table for fast import into column store tables. If NO TYPE CHECK option is specified, then
the record is inserted without checking the type of each field.
COLUMN LIST IN FIRST ROW Indicates the column list that is in the first row of CSV file.
RECORD DELIMITED BY '<string>' Indicates the record delimiter of the CSV file
FIELD DELIMITED BY '<string>' Indicates the field delimiter of the CSV file
126 2012-05-09
SAP HANA Database - SQL Reference Manual
DATE FORMAT '<string>' Indicates the string of date format. If there is date type in CSV file, it will use the
specified format for date type field.
TIME FORMAT '<string>' Indicates the string of time format. If there is time type in CSV file, it will use the
specified format for time type field.
TIMESTAMP FORMAT '<string>' Indicates the string of timestamp format. If there is timestamp type in CSV
file, it will use the specified format for timestamp type field.
Example
IMPORT FROM CSV FILE '/data/data.csv' INTO "MYSCHEMA"."MYTABLE" WITH RECORD DELIMIT
ED BY '\n' FIELD DELIMITED BY ','
127 2012-05-09