Upload
sowmitri69
View
232
Download
1
Embed Size (px)
Citation preview
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 1/193
SAP HANA Database - SQL Reference ManualSAP HANA Appliance Software SPS 05, Revision 45
Target Audience
Consultants
Administrators
SAP Hardware Partner
Others
1 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 2/193
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 3/193
BlackBerry Torch, BlackBerry Storm, BlackBerry Storm2, BlackBerry PlayBook,
and BlackBerry App World are trademarks or registered trademarks of Research
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.
INTERMEC is a registered trademark of Intermec Technologies Corporation.
Wi-Fi is a registered trademark of Wi-Fi Alliance.
Bluetooth is a registered trademark of Bluetooth SIG Inc.
Motorola is a registered trademark of Motorola Trademark Holdings LLC.
Computop is a registered trademark of Computop Wirtschaftsinformatik GmbH.
SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP
BusinessObjects Explorer, StreamWork, SAP HANA, and other SAP products
and services mentioned herein as well as their respective logos are trademarks
or registered trademarks of SAP AG in Germany and other countries.
Business Objects and the Business Objects logo, BusinessObjects, Crystal
Reports, Crystal Decisions, Web Intelligence, Xcelsius, and other Business
Objects products and services mentioned herein as well as their respective
logos are trademarks or registered trademarks of Business Objects Software
Ltd. Business Objects is an SAP company.
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-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 4/193
489
10
10
10
11
11
11
11
11
11
11
12
1313
1313
14
14
14
15
15
16
17
17
18
18
20
2222
22
22
22
22
22
23
25
25
25
25
26
26
26
26
28
28
28
28
28
30
30
3030
30
30
31
31
31
Table of Content
Table of ContentSAP HANA Database - SQL Reference Manual
SQL Reference Manua l
Notation
Symbols used in BNF
BNF Lowest Terms Representations
Introduction
SQL
Supported Languages and Code Pages
Comment
Identifiers
Single Quotation Mark
Double Quotation Mark
SQL Reserved Words
Data TypesClassification of Data Types
Datetime TypesDate Formats
Time Formats
Timestamp Formats
Additional Formats
Supported Functions for Date/Time types
Numeric Types
Character String Ty pes
Binary Ty pes
Large Object (LOB) Types
Mapping between SQL Data Type and Column Store Data Type
Data Type Conversion
Typed Constant
PredicatesComparison Predicates
Range Predicate
In Predicate
Exists Predicate
LIKE Predicate
NULL Predicate
CONTAINS Predicate
Operators
Unary and Binary Operators
Operator Precedence
Arithmetic Operators
String Operators
Comparsion Operators
Logical Operators
Set Operators
Expressions
Case Expressions
Function Expressions
Aggregate Expressions
Subqueries in Expressions
SQL Functions
Introduction
Data Type Conversion FunctionsCAST
TO_ALPHANUM
TO_BIGINT
TO_BINARY
TO_BLOB
TO_CLOB
Table of Content
4 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 5/193
31
32
32
32
33
33
33
33
34
34
34
34
35
35
35
36
3636
36
36
37
37
37
3738
38
38
38
39
39
39
39
40
40
40
40
41
41
41
42
42
42
42
43
43
43
43
44
4444
44
44
45
45
45
45
46
46
4647
47
47
47
48
48
48
48
49
49
49
50
50
50
50
51
51
TO_DATE
TO_DATS
TO_DECIMAL
TO_DOUBLE
TO_INT
TO_INTEGER
TO_NCLOB
TO_NVARCHAR
TO_REAL
TO_SECONDDATE
TO_SMALLDECIMAL
TO_SMALLINT
TO_TIME
TO_TIMESTAMP
TO_TINYINT
TO_VARCHAR
DateTime FunctionsADD_DAYS
ADD_MONTHS
ADD_SECONDS
ADD_YEARS
CURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMPCURRENT_UTCDATE
CURRENT_UTCTIME
CURRENT_UTCTIMESTAMP
DAYNAME
DAYOFMONTH
DAYOFYEAR
DAYS_BETWEEN
EXTRACT
HOUR
ISOWEEK
LAST_DAY
LOCALTOUTC
MINUTE
MONTH
MONTHNAME
NEXT_DAY
NOW
QUARTER
SECOND
SECONDS_BETWEEN
UTCTOLOCAL
WEEK
WEEKDAY
YEAR
Number FunctionsABS
ACOS
ASIN
ATAN
ATAN2
BINTOHEX
BITAND
CEIL
COS
COSHCOT
EXP
FLOOR
GREATEST
HEXTOBIN
LEAST
LN
LOG
MOD
POWER
RAND
ROUND
SIGN
SIN
SINH
SQRT
TAN
Table of Content
5 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 6/193
51
51
5252
52
5253
53
53
53
54
54
54
55
55
55
56
56
56
56
57
57
57
58
58
58
5858
59
59
59
60
61
61
62
62
62
63
64
6464
65
66
67
68
77
81
82
83
84
85
86
95
101
102
102
103
103104
104
105
106
106
107
108
108
109109
110
114
114
115
117
118
128
TANH
UMINUS
String FunctionsASCII
CHAR
CONCATLCASE
LEFT
LENGTH
LOCATE
LOWER
LPAD
LTRIM
NCHAR
REPLACE
RIGHT
RPAD
RTRIM
SUBSTR_AFTER
SUBSTR_BEFORE
SUBSTRING
TRIM
UCASE
UNICODE
UPPER
Window Functions
Miscellaneous FunctionsCOALESCE
CURRENT_CONNECTION
CURRENT_SCHEMA
CURRENT_USER
GROUPING_ID
IFNULL
MAP
NULLIF
SESSION_CONTEXT
SESSION_USER
SYSUUID
SQL Statements
Data Definition StatementsALTER AUDIT POLICY
ALTER FULLTEXT INDEX
ALTER INDEX
ALTER SEQUENCE
ALTER TABLE
CREATE AUDIT POLICY
CREATE FULLTEXT INDEX
CREATE INDEX
CREATE SCHEMA
CREATE SEQUENCE
CREATE SYNONYM
CREATE TABLE
CREATE TRIGGER
CREATE VIEW
DROP AUDIT POLICY
DROP FULLTEXT INDEX
DROP INDEX
DROP SCHEMADROP SEQUENCE
DROP SYNONYM
DROP TABLE
DROP TRIGGER
DROP VIEW
RENAME COLUMN
RENAME INDEX
RENAME TABLE
Data Manipulation StatementsDELETE
EXPLAIN PLAN
INSERT
LOAD
MERGE DELTA
REPLACE | UPSERT
SELECT
TRUNCATE TABLE
Table of Content
6 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 7/193
129
129
130130
132
132133
134
134
135
135
136
137
137
138
138
139
140
140
141
141
142
142
143
143
144144
144
145
146
147
147147
147
148
149
150150
151
153
155
155
157
157
158
159
165
166167
168
169
172
173173
173
174
176
178179
180
180
182
184
185
UNLOAD
UPDATE
System M anagement StatementsALTER SYSTEM ALTER CONFIGURATION
ALTER SYSTEM ALTER SESSION SET
ALTER SYSTEM ALTER SESSION UNSETALTER SYSTEM CANCEL [WORK IN] SESSION
ALTER SYSTEM CLEAR SQL PLAN CACHE
ALTER SYSTEM CLEAR TRACES
ALTER SYSTEM DISCONNECT SESSION
ALTER SYSTEM LOGGING
ALTER SYSTEM PERSISTENCE ENCRYPTION
ALTER SYSTEM RECLAIM DATAVOLUME
ALTER SYSTEM RECLAIM LOG
ALTER SYSTEM RECLAIM VERSION SPACE
ALTER SYSTEM RECONFIGURE SERVICE
ALTER SYSTEM REMOVE TRACES
ALTER SYSTEM RESET MONITORING VIEW
ALTER SYSTEM SAVE PERFTRACE
ALTER SYSTEM SAVEPOINT
ALTER SYSTEM START PERFTRACE
ALTER SYSTEM STOP PERFTRACE
ALTER SYSTEM STOP SERVICE
SET SYSTEM LICENSE
UNSET SYSTEM LICENSE ALL
Session Management StatementsCONNECT
SET HISTORY SESSION
SET SCHEMA
SET [SESSION]
UNSET [SESSION]
Transaction Management StatementsCOMMIT
LOCK TABLE
ROLLBACK
SET TRANSACTION
Access Control StatementsALTER SAML PROVIDER
ALTER USER
CREATE ROLE
CREATE SAML PROVIDER
CREATE USER
DROP ROLE
DROP SAML PROVIDER
DROP USER
GRANT
REVOKE
Data Import Export StatementsEXPORT
IMPORT
IMPORT FROM
IMPORT SCAN
Procedural StatementsALTER PROCEDURE RECOMPILE
CALL
CREATE F UNCTION
CREATE PROCEDURE
CREATE TYPEDROP FUNCTION
DROP PROCEDURE
DROP TYPE
Res trictions for SQL Statements
See Also
SQL Error Code s
Table of Content
7 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 8/193
SAP HANA Database - SQL Reference Manual
This guide describes SQL language supported by SAP HANA DB.
SAP HANA Database - SQL Reference Manual
8 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 9/193
SQL Reference Manual
SAP HANA Database - SQL Reference Manual
9 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 10/193
Notation
This reference use BNF (Backus Naur Form) which is a notation technique used to define programming
languages. BNF describes the syntax of a grammar using a set of production rules and a set of symbols.
Symbols used in BNF
Symbol Description
< >Angle brackets are used to surround the name of a syntactic element (BNF nonterminal) of the SQL
language.
::=The definition operator is used to provide defini tions of the element appea red on the left side of
the operator in a production rule.
[ ]Square brackets are use d to indicate optional el ements in a formula. Optional el ements may be
specified or omitted.
{ }Braces group ele ments in a formula. Repetitive ele ments (zero or more el ements) can be s pecified
within brace symbols.
|The alternative operator indicates that the portion of the formula foll owing the bar is an
alternative to the portion preceding the bar.
...
The elli psis indicates that the element may be repeated any number of times. If ellips is a ppears
after grouped ele ments specifying that the grouped elements enclose d with braces are repeated.
If elli psis a ppears after a single ele ment, only that element is repeated.
!!Introduces normal English text. This is used when the definition of a syntactic element is not
express ed in BNF.
BNF Lowest Terms Representations
Throughout the BNF used in this manual each syntax term will be defined to one of the lowest term
representations shown below.
<digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
<letter> ::= a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r |
s | t | u | v | w | x | y | z
| A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R |
S | T | U | V | W | X | Y | Z
<string_literal> ::= <double_quote><string_content><double_quote> | <single_quote><string_content><single _quote>
<string_content> = { <letter> | <digit> }...
<identifier> ::= <letter> { <letter> | <digit> }...
<password> ::= [{ <letter> | <digit> }...]
<sign> ::= + | -
<period> ::= .
<unsigned_integer> ::= <digit>...
<signed_integer> ::= [<sign>] <unsigned_integer>
<signed_numeric_literal> ::= [<sign>] <unsigned_numeric_literal>
<unsigned_numeric_literal> ::= <exact_numeric_literal> | <approximate_numeric_literal>
<exact_numeric_literal> ::= <unsigned_integer> [<period> [<unsigned_integer>]]
| <period> <unsigned_integer>
<approximate_numeric_literal> ::= <mantissa> E <exponent>
<mantissa> ::= <exact_numeric_literal>
<exponent> ::= <signed_integer>
SAP HANA Database - SQL Reference Manual
10 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 11/193
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. I t is a standardized language for communicating with a relational
database. SQL is used to retrieve, store or manipulate information in the database.
SQL statements perform the following tasks:
Schema definition and manipulation
Data manipulation
System management
Session management
Transaction management
Supported Languages and Code Pages
The SAP HANA Dat abase supports Unicode to allow the use of all languages in the Unicode Standard and 7 Bit
ASCII code page without restriction.
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:
<identifier> ::= <simple_identifier> | <double_quotes><special_identifier><double_quotes>
<simple_identifier> ::= <letter> [{<letter_or_digit>|<underscore>}, ...]
<double_quotes> ::= "
<special_identifier> ::= any character
<letter> ::= A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P
| Q | R | S
| T | U | V | W | X | Y | Z | a | b | c | d | e | f | g | h | i
| j | k | l | m
| n | o | p | q | r | s | t | u | v | w | x | y | z
<digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
<letter_or_digit> ::= <letter> | <digit>
<underscore> ::= _
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 otherthan 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.
Single Quotation Mark
Single quotation marks are used to delimit string literals and single quotation mark itself can be represented
using two single quotation marks.
Double Quotation Mark
SAP HANA Database - SQL Reference Manual
11 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 12/193
Double quotation marks are used to delimit identifiers and double quotation mark itself can be represented
using two double quotation marks.
SQL Reserved Words
Reserved words are words which have a special meaning to the SQL parser in the SAP HANA Data base that
cannot be used as a user-defined name. Reserved words should not be used in SQL statements for schema
object names. If necessary, you can work around this limitation by delimiting a table or column name with
double quotation marks.
The following table lists all the current and future reserved words for the SAP HANA Database.
Table 1. Reserved Words
ALL ALTER AS BEFORE
BEGIN BOTH CASE CHAR
CONDITION CONNECT CROSS CUBE
CURRENT_CONNECTION CURRENT_DATE CURRENT_SCHEMA CURRENT_TIME
CURRENT_TIMESTAMP CURRENT_USER CURRENT_UTCDATE CURRENT_UTCTIME
CURRENT_UTCTIMESTAMP CURRVAL CURSOR DECLARE
DISTINCT ELSE ELSEIF ELSIF
END EXCEPT EXCEPTION EXEC
FOR FROM FULL GROUP
HAVING IF IN INNER
INOUT INTERSECT INTO IS
JOIN LEADING LEFT LIMIT
LOOP MINUS NATURAL NEXTVAL
NULL ON ORDER OUT
PRIOR RETURN RETURNS REVERSE
RIGHT ROLLUP ROWID SELECT
SET SQL START SYSDATE
SYSTIME SYSTIMESTAMP SYSUUID TOP
TRAILING UNION USING UTCDATE
UTCTIME UTCTIMESTAMP VALUES WHEN
WHERE WHILE WITH
SAP HANA Database - SQL Reference Manual
12 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 13/193
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.
Classification of Data Types
In the SAP HANA Database each data type can be classified by its characteristic a s follows:
Table 2: Classification of data types
Classification Data Type
D a te ti m e typ e s D AT E, T IME , S ECO ND DAT E, T IME STA MP
Numeric types TINYINT, SMALLINT, INTEGER, BIGINT, SMALLDECIMAL, DECIMAL, REAL, DOUBLE
Character string types VARCHAR, NVARCHAR, ALPHANUM, SHORTTEXT
Bina ry types VARBINARY
Large Object types B LOB, CLOB , NCLOB , TEXT
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 t he 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 a nd 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.
SAP HANA Database - SQL Reference Manual
13 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 14/193
Table 4: Supported formats for Date
Format Description Examples
YYYY-MM-DD Default format INSERT INTO my_tbl VALUES ('1957-06-13');
YYYY/MM/DD
YYYY/MM-DD
YYYY-MM/DD
YYYY from 0001 to 9999, MM from 1 to 12,
DD from 1 to 31. If year has less than four
digits, month has les s than two digits, orday has les s than two digits, then values
will be padded by one or more zeros. For
example, a two digit year 45 will be saved
as year 0045, a one digit month 9 will be
saved as 09, and a one di git day 2 will be
saved as 02.
INSERT INTO my_tbl VALUES ('1957-06-13');INSERT INTO my_tbl VALUES ('1957/06/13');
INSERT INTO my_tbl VALUES ('1957/06-13');
INSERT INTO my_tbl VALUES ('1957-06/13');
YYYYMMDD ABAP Da ta Type , DATS forma t. INSERT INTO my_tbl VALUES ('19570613');
MON Abbrevia ted na me of month. (JAN. ~ DEC.)
INSERT INTO my_tbl VALUES
(TO_DATE('2040-Jan-10', 'YYYY-MON-DD'));
INSERT INTO my_tbl VALUES
(TO_DATE('Jan-10', 'MON-DD'));
MONTH Na me of month. (JANUARY - DECEMBER).
INSERT INTO my_tbl VALUES
(TO_DATE('2040-Janua ry-10', 'YYYY-MONTH-
DD'));
INSERT INTO my_tbl VALUES
(TO_DATE('January-10', 'MONTH-DD'));
RM Roma n numera l month (I -XII ; JAN = I).
INSERT INTO my_tbl VALUES(TO_DATE('2040-I-10', 'YYYY-RM-DD'));
INSERT INTO my_tbl VALUES (TO_DATE('I-
10', 'RM-DD'));
DDD Da y of year (1-366).
INSERT INTO my_tbl VALUES
(TO_DATE('204', 'DD D'));
INSERT INTO my_tbl VALUES
(TO_DATE('2001-204','YYYY-DDD'));
Time Formats
Table 5: Supported formats for Time
Format Description Examples
HH24:MI:SS Defa ult forma t
HH:MI[:SS][AM|PM]
HH12:MI[:SS][AM|PM]
HH24:MI[:SS]
HH from 0 to 23. MI from 0 to 59. SS from 0
to 59. FFF from 0 to 999.
If one di git hour, minute, second isspecified, then 0 will be inserted into
the value. For example, 9:9:9 will be
saved as 09:09:09.
HH12 indicates 12 hour clock and HH24
indicates 24 hour clock.
AM or PM can be specified as a suffix to
indicate the time value i s before or after
noon.
INSERT INTO my_tbl VALUES ('23:59:59');
INSERT INTO my_tbl VALUES ('3:47:39 AM');
INSERT INTO my_tbl VALUES ('9:9:9 AM');
INSERT INTO my_tbl VALUES
(TO_TIME('11:59:59','HH12:MI:SS');
SSSSS Seconds pa st midnight (0-86399).INSERT INTO my_tbl VALUES
(TO_TIME('12345', 'SSSSS '));
Timestamp Formats
Table 6: Supported formats for Timestamp
Format Description Examples
YYYY-MM-DD
HH24:MI:SS.FF7 Default format
FF [1..7]
Fractional s econds has the range 1 to 7
after the FF parameter to specify the
number of digits in the fractional second
portion of the date time value returned. If
a digit is not specified, the default value
is used.
INSERT INTO my_tbl VALUES
(TO_TIMESTAMP('2011-05-11
12:59.999','YYYY-MM-DD HH:SS.FF3'));
Additional Formats
SAP HANA Database - SQL Reference Manual
14 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 15/193
Table 7: Additional formats for Datetime
Format Description Example
D Da y of week (1-7). TO_CHAR(CURRENT_TIMESTAMP,'D')
DAY Na me of da y (MONDAY - SUNDAY). TO_CHAR(CURRENT_TIMESTAMP,'DAY')
DY Abbrevia ted na me of day (MON - SUN). TO_CHAR(CURRENT_TIMESTAMP,'DY')
MON Abbre vi ated month na me (JAN - DEC) TO_CHAR(CURRENT_TIMESTAMP,'MON')
MONTH Fu ll m on th n ame ( JANUAR Y - DECEMBER ) TO_CHAR(CUR RENT_TI MESTAMP,'MONTH')
RMRoman numeral month (I - XII; I is for
January)TO_CHAR(CURRENT_TIMESTAMP,'RM')
Q Quarter of year (1, 2, 3, 4) TO_CHAR(CURRENT_TIMESTAMP,'Q')
W Week of month (1-5). TO_CHAR(CURRENT_TIMESTAMP,'W')
WW Week of yea r (1-53). TO_CHAR(CURRENT_TIMESTAMP,'WW')
Supported Functions for Date/Time types
ADD_DAYS
ADD_MONTHS
ADD_SECONDS
ADD_YEARS
COALESCECURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMP
CURRENT_UTCDATE
CURRENT_UTCTIME
CURRENT_UTCTIMESTAMP
DAYNAME
DAYOFMONTH
DAYOFYEAR
DAYS_BETWEEN
EXTRACT
GREATEST
GREATEST
HOUR
IFNULL
ISOWEEKLAST_DAY
LEAST
LOCALTOUTC
MINUTE
MONTH
MONTHNAME
NEXT_DAY
NULLIF
QUARTER
SECOND
SECONDS_BETWEEN
TO_DATE
TO_DATS
TO_TIME
TO_TIMESTAMP
UTCTOLOCALWEEK
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.
INTEGER
The INTEGER data type stores a 32-bit signed integer. The minimum value is -2,147,483,648 and the
SAP HANA Database - SQL Reference Manual
15 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 16/193
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.
DECIMAL(precision, scale) or DEC(p,s)
DECIMAL(p, s) is the SQL standard notation for fixed-point decimal. "p" specifies precision or the
number of total digits (the sum of whole digits and fractional digits). "s" denotes scale or the number
of fractional digits. For example, if a column is defined as DECIMAL(5, 4), the numbers 3.14, 3. 1415,
3.141592 are stored in the column as 3.1400, 3. 1415, 3.1416, respectively keeping the specified
precision(5) and scale(4).
The precision p, can range from 1 to 34. The scale can range from 0 to p. I f the scale is not specified, it
defaults to 0.
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 1 to 34 for precision and -6,111 to 6,176 for
scale depending on the stored value.
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 negat ive 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.
Character String Types
The character string data types are used to store values that contain character strings. While VARCHAR data
types contain ASCII character strings, NVARCHAR are used for storing Unicode character strings.
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.
SAP HANA Database - SQL Reference Manual
16 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 17/193
SHORTTEXT
The SHORTTEXT(n) data type specifies veriable-length character string which supports textsearch-
features and stringsearch-features. This is not a standalone sql-type. Selecting a SHORTTEXT(n)-
column yields a column of type NVARCHAR(n).
<shorttext_type> ::= SHORTTEXT '(' int_const ')' <elem_list_shorttext>
<elem_list_shorttext> ::= <elem_shorttext> [... ',' <elem_shorttext>]
<elem_shorttext> ::= <fulltext_elem> | SYNC[HRONOUS]
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.
Large Object (LOB) Types
LOB (large objects) data types, CLOB, NCLOB and BLOB, are used to store a large amount of data such as text
documents and images. The maximum size of an LOB is 2 GB.
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.
<text_type> ::= TEXT <opt_fulltext_elem_list_text>
<opt_fulltext_elem_list_text> ::=
<fulltext_elem_text> [... ',' <fulltext_elem_text>]
<fulltext_elem_text> ::= <fulltext_elem>
| [SYNC[HRONOUS]
| [ASYNC[HRONOUS] FLUSH [QUEUE]
EVERY <n> MINUTES [[OR] AFTER <m> DOCUMENTS] ]
Syntax-rules common to TEXT and SHORTTEXT
<fulltext_elem> ::= LANGUAGE COLUMN <column_name>
| LANGUAGE DETECTION '(' <str_const_list> ')'
| MIME TYPE COLUMN <column_name>
| FUZZY SEARCH INDEX [ON|OFF]
| PHRASE INDEX RATIO [ON|OFF]
| CONFIGURATION <str_const>
| SEARCH ONLY [ON|OFF]
| FAST PREPROCESS [ON|OFF]
LOB types are provided for storing and retrieving such large data. LOB types support the following
operations.
The length() function returns the LOB length in bytes.
LIKE can be used to search LOB columns.
The LOB types have the following restrictions:
LOB columns cannot appear in ORDER BY or GROUP BY c lauses.
LOB columns cannot appear in FROM clauses as a join predicate.
LOB columns cannot appear in WHERE clauses as a predicate except LIKE, CONTAINS, =, or <>.
LOB columns cannot appear in SELECT clauses as an aggregate function argument.
LOB columns cannot appear in SELECT DI STINCT clauses.
LOB columns cannot be used in set operations such as EXCEPT. UNION ALL is an exception.
LOB columns cannot be used as a primary key.
SAP HANA Database - SQL Reference Manual
17 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 18/193
LOB columns cannot be used in CREATE INDEX statements.
LOB columns cannot be used in statistics update statements.
Mapping between SQL Data Type and Column Store Data Type
SQL Type Column Store Type
I nte ge r Typ es TI NYI NT, S MALLI NT, I NT CS_I NT
BIGINT CS_FIXED(18,0)
Approxi mate Types REAL CS_FLOAT
DOUBLE CS_DOUBLE
FLOAT CS_DOUBLE
FLOAT(p) CS_FLOAT, CS_DOUBLE
Deci ma l Types DECIMAL CS_DECIMAL_FLOAT
DECIMAL(p,s) CS_FIXED(p-s ,s )
SMALLDECIMAL CS_SDFLOAT
Character Types VARCHAR CS_STRING
NVARCHAR CS_STRING
CLOB, NCLOB CS_STRING
ALPHANUM CS_ALPHANUM
Bina ry Types BLOB CS_RAW
VARBINARY CS_RAW
Date/Ti me Types DATE CS_DAYDATE
TIME CS_SECONDTIME
TIMESTAMP CS_LONGDATE
SECONDDATE CS_SECONDDATE
Data Type Conversion
This section describes the data type conversion allowed in SAP HANA Database.
Explicit type conversion
The type of an expression result, for example a field reference, a function on fields, or literals can beconverted 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.
Implicit type conversion
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 B IGINT. 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
Table 8: Implicit Type conversion Examples
Input Expression Transformed Expression with Implicit Conversion
BIGINT > VARCHAR BIGINT > BIGINT(VARCHAR)
BIGINT > DECIMAL DECIMAL(BIGINT) > DECIMAL
TIMESTAMP > DATE TIMESTAMP > TIMESTAMP(DATE)
DATE > T IME Error because there is no convers ion avai lab le between DATE and T IME
In the tables below,
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.
SAP HANA Database - SQL Reference Manual
18 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 19/193
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.
Table 9a: Data type conversion table
Target/
Source
tinyint - OK OK OK OK OK OK OK OK OK OK
smallint CHK - OK OK OK OK OK OK OK OK OK
integer CHK CHK - OK OK OK OK OK OK OK OK
bigint CHK CHK CHK - OK CHK CHK CHK OK OK OK
decimal CHK CHK CHK CHK - CHK CHK CHK OK OK OK
decimal(p,s) CHK CHK CHK CHK CHK CHK CHK CHK CHK CHK OK
smalldecimal CHK CHK CHK CHK OK CHK - CHK CHK OK OK
real CHK CHK CHK CHK OK CHK CHK - OK OK OK
double CHK CHK CHK CHK CHK CHK CHK CHK - OK OK
varchar CHK CHK CHK CHK CHK CHK CHK CHK CHK - OK
nvarchar CHK CHK CHK CHK CHK CHK CHK CHK CHK CHK -
Table 9b: Data type conversion table
Target/
Source time date seconddate timestamp varchar nvarchar
time - - - - OK OK
date - - OK OK OK OK
seconddate time da te - timesta mp OK OK
timestamp time da te seconddate - OK OK
varchar CHK CHK CHK CHK - OK
nvarchar CHK CHK CHK CHK CHK -
Table 9c: Data type conversion table
Target/
Source varbinary alphanum varchar nvarchar
varbinary - - - -
alphanum - - OK OK
varchar OK OK - OK
nvarchar OK OK CHK -
Data Type Precedence
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.
t i n y i n t
s m a l l i n t
i n t e g e r
b i g i n t
d e c i m a l
d e c i m a l ( p , s )
s m a l l d e c i m
a l
r e a l
d o u b l e
v a r c h a r
n v a r c h a r
SAP HANA Database - SQL Reference Manual
19 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 20/193
Highest TIMESTAMP
SECONDDATE
DATE
TIME
DOUBLE
REAL
DECIMAL
SMALLDECIMAL
BIGINT
INTEGER
SMALLINT
TINYINT
NCLOB
NVARCHAR
CLOB
VARCHAR
BLOB
Lowest VARBINARY
Typed Constant
A constant is a symbol that represents a specific fixed data value.
Character string contant
A character string constant is enclosed in single quotation marks.
'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;
character string 1, character string 2, unicode string
Brian, 100, abc
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
SELECT 123 "integer", 123.4 "decimal1", 1.234e2 "decimal2", 0x0abc "hexadecimal" FR
OM DUMMY;
integer, decimal1, decimal2, hexadecimal
123, 123.4, 123.4, 2748
Binary string constant
A binary string has the prefix X and is a string of hexadecimal numbers that are enclosed in quotation
marks.
X'00abcd'
x'dcba00'
SELECT X'00abcd' "binary string 1", x'dcba00' "binary string 2" FROM DUMMY;
binary string 1, binary string 2
SAP HANA Database - SQL Reference Manual
20 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 21/193
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'
SELECT date'2010-01-01' "date", time'11:00:00.001' "time", timestamp'2011-12-31 23:
59:59' "timestamp" FROM DUMMY;
date, time, timestamp
2010-01-01, 11:00:00, 2011-12-31 23:59:59.0
SAP HANA Database - SQL Reference Manual
21 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 22/193
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:
<range_predicate> ::= <expression1> [NOT] BETWEEN <expression2> AND <expression3>
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:
<in_predicate> ::= <expression> [NOT] IN { <expression_list> | <subquery> }
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:
<exists_predicate> ::= [NOT] EXISTS ( <subquery> )
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 (%) mat ches 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 mat ched.
Syntax:
<like_predicate> ::= <expression1> [NOT] LIKE <expression2> [ESCAPE <expression3>]
NULL Predicate
SAP HANA Database - SQL Reference Manual
22 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 23/193
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:
<null_predicate> ::= <expression> IS [NOT] NULL
CONTAINS Predicate
The CONTAINS predicate is used to search for text-matches to a search string in subqueries.
Syntax:
<contains_function> ::= CONTAINS '(' <contains_columns> ',' <search_string>')'
| CONTAINS '(' <contains_columns> ',' <search_string> ',' <se
arch_specifier> ')'
<contains_columns> ::= '*' | <column_name> | '(' <columnlist> ')'
<search_string> ::= <string_const>
<search_specifier> ::= <search_type> <opt_search_specifier2_list>
| <search_specifier2_list>
<opt_search_specifier2_list> ::= empty
| <search_specifier2_list>
<search_type> ::= <exact_search> | <fuzzy_search> | <linguistic_search>
<search_specifier2_list> ::= <search_specifier2>
| <search_specifier2_list> ',' <search_specifier2>
<search_specifier2> := <weights> | <language>
<exact_search> ::= EXACT
<fuzzy_search> ::= FUZZY
| FUZZY '(' <float_const> ')'
| FUZZY '(' <float_const> ',' <additional_params> ')'
<linguistic_search> ::= LINGUISTIC
<weights> ::= WEIGHT '(' <float_const_list> ')'
<language> :: LANGUAGE '(' <string_const> ')'
<additional_params> ::= <string_const>
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
SAP HANA Database - SQL Reference Manual
23 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 24/193
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
select * from T where contains(column1, 'dog OR cat') -- EXACT is implicit select
* from T where contains(column1, 'dog OR cat', EXACT)
select * from T where contains(column1, '"cats and dogs"') -- phrase search
Fuzzy search
select * from T where contains(column1, 'catz', FUZZY(0.8))
Linguistic search:
select * from T where contains(column1, 'catz', LINGUISTIC)
Freestyle search:
The freestyle-search is a search mulitple columns.
select * from T where CONTAINS( (column1,column2,column3), 'cats OR dogz', FUZZY(0.
7))
select * from T where CONTAINS( (column1,column2,column3), 'cats OR dogz', FUZZY(0.
7))
SAP HANA Database - SQL Reference Manual
24 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 25/193
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 26/193
Table 12. Arithmetic operators
Operator Description
-<e xp re s si on > Ne ga ti on . I f th e e xp re s si on i s th e NU LL va l ue , th e re s ul t i s N ULL.
<express ion> +
<expression>Addition. If either express ion i s the NULL value, the result i s NULL.
<express ion> -<expression>
Subtraction. If either expression is the NULL value, the result is NULL.
<express ion> *
<expression>Multipli cation. If either express ion i s NULL, the resul t is NULL.
<express ion> /
<expression>
Division. If ei ther expression i s NULL, or if the se cond expression i s 0, an error is
returned.
String Operators
A concatenation operator combines two items such as strings, expressions or constants into one.
Table 13. Concatenation operators
Operator Description
<express ion> || <expression>String concatenation (two vertical bars).
If ei ther string is NULL, it returns NULL.
For VARCHAR or NVARCHAR type strings, leading or tra iling 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:
<comparison_operation> ::= <expression1> <comparison_operator> <expression2>
Table 14. Comparison operators
Operator Description Example
= Equal to SELECT * FROM s tudents WHERE id = 25;
> Greater than SELECT * FROM s tudents WHERE id > 25;
< Less than SELECT * FROM s tudents WHERE id < 25;
>= Gre a te r th an or e qu al to S ELECT * F ROM s tu de nts WH ER E i d >= 25;
<= Le ss tha n or e qua l to SELECT * FROM s tude nts WHERE i d <= 25;
!=, <> Not equa lSELECT * FROM students WHERE id != 25;
SELECT * FROM students WHERE id <> 25;
Logical Operators
Search conditions can be combined using AND or OR operators. You can also negate them using the NOT
operator.
Table 15. Logical operators
Operator Syntax Descr iption
AND
WHERE
condition1AND
condition2
When using AND, the combined condition is TRUE if both conditions are TRUE,FALSE if either condition is FALSE, and UNKNOWN otherwise.
OR
WHERE
condition1
OR
condition2
When usi ng OR, the combined condition is TRUE if either condition i s TRUE,
FALSE if both conditions a re FALSE, and UNKNOWN otherwise.
NOTWHERE NOT
condition
The NOT operator is placed before a condition to negate the condition. The NOT
condition is TRUE if condition is FALSE, FALSE if condition is TRUE, and UNKNOWN
if condition is UNKNOWN.
Set Operators
The operators described in this section perform set operations on the results of two or more queries.
SAP HANA Database - SQL Reference Manual
26 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 27/193
Table 16. Set operators
Operator Returned Value
UNION Combines the resu lts o f two or more select statements or query express ions
UNION
ALL
Combines the results of two or more s elect statements or query express ions, including a ll
duplicate rows.
INTERSECT Combines the results of two or more s elect statements or query expressions , and returns allcommon rows.
EXCEPT Takes output from the f irst query and then removes rows sele cted by the second query.
SAP HANA Database - SQL Reference Manual
27 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 28/193
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 }
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:
<function_expression> ::= <function_name> ( <expression>, ... )
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_expression> ::= COUNT(*) | <agg_name> ( [ ALL | DISTINCT ] <expression>
)
<agg_name> ::= COUNT | MIN | MAX | SUM | AVG | STDDEV | VAR
Aggregate
name Description
COUNT
Counts the numbe r of rows returned by a que ry. COUNT(*) returns the nu mber of rows, regardle ss
of the value of those rows and including duplicate values. COUNT(<expression>) returns the
number of non-NULL val ues for that expres si on returned by the query.
MI N R etu rns the mi ni mum va l ue of e xp re ss i on .
MAX R etu rns the ma xi mum va l ue of exp re ss i on .
SUM Re turns the s um of e xpre ss ion.
AVG R etu rn s th e a ri th me ti ca l me a n o f e xp re s si on .
STDDEV Returns the standard deviation of given expression as the square root of VARIANCE function.
V AR R e tu rn s th e va ri a n ce o f e xp re s s i on a s th e s qu a re o f s ta n da rd de vi a ti o n.
Subqueries in Expressions
SAP HANA Database - SQL Reference Manual
28 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 29/193
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:
<scalar_subquery_expression> ::= (<subquery>)
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:
SELECT DepartmentName, COUNT(*), 'out of',
(SELECT COUNT(*) FROM Employees)
FROM Departments AS D, Employees AS E
WHERE D.DepartmentID = E.DepartmentID
GROUP BY DepartmentName;
SAP HANA Database - SQL Reference Manual
29 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 30/193
SQL Functions
Introduction
This chapter describes SQL Functions that are provided by SAP HANA Database.
Data Type Conversion Functions
DateTime Functions
Number Functions
String Functions
Window Functions
Miscellaneous Functions
Data Type Conversion Functions
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
CAST (expression AS data_type)
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
Returns the value of an expression converted to a supplied data type.
Example
SELECT CAST (7 AS VARCHAR) "cast" FROM DUMMY;
cast
7
TO_ALPHANUM
Syntax
TO_ALPHANUM (value)
Description
Converts a given value to an ALPHANUM data type.
Example
SELECT TO_ALPHANUM ('10') "to alphanum" FROM DUMMY;
to alphanum
10
TO_BIGINT
Syntax
TO_BIGINT (value)
Description
Converts a value to a BIGINT data type.
SAP HANA Database - SQL Reference Manual
30 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 31/193
Example
SELECT TO_BIGINT ('10') "to bigint" FROM DUMMY;
to bigint 10
TO_BINARY
Syntax
TO_BINARY (value)
Description
Converts a value to a BINARY data type.
Example
SELECT TO_BINARY ('abc') "to binary" FROM DUMMY;
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
SELECT TO_BLOB (TO_BINARY('abcde')) "to blob" FROM DUMMY;
to blob
abcde
TO_CLOB
Syntax
TO_CLOB (value)
Description
Converts a value to a CLOB data type.
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
SAP HANA Database - SQL Reference Manual
31 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 32/193
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
SELECT TO_DATE('2010-01-12', 'YYYY-MM-DD') "to date" FROM DUMMY;
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
SELECT TO_DATS ('2010-01-12') "abap date" FROM DUMMY;
abap date
20100112
TO_DECIMAL
Syntax
TO_DECIMAL (value [, precision, scale])
Description
Converts the value to a D ECIMAL data type.
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 t he 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.
Example
SELECT TO_DECIMAL(7654321.888888, 10, 3) "to decimal" FROM DUMMY
to decimal
7654321.889
TO_DOUBLE
Syntax
TO_DOUBLE (value)
Description
Converts a value to a DOUBLE (double precision) data type.
SAP HANA Database - SQL Reference Manual
32 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 33/193
Example
SELECT 3*TO_DOUBLE ('15.12') "to double" FROM DUMMY;
to double
45.36
TO_INT
Syntax
TO_INT (value)
Description
Converts the value to an INTEGER data type.
Example
SELECT TO_INT('10') "to int" FROM DUMMY;
to int
10
TO_INTEGER
Syntax
TO_INTEGER (value)
Description
Converts the value to an INTEGER data type.
Example
SELECT TO_INTEGER ('10') "to int" FROM DUMMY;
to int
10
TO_NCLOB
Syntax
TO_NCLOB (value)
Description
Converts a value to a NCLOB data type.
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
TO_NVARCHAR (value [,format])
Description
SAP HANA Database - SQL Reference Manual
33 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 34/193
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
SELECT TO_NVARCHAR(TO_DATE('2009/12/31'), 'YY-MM-DD') "to nchar" FROM DUMMY;
to nchar
09-12-31
TO_REAL
Syntax
TO_REAL (value)
Description
Converts a value to a REAL (single precision) data type.
Example
SELECT 3*TO_REAL ('15.12') "to real" FROM DUMMY;
to real
45.36000061035156
TO_SECONDDATE
Syntax
TO_SECONDDATE (d [, format])
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
SELECT TO_SECONDDATE ('2010-01-11 13:30:00', 'YYYY-MM-DD HH24:MI:SS') "to seconddat
e" FROM DUMMY;
to seconddate
2010-01-11 13:30:00.0
TO_SMALLDECIMAL
Syntax
TO_SMALLDECIMAL (value)
Description
Converts the value to a SMALLDECIMAL data type.
Example
SELECT TO_SMALLDECIMAL(7654321.89) "to smalldecimal" FROM DUMMY;
to smalldecimal
7654321.89
TO_SMALLINT
Syntax
SAP HANA Database - SQL Reference Manual
34 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 35/193
TO_SMALLINT (value)
Description
Converts the value to a SMALLINT data type.
Example
SELECT TO_SMALLINT ('10') "to smallint" FROM DUMMY;
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
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
SELECT TO_TIMESTAMP ('2010-01-11 13:30:00', 'YYYY-MM-DD HH24:MI:SS') "to timestamp"
FROM DUMMY;
to timestamp
2010-01-11 13:30:00.0
TO_TINYINT
Syntax
TO_TINYINT (value)
Description
Converts the value to a TINYINT data type.
Example
SELECT TO_TINYINT ('10') "to tinyint" FROM DUMMY;
to tinyint
10
SAP HANA Database - SQL Reference Manual
35 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 36/193
TO_VARCHAR
Syntax
TO_VARCHAR (value [, format])
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
SELECT TO_VARCHAR (TO_DATE('2009-12-31'), 'YYYY/MM/DD') "to char" FROM DUMMY;
to char
2009/12/31
DateTime Functions
ADD_DAYS
Syntax
ADD_DAYS (d, n)
Description
Computes the date d plus n days.
Example
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
Computes the date d plus n months.
Example
SELECT ADD_MONTHS (TO_DATE ('2009-12-05', 'YYYY-MM-DD'), 1) "add months" FROM DUMMY
;
add months
2010-01-05
ADD_SECONDS
Syntax
ADD_SECONDS (t, n)
Description
Computes the time t plus n seconds.
Example
SAP HANA Database - SQL Reference Manual
36 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 37/193
SELECT ADD_SECONDS (TO_TIMESTAMP ('2012-01-01 23:30:45'), 60*30) "add seconds" FROM
DUMMY;
add seconds
2012-01-02 00:00:45.0
ADD_YEARS
Syntax
ADD_YEARS (d, n)
Description
Computes the date d plus n years.
Example
SELECT ADD_YEARS (TO_DATE ('2009-12-05', 'YYYY-MM-DD'), 1) "add years" FROM DUMMY;
add years 2010-12-05
CURRENT_DATE
Syntax
CURRENT_DATE
Description
Returns the current local system date.
Example
SELECT CURRENT_DATE "current date" FROM DUMMY;
current date
2010-01-11
CURRENT_TIME
Syntax
CURRENT_TIME
Description
Returns the current local system time.
Example
SELECT CURRENT_TIME "current time" FROM DUMMY;
current time
17:37:37
CURRENT_TIMESTAMP
Syntax
CURRENT_TIMESTAMP
Description
Returns the current local system timestamp information.
SAP HANA Database - SQL Reference Manual
37 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 38/193
Example
SELECT CURRENT_TIMESTAMP "current timestamp" FROM DUMMY;
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
SELECT CURRENT_UTCDATE "Coordinated Universal Date" FROM DUMMY;
Coordinated Universal Time
2010-01-11
CURRENT_UTCTIME
Syntax
CURRENT_UTCTIME
Description
Returns the current UTC t ime.
Example
SELECT CURRENT_UTCTIME "Coordinated Universal Time" FROM DUMMY;
Coordinated Universal Time
08:41:19
CURRENT_UTCTIMESTAMP
Syntax
CURRENT_UTCTIMESTAMP
Description
Returns the current UTC t imestamp.
Example
SELECT CURRENT_UTCTIMESTAMP "Coordinated Universal Timestamp" FROM DUMMY;
Coordinated Universal Timestamp
2010-01-11 08:41:42.484
DAYNAME
Syntax
DAYNAME (d)
Description
SAP HANA Database - SQL Reference Manual
38 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 39/193
Returns the weekday in English for date d.
Example
SELECT DAYNAME ('2011-05-30') "dayname" FROM DUMMY;
dayname
MONDAY
DAYOFMONTH
Syntax
DAYOFMONTH (d)
Description
Returns an integer the day of the month for date d.
Example
SELECT DAYOFMONTH ('2011-05-30') "dayofmonth" FROM DUMMY;
dayofmonth
30
DAYOFYEAR
Syntax
DAYOFYEAR (d)
Description
Returns an integer representation of the day of the year for date d.
Example
SELECT DAYOFYEAR ('2011-05-30') "dayofyear" FROM DUMMY;
dayofyear
150
DAYS_BETWEEN
Syntax
DAYS_BETWEEN (d1, d2)
Description
Computes the number of days between d1 and d2.
Example
SELECT DAYS_BETWEEN (TO_DATE ('2009-12-05', 'YYYY-MM-DD'), TO_DATE('2010-01-05', 'Y
YYY-MM-DD')) "days between" FROM DUMMY;
days between
31
EXTRACT
Syntax
EXTRACT ({YEAR | MONTH | DAY | HOUR | MINUTE | SECOND} FROM d)
SAP HANA Database - SQL Reference Manual
39 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 40/193
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
Returns an integer representation of the hour for time t.
Example
SELECT HOUR ('12:34:56') "hour" FROM DUMMY;
hour
12
ISOWEEK
Syntax
ISOWEEK (d)
Description
Returns the ISO year and week numbers of date d. The week number is prefixed by the letter W.
Please also see WEEK
Example
SELECT ISOWEEK (TO_DATE('2011-05-30', 'YYYY-MM-DD')) "isoweek" FROM DUMMY;
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
SELECT LAST_DAY (TO_DATE('2010-01-04', 'YYYY-MM-DD')) "last day" FROM DUMMY;
last day
2010-01-31
LOCALTOUTC
SAP HANA Database - SQL Reference Manual
40 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 41/193
Syntax
LOCALTOUTC (t, timezone)
Description
Convert the local time t from a timezone to the UTC(GMT) time
Example
SELECT LOCALTOUTC (TO_TIMESTAMP('2012-01-01 01:00:00', 'YYYY-MM-DD HH24:MI:SS'), '
EST') "localtoutc" FROM DUMMY;
localtoutc
2012-01-01 06:00:00.0
MINUTE
Syntax
MINUTE (t)
Description
Returns an integer representation of the minute for t ime t.
Example
SELECT MINUTE ('12:34:56') "minute" FROM DUMMY;
minute
34
MONTH
Syntax
MONTH(d)
Description
Returns the number of the month from date d.
Example
SELECT MONTH ('2011-05-30') "month" FROM DUMMY;
month
5
MONTHNAME
Syntax
MONTHNAME(d)
Description
Returns the name of the month in English for date d.
Example
SELECT MONTHNAME ('2011-05-30') "monthname" FROM DUMMY;
monthname
MAY
SAP HANA Database - SQL Reference Manual
41 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 42/193
NEXT_DAY
Syntax
NEXT_DAY (d)
Description
Returns the date of the next day after date d.
Example
SELECT NEXT_DAY (TO_DATE ('2009-12-31', 'YYYY-MM-DD')) "next day" FROM DUMMY;
next day
2010-01-01
NOW
Syntax
NOW ()
Description
Returns the current timestamp.
Example
SELECT NOW () "now" FROM DUMMY;
now
2010-01-01 16:34:19.894
QUARTER
Syntax
QUARTER (d, [, start_month ])
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
SELECT QUARTER (TO_DATE('2012-01-01', 'YYYY-MM-DD'), 2) "quarter" FROM DUMMY;
quarter
2011-Q4
SECOND
Syntax
SECOND (t)
Description
Returns an integer representation of the second for time t .
Example
SELECT SECOND ('12:34:56') "second" FROM DUMMY;
second
SAP HANA Database - SQL Reference Manual
42 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 43/193
56
SECONDS_BETWEEN
Syntax
SECONDS_BETWEEN (d1, d2)
Description
Computes the number of seconds between date arguments d1 and d2, which is semantically equal to d2 - d1.
Example
SELECT SECONDS_BETWEEN ('2009-12-05', '2010-01-05') "seconds between" FROM DUMMY;
Seconds between
2678400
UTCTOLOCAL
Syntax
UTCTOLOCAL (t, timezone)
Description
Convert the UTC(GMT) time t to the local time in a timezone
Example
SELECT UTCTOLOCAL (TO_TIMESTAMP('2012-01-01 01:00:00', 'YYYY-MM-DD HH24:MI:SS'), '
EST') "utctolocal" FROM DUMMY;
utctolocal
2011-12-31 20:00:00.0
WEEK
Syntax
WEEK (d)
Description
Returns the week number of date d.
Please also see ISOWEEK
Example
SELECT WEEK (TO_DATE('2011-05-30', 'YYYY-MM-DD')) "week" FROM DUMMY;
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).
SAP HANA Database - SQL Reference Manual
43 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 44/193
Example
SELECT WEEKDAY (TO_DATE ('2010-12-31', 'YYYY-MM-DD')) "week day" FROM DUMMY;
week day
4
YEAR
Syntax
YEAR (d)
Description
Returns the year number of date d.
Example
SELECT YEAR (TO_DATE ('2011-05-30', 'YYYY-MM-DD')) "year" FROM DUMMY;
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
Syntax
ABS (n)
Description
Returns the absolute value of the numeric argument n.
Example
SELECT ABS (-1) "absolute" FROM DUMMY;
absolute
1
ACOS
Syntax
ACOS (n)
Description
Returns the arc-cosine, in radians, of the numeric argument n between -1 and 1.
Example
SELECT ACOS (0.5) "acos" FROM DUMMY;
acos
1.0471975511965979
ASIN
Syntax
SAP HANA Database - SQL Reference Manual
44 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 45/193
ASIN (n)
Description
Returns the arc-sine, in radians, of the numeric argument n between -1 and 1.
Example
SELECT ASIN (0.5) "asin" FROM DUMMY;
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
SELECT ATAN (0.5) "atan" FROM DUMMY;
atan
0.4636476090008061
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
SELECT ATAN2 (1.0, 2.0) "atan2" FROM DUMMY;
atan2
0.4636476090008061
BINTOHEX
Syntax
BINTOHEX (expression)
Description
Converts a binary value to a hexadecimal value.
Example
SELECT BINTOHEX('AB') "bintohex" FROM DUMMY;
bintohex
4142
BITAND
SAP HANA Database - SQL Reference Manual
45 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 46/193
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 t ype.
Example
SELECT BITAND (255, 123) "bitand" FROM DUMMY;
bitand
123
CEIL
Syntax
CEIL (n)
Description
Returns the first integer that is greater or equal to the value n.
Example
SELECT CEIL (14.5) "ceiling" FROM DUMMY;
ceiling
15
COS
Syntax
COS (n)
Description
Returns the cosine of the angle, in radians, of the argument n.
Example
SELECT COS (0.0) "cos" FROM DUMMY;
cos
1.0
COSH
Syntax
COSH (n)
Description
Computes the hyperbolic cosine of the argument n.
Example
SELECT COSH (0.5) "cosh" FROM DUMMY;
cosh
1.1276259652063807
SAP HANA Database - SQL Reference Manual
46 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 47/193
COT
Syntax
COT (n)
Description
Computes the cotangent of a number n, where the argument is an angle expressed in radians.
Example
SELECT COT (40) "cot" FROM DUMMY;
cot
-0.8950829176379128
EXP
Syntax
EXP (n)
Description
Returns the result of the base of natural logarithms e raised to the power of the arg ument n.
Example
SELECT EXP (1.0) "exp" FROM DUMMY;
exp
2.718281828459045
FLOOR
Syntax
FLOOR (n)
Description
Returns the largest integer not greater than the numeric argument n.
Example
SELECT FLOOR (14.5) "floor" FROM DUMMY;
floor
14
GREATEST
Syntax
GREATEST (n1 [, n2]...)
Description
Returns the greatest value among the arguments: n1, n2, .. .
Example
SELECT GREATEST ('aa', 'ab', 'ba', 'bb') "greatest" FROM DUMMY;
SAP HANA Database - SQL Reference Manual
47 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 48/193
greatest
bb
HEXTOBIN
Syntax
HEXTOBIN (value)
Description
Converts a hexadecimal value to a binary value.
Example
SELECT HEXTOBIN ('1a') "hextobin" FROM DUMMY;
hextobin
1A
LEAST
Syntax
LEAST (n1 [, n2]...)
Description
Returns the least value among the arguments: n1, n2.. .
Example
SELECT LEAST('aa', 'ab', 'ba', 'bb') "least" FROM DUMMY;
least
aa
LN
Syntax
LN (n)
Description
Returns the natural logarithm of the argument n.
Example
SELECT LN (9) "ln" FROM DUMMY;
ln 2.1972245773362196
LOG
Syntax
LOG (b, n)
Description
Returns the natural logarithm of a number n base b. B ase b must be a positive value greater than 1 and n
must be any positive value.
Example
SAP HANA Database - SQL Reference Manual
48 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 49/193
SELECT LOG (10, 2) "log" FROM DUMMY;
log
0.30102999566398114
MOD
Syntax
MOD (n, d)
Description
Returns the remainder of a number n divided by a divisor d.
When n is negative this function acts differently to the standard computational modulo operation.
The following explains example of what the MOD function returns as the result.
If d is zero, then n is returned.
If n is greater than 0 and n is less than d, then n is returned.
If n is less than 0 and n is greater than d, then n is returned.In other case that those mentioned above, remainder of the absolute value of n divided by the
absolute value of d is used to calculate remainder. If n is less than 0, then the returned remainder
from MOD is a negative number, and if n is greater than 0, then the returned remainder from MOD is
a positive number.
Example
SELECT MOD (15, 4) "modulus" FROM DUMMY;
modulus
3
SELECT MOD (-15, 4) "modulus" FROM DUMMY;
modulus
-3
POWER
Syntax
POWER (b, e)
Description
Calculates the base number b raised to the power of an exponent e.
Example
SELECT POWER (2, 10) "power" FROM DUMMY;
power 1024.0
RAND
Syntax
DOUBLE RAND()
Description
Returns a pseudo-random value in the range of [0, 1.0). I ts return value type is DOUBLE.
Example
SAP HANA Database - SQL Reference Manual
49 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 50/193
SELECT RAND() FROM DUMMY;
RAND
3.907985046680551e-14
ROUND
Syntax
ROUND (n [, pos])
Description
Rounds argument n to the specified pos amount of places after the decimal point.
Example
SELECT ROUND (16.16, 1) "round" FROM DUMMY;
round
16.2
SELECT ROUND (16.16, -1) "round" FROM DUMMY;
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
SELECT SIGN (-15) "sign" FROM DUMMY;
sign
-1
SIN
Syntax
SIN (n)
Description
Returns the sine of n, where the argument is an angle expressed in radians.
Example
SELECT SIN ( 3.141592653589793/2) "sine" FROM DUMMY;
sine
1.0
SINH
Syntax
SINH (n)
SAP HANA Database - SQL Reference Manual
50 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 51/193
Description
Returns the hyperbolic sine of n, where the argument is an angle expressed in radians.
Example
SELECT SINH (0.0) "sinh" FROM DUMMY;
sinh
0.0
SQRT
Syntax
SQRT (n)
Description
Returns the square root of the argument n.
Example
SELECT SQRT (2) "sqrt" FROM DUMMY;
sqrt
1.4142135623730951
TAN
Syntax
TAN (n)
Description
Returns the tangent of n, where the argument is an angle expressed in radians.
Example
SELECT TAN (0.0) "tan" FROM DUMMY;
tan
0.0
TANH
Syntax
TANH (n)
Description
Returns the hyperbolic tangent of the numeric argument n.
Example
SELECT TANH (1.0) "tanh" FROM DUMMY;
tanh
0.7615941559557649
UMINUS
Syntax
UMINUS (n)
SAP HANA Database - SQL Reference Manual
51 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 52/193
Description
Returns the negated value of the numeric argument n.
Example
SELECT UMINUS(-765) "uminus" FROM DUMMY;
uminus
765
String Functions
ASCII
Syntax
ASCII(c)
Description
Returns the integer ASCII value of the first byte in a string c.
Example
SELECT ASCII('Ant') "ascii" FROM DUMMY;
ascii
65
CHAR
Syntax
CHAR (n)
Description
Returns the character with the ASCII value of a number n.
Example
SELECT CHAR (65) || CHAR (110) || CHAR (116) "character" FROM DUMMY;
character
Ant
CONCAT
Syntax
CONCAT (str1, str2)
Description
Returns a combined string consisting of str1 followed by str2. The concatenation operator (||) is identical to
this function.
Example
SELECT CONCAT ('C', 'at') "concat" FROM DUMMY;
concat
Cat
SAP HANA Database - SQL Reference Manual
52 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 53/193
LCASE
Syntax
LCASE(str)
Description
Converts all characters in string str to lowercase.
Note:
The LCASE function is identical to the LOWER function.
Example
SELECT LCASE ('TesT') "lcase" FROM DUMMY;
lcase
test
LEFT
Syntax
LEFT (str, n)
Description
Returns the first n characters/bytes from the beginning of string str.
Example
SELECT LEFT ('Hello', 3) "left" FROM DUMMY;
left
Hel
LENGTH
Syntax
LENGTH(str)
Description
Returns the number of characters in string str.
Note:
Supplementary plane Unicode characters, each of which occupies 6 bytes in CESU-8 encoding, are
counted as two characters.
Example
SELECT LENGTH ('length in char') "length" FROM DUMMY;
length
14
LOCATE
Syntax
LOCATE (haystack, needle)
Description
Returns the position of a substring needle within a string haystack. Returns 0 if needle is not found within
SAP HANA Database - SQL Reference Manual
53 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 54/193
haystack. Returns NULL if haystack or needle is NULL, or if haystack is an empty string.
Example
SELECT LOCATE ('length in char', 'char') "locate" FROM DUMMY;
Locate
11
SELECT LOCATE ('length in char', 'length') "locate" FROM DUMMY;
Locate
1
SELECT LOCATE ('length in char', 'zchar') "locate" FROM DUMMY;
Locate
0
LOWER
Syntax
LOWER(str)
Description
Converts all characters in string str to lowercase.
Note:
The LOWER function is identical to the LCASE function.
Example
SELECT LOWER ('AnT') "lower" FROM DUMMY;
lower
ant
LPAD
Syntax
LPAD (str, n [, pattern])
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
SELECT LPAD ('end', 15, '12345') "lpad" FROM DUMMY;
lpad
123451234512end
LTRIM
Syntax
LTRIM (str [, remove_set])
Description
Returns string str, t rimmed of all leading spaces. I f 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.
SAP HANA Database - SQL Reference Manual
54 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 55/193
Note:
remove_set is treated as a set of characters and not as a search string.
Example
SELECT LTRIM ('babababAabend','ab') "ltrim" FROM DUMMY;
ltrim
Aabend
NCHAR
Syntax
NCHAR (n)
Description
Returns the Unicode character with the integer code number n.
Example
SELECT NCHAR (65) "nchar" FROM DUMMY;
nchar
A
REPLACE
Syntax
REPLACE (original_string, search_string, replace_string)
Description
Searches in original_string for all occurrences of search_string and replaces them with replace_string.
If original_string is an empty string, then the result will be an empty string.
If two overlapping substrings match the search_string in the original_string, then only the first
occurrence will be replaced.
If original_string does not contain any occurrence of search_string, then original_string will be
returned unchanged.
If original_string, search_string, or replace_string are NULL then NULL is returned.
Example
SELECT REPLACE ('DOWNGRADE DOWNWARD','DOWN', 'UP') "replace" FROM DUMMY;
replace
UPGRADE UPWARD
RIGHT
Syntax
RIGHT(str, n)
Description
Returns the rightmost n characters/bytes of string str.
Example
SELECT RIGHT('HI0123456789', 3) "right" FROM DUMMY;
right
789
SAP HANA Database - SQL Reference Manual
55 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 56/193
RPAD
Syntax
RPAD (str, n [, pattern])
Description
Pads the end of string str with spaces to make a string of n characters in length. I f the pattern argument is
provided string str will be padded using sequences of these characters until the required length is met.
Example
SELECT RPAD ('end', 15, '12345') "right padded" FROM DUMMY;
right padded
end123451234512
RTRIM
Syntax
RTRIM (str [,remove_set ])
Description
Returns string str, t rimmed of all trailing spaces. If remove_set is specified, RTRI M 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
SELECT RTRIM ('endabAabbabab','ab') "rtrim" FROM DUMMY;
rtrim
endabA
SUBSTR_AFTER
Syntax
SUBSTR_AFTER (str, pattern)
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.
If pattern is an empty string, then str is returned.If str or pattern is NULL, then NULL is returned.
Example
SELECT SUBSTR_AFTER ('Hello My Friend','My ') "substr after" FROM DUMMY;
substr after
Friend
SUBSTR_BEFORE
Syntax
SUBSTR_BEFORE (str, pattern)
SAP HANA Database - SQL Reference Manual
56 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 57/193
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
SELECT SUBSTR_BEFORE ('Hello My Friend','My') "substr before" FROM DUMMY;
substr before
Hello
SUBSTRING
Syntax
SUBSTRING (str, start_position [, string_length])
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.
If start_position is less than 0, then it is considered as 1.
If string_length is less than 1, then an empty string is returned.
Example
SELECT SUBSTRING ('1234567890',4,2) "substring" FROM DUMMY;
substring
45
TRIM
Syntax
TRIM ([[LEADING | TRAILING | BOTH] trim_char FROM] str )
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.
If either str or trim_char are a null values, then a NULL is returned.
If no options are specified, TRIM removes both the leading and trailing substring trim_char from string
str.
If trim_char is not specified, then a single blank space is used.
Example
SELECT TRIM ('a' FROM 'aaa123456789aa') "trim both" FROM DUMMY;
trim both
123456789
SELECT TRIM (LEADING 'a' FROM 'aaa123456789aa') "trim leading" FROM DUMMY;
trim leading
123456789aa
UCASE
Syntax
UCASE (str)
SAP HANA Database - SQL Reference Manual
57 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 58/193
Description
Converts all characters in string str to uppercase.
Note:The UCASE function is identical to the UPPER function.
Example
SELECT UCASE ('Ant') "ucase" FROM DUMMY;
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
SELECT UNICODE ('#') "unicode" FROM DUMMY;
unicode
35
UPPER
Syntax
UPPER (str)
Description
Converts all characters in string str to uppercase.
Note:
The UPPER function is identical to the UCASE function.
Example
SELECT UPPER ('Ant') "uppercase" FROM DUMMY;
uppercase
ANT
Window Functions
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
SAP HANA Database - SQL Reference Manual
58 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 59/193
NULL.
Example
CREATE TABLE coalesce_example (ID INT PRIMARY KEY, A REAL, B REAL);
INSERT INTO coalesce_example VALUES(1, 100, 80);
INSERT INTO coalesce_example VALUES(2, NULL, 63);
INSERT INTO coalesce_example VALUES(3, NULL, NULL);
SELECT id, a, b, COALESCE (a, b*1.1, 50.0) "coalesce" FROM coalesce_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
Returns the id of the current connection.
Example
SELECT CURRENT_CONNECTION "current connection" FROM DUMMY;
current connection
2
CURRENT_SCHEMA
Syntax
CURRENT_SCHEMA
Description
Returns a string containing the current schema name.
Example
SELECT CURRENT_SCHEMA "current schema" FROM DUMMY;
current schema
SYSTEM
CURRENT_USER
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
-- example showing basic function operation using SYSTEM user
SELECT CURRENT_USER "current user" FROM DUMMY;
SAP HANA Database - SQL Reference Manual
59 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 60/193
current user
SYSTEM
-- definer-mode procedure declared by USER_A
CREATE PROCEDURE USER_A.PROC1 LANGUAGE SQLSCRIPT SQL SECURITY DEFINER AS
BEGIN
SELECT CURRENT_USER "current user" FROM DUMMY;
END;
-- USER_B executing USER_A.PROC1
CALL USER_A.PROC1;
current user
USER_A
-- invoker-mode procedure declared by USER_A
CREATE PROCEDURE USER_A.PROC2 LANGUAGE SQLSCRIPT SQL SECURITY INVOKER AS
BEGIN
SELECT CURRENT_USER "current user" FROM DUMMY;
END;
-- USER_B is executing USER_A.PROC
CALL USER_A.PROC2;
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 numberby 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 a s a binary number, this function returns an integer value as the output.
Example
SELECT customer, year, product, SUM(sales),
GROUPING_ID(customer, year, product)
FROM guided_navi_tab
GROUP BY GROUPING SETS (
(customer, year, product),
(customer, year),
(customer, product),
(year, product),
(customer),
(year),
(product));
CUSTOMER YEAR PRODUCT SUM(SALES) GROUPING_ID(CUSTOMER,YEAR,PRODUCT)
1 C1 2009 P1 100 0
2 C1 2010 P1 50 0
3 C2 2009 P1 200 0
4 C2 2010 P1 100 0
5 C1 2009 P2 200 0
6 C1 2010 P2 150 0
7 C2 2009 P2 300 0
8 C2 2010 P2 150 0
9 C1 2009 a 300 1
10 C1 2010 a 200 1
11 C2 2009 a 500 1
12 C2 2010 a 250 1
13 C1 a P1 150 2
14 C2 a P1 300 2
15 C1 a P2 350 2
16 C2 a P2 450 2
SAP HANA Database - SQL Reference Manual
60 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 61/193
17 a 2009 P1 300 4
18 a 2010 P1 150 4
19 a 2009 P2 500 4
20 a 2010 P2 300 4
21 C1 a a 500 3
22 C2 a a 750 3
23 a 2009 a 800 5
24 a 2010 a 450 5
25 a a P1 450 6
26 a a P2 800 6
IFNULL
Syntax
IFNULL (expression1, expression2)
Description
Returns the first not NULL input expression.
Returns expression1 if expression1 is not NULL.
Returns expression2 if expression1 is NULL.
Returns NULL if both input expressions are NULL.
Example
SELECT IFNULL ('diff', 'same') "ifnull" FROM DUMMY;
ifnull
diff
SELECT IFNULL (NULL, 'same') "ifnull" FROM DUMMY;
ifnull
same
SELECT IFNULL (NULL, NULL) "ifnull" FROM DUMMY;
ifnull
NULL
MAP
Syntax
MAP (expression, search1, result1 [, search2, result2] ... [, default_result])
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.
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;
SAP HANA Database - SQL Reference Manual
61 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 62/193
map
Default
SELECT MAP(99, 0, 'Zero', 1, 'One', 2, 'Two', 3, 'Three') "map" FROM DUMMY;
map
NULL
NULLIF
Syntax
NULLIF (expression1, expression2)
Description
NULLIF compares the values of two input expressions. If the first expression equals the second expression,
NULLIF returns NULL.
If expression1 does not equal expression2, NULLIF returns expression1.
If expression2 is NULL, NULLIF returns expression1.
Example
SELECT NULLIF ('diff', 'same') "nullif" FROM DUMMY;
nullif
diff
SELECT NULLIF('same', 'same') "nullif" FROM DUMMY;
nullif
NULL
SESSION_CONTEXT
Syntax
SESSION_CONTEXT(session_variable)
Description
Returns the value of session_variable assigned to the current user.
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>.
SESSION_CONTEXT returns an NVARCHAR with a maximum length of 512 characters.
Example
To read session variables use:
SELECT SESSION_CONTEXT('APPLICATION') "session context" FROM DUMMY;
session context
HDBStudio
SESSION_USER
Syntax
SESSION_USER
Description
SAP HANA Database - SQL Reference Manual
62 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 63/193
Returns the user name of the current session.
Example
-- example showing basic function operation using SYSTEM user
SELECT SESSION_USER "session user" FROM DUMMY;
session user
SYSTEM
-- definer-mode procedure declared by USER_A
CREATE PROCEDURE USER_A.PROC1 LANGUAGE SQLSCRIPT SQL SECURITY DEFINER AS
BEGIN
SELECT SESSION_USER "session user" FROM DUMMY;
END;
-- USER_B is executing USER_A.PROC
CALL USER_A.PROC1;
session user
USER_B
-- invoker-mode procedure declared by USER_A
CREATE PROCEDURE USER_A.PROC2 LANGUAGE SQLSCRIPT SQL SECURITY INVOKER AS BEGIN
SELECT SESSION_USER "session user" FROM DUMMY;
END;
-- USER_B is executing USER_A.PROC
CALL USER_A.PROC2;
session user
USER_B
SYSUUID
SYSUUID
SYSUUID
Description
Returns a new universally unique identifier, generated by the connected SAP HANA instance. Each call of
SYSUUID returns a new UUID value. SYSUUID ca lls from multiple connections are internally serialized to
guarantee unique value generation.
Example
SELECT SYSUUID FROM DUMMY;
SYSUUID
4DE3CD576C79511BE10000000A3C2220
SAP HANA Database - SQL Reference Manual
63 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 64/193
SQL Statements
This chapter describes the SQL statements that are supported by the SAP HANA Database.
Data Definition Statements
Data Manipulation Statements
System Management Statements
Session Management Statements
Transaction Management Statements
Access Control Statements
Data Import Export Statements
Procedural Statements
Data Definition Statements
ALTER AUDIT POLICY
Syntax
ALTER AUDIT POLICY <policy_name> <audit_mode>
Syntax Elements
<policy_name> ::= <identifier>
The name of the audit policy to be altered.
<audit_mode> ::= ENABLE | DISABLE
The audit mode enables or disables the audit policy.
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 with the system privilege AUDIT ADMIN are allowed to alter an audit policy. Users with
this privilege can alter any audit policy, regardless of if they are the creator of the policy.
When an audit policy is created, it is created in the disabled state. Therefore the audit policy has to be
enabled to make its audit actions take effect.
An audit policy can be disabled and enabled as often as required.
Configuration Parameters
The following configuration parameters for auditing are stored in global.ini, in the section auditing
configuration:
global_auditing_state ( 'true' / 'false' )
Regardless of the number of enabled audit policies, auditing will only occur if the global_auditing_state
configuration parameter is set to true. The default is 'false'.
default_audit_trail_type ( 'SYSLOGPROTOCOL' / 'CSVTEXTFILE' )
Specifies how auditing results will be stored.
SYSLOGPROTOCOL: uses the system syslog.
CSVTEXTFILE: stores audit information as comma-separated values in a text file.
SAP HANA Database - SQL Reference Manual
64 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 65/193
default_audit_trail_path
Specifies the file path where the CSVTEXTFILE should be stored.
The parameters above can be selected in the M_INIFILE_CONTENTS monitoring view if the user has therequired system privileges. The parameters can only be observed in a monitoring view when they have been
explicitly defined.
System Tables and Monitoring Views
AUDIT_POLICY: shows all audit policies and their states.
M_INIFILE_CONTENTS: shows the database system configuration parameters.
Only users with system privilege CATALOG READ, DATA ADMIN or INIFILE ADMI N can view the content of
the M_INIFILE_CONTENTS view. For a ll 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 PRIVILEGE, GRANT ROLE, REVOKE ROLE LEVEL CRITICAL;
Now you can enable this audit policy with:
ALTER AUDIT POLICY priv_audit ENABLE;
You can also disable the same audit policy with:
ALTER AUDIT POLICY priv_audit DISABLE;
ALTER FULLTEXT INDEX
Syntax
ALTER FULLTEXT INDEX <index_name> <alter_fulltext_index_option>
Syntax Elements
<index_name> ::= <identifier>
The identifier of the fulltext index to be altered.
<alter_fulltext_index_option> ::= <fulltext_parameter_list> | <queue_command> QUEUE
Specifies whether the parameters of the fulltext index or the state of the fulltext index queue should be
changed. The latter is only possible for an asynchronous explicit fulltext index.
<fulltext_parameter_list> ::= <fulltext_parameter> [{, <fulltext_parameter>} ...]
A list of fulltext index parameters that are to be changed.
<fulltext_parameter> ::= FUZZY SEARCH INDEX <on_off>
| PHRASE INDEX RATIO <index_ratio>
Fulltext index parameters.
FUZZY SEARCH INDEX <on_off>
<on_off> ::= ON | OFF
Defines if a fuzzy search index will be used. ON switches on the fuzzy seach index, and OFF turns the fuzzy
search index off.
PHRASE INDEX RATIO <index_ratio>
Specifies the phrase index ratio.
SAP HANA Database - SQL Reference Manual
65 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 66/193
<index_ratio> ::= <exact_numeric_literal>
Specifies the percentage of the phrase index ratio, the value used must be between 0.0 and 1.0
<queue_command> ::= FLUSH | SUSPEND | ACTIVATE
Specifies an action to be performed on the index queue.
FLUSH
Updates the fulltext index with the documents in the queue that have already been processed.
SUSPEND
Suspends the fulltext index processing queue.
ACTIVATE
Activates the fulltext index processing queue.
Description
The ALTER FULLTEXT I NDEX command either change the parameters of a fulltext index or the state of an
index processing queue. The queue is a mechanism used to enable a fulltext index to operate in asynchronous
manner, i.e. inserts will not block until a document is processed.
Examples
You create table T and then add two indices i1 and i2. Index i1 is a synchronous fulltext index, i2 is an
asynchronous fulltext index.
CREATE COLUMN TABLE T (c1 NVARCHAR(1000), c2 NVARCHAR(1000));
CREATE FULLTEXT INDEX i1 ON T (c1) SYNC;
CREATE FULLTEXT INDEX i2 ON T (c2) ASYNC;
You alter the phrase index to 30 percent and turn on the fuzzy search index for indexes i1 and i2.
ALTER FULLTEXT INDEX i1 PHRASE INDEX RATIO 0.3 FUZZY SEARCH INDEX ON; ALTER FULLTEXT INDEX i2 PHRASE INDEX RATIO 0.3 FUZZY SEARCH INDEX ON;
You suspend the queue for fulltext index i2.
ALTER FULLTEXT INDEX i2 SUSPEND QUEUE;
You update the fulltext index with the documents in the queue that have already been processed.
ALTER FULLTEXT INDEX i2 FLUSH QUEUE;
ALTER INDEX
Syntax
ALTER INDEX <index_name> REBUILD
Syntax Elements
<index_name>::= <identifier>
Specifies the name of the index to be rebuilt.
Description
The ALTER I NDEX statement rebuilds an index.
Example
You create table A and an index i on column b of table A.
SAP HANA Database - SQL Reference Manual
66 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 67/193
CREATE TABLE A (a INT, b NVARCHAR(10), c NVARCHAR(20));
CREATE INDEX i ON A(b);
You rebuild index i.
ALTER INDEX i REBUILD;
ALTER SEQUENCE
Syntax
ALTER SEQUENCE <sequence_name> [<restart_with>] [<parameter_list>] [RESET BY <reset
_by_subquery>]
Syntax Elements
<sequence_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
The name of the sequence to be altered with optional schema name.
<sequence_parameter_restart_with> ::= RESTART WITH <restart_value>
The starting value of the sequence. If you do not specify a value for the RESTART WITH clause, the current
value of the sequence is used.
<restart_value> ::= <unsigned_integer>
An integer value between 0 and 4611686018427387903 which will be the first value provided by the
sequence generator.
<parameter_list> ::= <sequence_parameter>[{, <sequence_parameter>}...]
Defines the paramter list.
<sequence_parameter>::= INCREMENT BY <increment_value>
| MAXVALUE <maximum_value>
| NO MAXVALUE
| MINVALUE <minimum_value>
| NO MINVALUE
| CYCLE
| NO CYCLE
A set of parameters that can be used with ALTER SEQUENCE. For parameter details see below.
INCREMENT BY <increment_value>
The sequence increment.
<increment_value> ::= <signed_integer>
An integer value which will be used to increment or decrement the sequence value.
MAXVALUE <maximum_value>
Defines the maximum value that can be generated by the sequence.
<maximum_value> ::= <unsigned_integer>
A positive integer which defines the maximum value generated by the sequence. The maximum value 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 <minimum_value>
SAP HANA Database - SQL Reference Manual
67 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 68/193
Defines the minimum value that can be generated by the sequence.
<minimum_value> ::= <unsigned_integer>
A positive integer which defines the minimum value generated by the sequence. The minimum value 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.
<reset_by_subquery> ::= <subquery>
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.
For details about subqueries please see Subquery
Description
The ALTER SEQUENCE statement is used to alter the parameters of a sequence generator.
Examples
Example 1
You create table A and a sequence seq. Sequence seq, when reset, will start from the value of the selectstatement shown.
CREATE TABLE A (a INT);
CREATE SEQUENCE seq RESET BY SELECT IFNULL(MAX(a), 0) + 1 FROM A;
You change the starting sequence value of sequence seq to 2.
ALTER SEQUENCE seq RESTART WITH 2;
You change the maximum value of sequence s to 100, and specify that it does not have a minimum value.
ALTER SEQUENCE seq MAXVALUE 100 NO MINVALUE;
You change the incremental value of sequence seq to 3, and specify that the sequence will not restart upon
reaching its maximum or minimum value.
ALTER SEQUENCE seq INCREMENT BY 3 NO CYCLE;
Example 2
You create table B, with column a. You create a sequence s1 with a reset-by subquery based on table B.
CREATE TABLE B (a INT);
CREATE SEQUENCE s1 RESET BY SELECT IFNULL(MAX(a), 0) + 1 FROM B;
You change the reset-by subquery of sequence s1 to the maximum value contained in column a of table B.
ALTER SEQUENCE s1 RESET BY SELECT MAX(a) FROM B;
ALTER TABLE
SAP HANA Database - SQL Reference Manual
68 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 69/193
Syntax
ALTER TABLE <table_name> [<add_column_clause>] [<drop_column_clause>] [<alter_colum
n_clause>] [<add_constraint_clause>]
[<drop_primary_key_clause>][<drop_constraint_clause>] [<pr
eload_clause>] [<table_conversion_clause>] [<move_clause>] [<add_range_partition_clause>] [<drop_rang
e_partition_clause>] [<partition_clause>]
[<persistent_merge_option>] [<delta_log_option>] [<auto_me
rge_option>] [<unload_priority>]
[<schema_flexibility_option>]
Syntax elements:
<table_name>
<add_column_clause>
<drop_column_clause>
<alter_column_clause>
<add_constraint_clause>
<drop_primary_key_clause>
<drop_constraint_clause>
<preload_clause>
<table_conversion_clause>
<add_range_partition_clause><drop_range_partition_clause>
<partition_clause>
<persistent_merge_option>
<delta_log_option>
<auto_merge_option>
<unload_priority>
<schema_flexibility_option>
Syntax Elements
<table_name>
<table_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
The identifier of the table to be altered, with optional schema name.
<add_column_clause>
<add_column_clause> ::= ADD ( {<column_definition> [<column_constraint>]} [{, <colu
mn_definition> [<column_constraint>]}...] )
Adds one or more columns to the specified table.
<drop_column_clause>
<drop_column_clause> ::= DROP ( <column_name>[{, <column_name>} ...] )
Removes one or more columns from the specified table.
<alter_column_clause>
<alter_column_clause> ::= ALTER ( <column_definition> [<column_constraint>] [{, <co
lumn_definition> [<column_constraint>]}...] )
Alters one or more column definitions.
Restrictions:
To prevent data loss, only increasing the size of a column data type is allowed. For example, changing
from nvarchar(20) to nvarchar(10) or from integer to tinyint will raise an error.
ALTER does not currently follow data type conversion rules.
Adding NOT NULL constraint to an existing column is allowed if either of the following cases are true:
The table is empty.
The default value is specified when the table contains data.
<column_definition> ::= <column_name> {<data_type> | <lob_data_type>} [<column_stor
e_data_type>] [<ddic_data_type>] [DEFAULT <default_value>]
SAP HANA Database - SQL Reference Manual
69 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 70/193
[GENERATED ALWAYS AS <expression>] [<schema_flexibility>] [
<fuzzy_search_index>] [<fuzzy_search_mode>]
Defines a table column.
<column_name> ::= <identifier>
The table column name.
<data_type> ::= DATE | TIME | SECONDDATE | TIMESTAMP | TINYINT | SMALLINT | INTEGER
| BIGINT | SMALLDECIMAL | DECIMAL
| REAL | DOUBLE | VARCHAR | NVARCHAR | ALPHANUM | SHORTTEXT | VARBINA
RY | TEXT
<lob_data_type> ::= <lob_type_name> [MEMORY THRESHOLD <memory_threshold_value>]
<lob_type_name> ::= BLOB | CLOB | NCLOB
<column_store_data_type> ::= CS_ALPHANUM | CS_INT | CS_FIXED | CS_FLOAT | CS_DOUBLE
| CS_DECIMAL_FLOAT | CS_FIXED(p-s, s)
| CS_SDFLOAT | CS_STRING | CS_UNITEDECFLOAT | CS_DATE |
CS_TIME | CS_FIXEDSTRING | CS_RAW
| CS_DAYDATE | CS_SECONDTIME | CS_LONGDATE | CS_SECONDDA
TE
<ddic_data_type> ::= DDIC_ACCP | DDIC_ALNM | DDIC_CHAR | DDIC_CDAY | DDIC_CLNT | DD
IC_CUKY | DDIC_CURR | DDIC_D16D
| DDIC_D34D | DDIC_D16R | DDIC_D34R | DDIC_D16S | DDIC_D34S | DD
IC_DATS | DDIC_DAY | DDIC_DEC
| DDIC_FLTP | DDIC_GUID | DDIC_INT1 | DDIC_INT2 | DDIC_INT4 | DD
IC_INT8 | DDIC_LANG | DDIC_LCHR
| DDIC_MIN | DDIC_MON | DDIC_LRAW | DDIC_NUMC | DDIC_PREC | DD
IC_QUAN | DDIC_RAW | DDIC_RSTR
| DDIC_SEC | DDIC_SRST | DDIC_SSTR | DDIC_STRG | DDIC_STXT | DD
IC_TIMS | DDIC_UNIT | DDIC_UTCM
| DDIC_UTCL | DDIC_UTCS | DDIC_TEXT | DDIC_VARC | DDIC_WEEK
The available data types. Please see Data Types.
<memory_threshold_value> ::= <unsigned_integer> | NULL
Controls if LOB data should be stored in memory or not according to the following conditions:
If <memory_threshold_value> is not provided, lob is stored in memory by default.
If <memory_threshold_value> is provided and its LOB size is bigger than memory threshold value, LOB
data is stored on disk.
If <memory_threshold_value> is provided and its LOB size is equal or less than memory threshold
value, LOB data is stored in memory.
If <memory_threshold_value> is NULL, all LOB data is stored in memory.
If <memory_threshold_value> is 0, all LOB data is stored in disk.
DEFAULT <default_value> ::= NULL | <string_literal> | <signed_numeric_literal> | <u
nsigned_numeric_literal>
Specifies a value to be assigned to the column if an INSERT statement does not provide a value for the column
GENERATED ALWAYS AS <expression>
Specifies the expression to generate the column value in runtime.
<schema_flexibility> ::= [ENABLE | DISABLE] SCHEMA FLEXIBILITY
Specifies the column is dynamic:
ENABLE produces a dynamic column.
DISABLE (default value) produces a stat ic column.
<fuzzy_search_index> ::= FUZZY SEARCH INDEX [ON | OFF]
Turns a fuzzy search index on or off. OFF is the default.
<fuzzy_search_mode> ::= FUZZY SEARCH MODE [<string_literal> | NULL]
Sets the fuzzy search mode with the value of <string_literal>. I f NULL is specified, the fuzzy search mode is
SAP HANA Database - SQL Reference Manual
70 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 71/193
reset.
<column_constraint> ::= NULL
| NOT NULL
| <unique_specification> | <references_specification>
The column constraint rules.
For NULL, NOT NULL and <unique_specification>, see below.
For <references_specification>, see References Specification
NULL
If NULL is specified it is not considered a constraint, it represents that a column that may contain a null value.
The default is NULL.
NOT NULL
The NOT NULL constraint prohibits a column value from being NULL.
<unique_specification> ::= UNIQUE [<unique_tree_type_index>] | PRIMARY KEY [<unique_tree_type_index>]
Specifies unique constraints. If the index type is omitted, the SAP HANA database chooses the appropriate
index by considering the column data type. If the index type is not specified, the SAP HANA database will
automatically select an index type as follows:
Index type Criteria
CPBTREE
- character string types.
- binary string types.
- decimal types.
- when the constraint i s a composite key.
- when the constraint i s a non-unique constraint
B TR EE A ll oth e r ca s e s th a n s p e ci fi e d f or CPB TR EE
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.
<unique_tree_type_index> ::= BTREE | CPBTREE;
Specifies the index type.
BTREE
BTREE specifies a B+-tree index. B+-tree is a tree that maintains sorted data which performs efficient
insertion, deletion and search of records.
CPBTREE
CPBTREE specifies a CPB+-tree index. CPB+-tree stands for Compressed Prefix B+-Tree, which is based on pkB-
tree. CPB+-tree is a very small index because it uses 'partial key' that is only part of full key in index nodes.
CPB+-tree shows better performance than B+-Tree for larger keys.
<add_constraint_clause>
<add_constraint_clause> ::= ADD [CONSTRAINT <constraint_name>] <table_constraint>
<constraint_name> ::= <identifier>
SAP HANA Database - SQL Reference Manual
71 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 72/193
Adds a table constraint.
<table_constraint> ::= <unique_constraint_definition> | <referential_constraint_def
inition>
The table constraint can be either a unique constraint or a referential constraint.
<unique_constraint_definition> ::= <unique_specification> (<unique_column_name_list
>)
The unique specification see Unique specifcation
<unique_column_name_list> ::= <unique_column_name>[{, <unique_column_name>}...]
Speicfies the unique column name list which can have one or more column names.
<unique_column_name> ::= <identifier>
A column name identifier.
<referential_constraint_definition> ::= FOREIGN KEY (<referencing_column_name_list>
) <references_specification>
Specifies a referential constraint.
<referencing_column_name_list> ::= <referencing_column_name>[{, <referencing_column
_name>}...]
Specifies the referencing column name list which can have one or more column names.
<referencing_column_name> ::= <identifier>
The identifier of a referencing column.
<references_specification> ::= REFERENCES <referenced_table> [(<referenced_column_n
ame_list>)] [<referential_triggered_action>]
Specifies the referenced table, with optional column name list and trigger act ion. If <referenced_column_name_list> is specified, there will be one-to-one correspondence between
<column_name> of <column_definition> (see column definition) and <referenced_column_name>. If it is not
specified, there will be one-to-one correspondence between <column_name> of <column_definition> and the
column name of the referenced table's primary key.
<referenced_column_name_list> ::= <referenced_column_name>[{, <referenced_column_na
me>}...]
Specifies the referenced column name list, which can have one or more column names.
<referenced_table> ::= <identifier>
The identifier of a table to be referenced.
<referenced_column_name> ::= <identifier>
The identifier of the column name to be referenced.
<referential_triggered_action> ::= <update_rule> [<delete_rule>]
| <delete_rule> [<update_rule>]
Specifies an update rule with optional delete rule or a delete rule with optional update rule. The order in
which they are provided provides an order of precedence for execution.
<update_rule> ::= ON UPDATE <referential_action>
<referential_action> ::= CASCADE | RESTRICT | SET DEFAULT | SET NULL
The following UPDATE referential actions are possible:
SAP HANA Database - SQL Reference Manual
72 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 73/193
Action
Name Update Action
RESTRICTAny updates to a referenced table are prohibited if there are any matched records in the
referencing table. This i s the defa ult action.
CASCADE If a record is updated in the referenced table, the corresponding records in the referencing tableare als o updated with the same values.
SET NULLIf a record is updated in the referenced table, the corresponding records in the referencing table
are als o updated with null values.
SET
DEFAULT
If a record is updated in the referenced table, the corresponding records in the referencing table
are als o updated with their default values
<delete_rule> ::= ON DELETE <referential_action>
The following D ELETE referential actions are possible:
Action
Name Delete Action
RESTRICTAny deletions to a referenced table are prohibited if there are any matched records in the
referencing table. This i s the defa ult action.
CASCADEIf a record in the referenced tabl e i s deleted, the corresponding records i n the referencing table
are also dele ted.
SET NULLIf a record in the referenced tabl e i s deleted, the corresponding records i n the referencing table
are set to null.
SET
DEFAULT
If a record in the referenced tabl e i s deleted, the corresponding records i n the referencing table
are set to their default values.
<drop_primary_key_clause>
<drop_primary_key_clause> ::= DROP PRIMARY KEY
Drops the primary key constraint.
<drop_constraint_clause>
<drop_constraint_clause> ::= DROP CONSTRAINT <constraint_name>
<constraint_name> ::= <identifier>
Drops a unique or referential constraint.
<preload_clause>
<preload_clause> ::= PRELOAD ALL | PRELOAD ( <column_name> ) | PRELOAD NONE
Sets or removes the preload flag of the given tables or columns.
When the preload flag is set 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 in the PRELOAD column. Possible
values are 'FULL', 'PARTIALLY ' and 'NO'. Also in system table TABLE_COLUMNS in column PRELOAD withpossible values being 'TRUE' or 'FALSE'.
PRELOAD ALL
Sets preload flags of all columns in the table.
PRELOAD ( <column_name> )
Sets the flags of the specified column.
PRELOAD NONE
Removes the preload flag from all columns.
<table_conversion_clause>
SAP HANA Database - SQL Reference Manual
73 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 74/193
<table_conversion_clause> ::= [ALTER TYPE] {ROW [THREADS <number_of_threads>] | COL
UMN [THREADS <number_of_threads> [BATCH <batch_size>]]}
Converts the table storage from ROW to COLUMN or from COLUMN to ROW.
ROW
Converts the table to ROW storage.
COLUMN
Converts the table to COUMN storage.
THREADS <number_of_threads>
<number_of_threads> ::= <unsigned_integer>
Specifies how many parallel execution threads should be used for the table conversion. The optimal value for
the number of threads is the number of available CPU cores. If THREADS is not provided the default value of
the number of CPU cores specified in the indexserver.ini file will be used.
BATCH <batch_size> <batch_size> ::= <unsigned_integer>
Specifies the number of rows to be inserted in a batch. If BATCH is not specified the default value of
2,000,000 will be used. Inserts into column tables will be immediately committed after every <batch_size>
records have been inserted. BATCH option can be used only when a table is converted from ROW to COLUMN
storage.
<move_clause>
<move_clause> ::= MOVE [PARTITION <partition_number>] TO <indexserver_host_port> [P
HYSICAL]
| MOVE [PARTITION <partition_number>] PHYSICAL
Moves a table to another location in a distributed environment.
PARTITION <partition_number>
<partition_number> ::= <unsigned_integer>
For partitioned tables, specifies the partition to be moved. If you attempt to move a partitioned table
without specifying a <partition_number> an error is returned.
<indexserver_host_port> ::= <unsigned_integer>
The internal indexserver port number where the table is to be moved.
PHYSICAL
Specifies that a column store tables persistence storage is moved immediately to the target host. If the
PHYSICAL option is not specified the table move will create a link inside the new host persistence pointing to
the old host persistence. The link will be removed on the next merge or upon execution of another move
operation not using the TO <indexserver_host_port> clause.
The PHYSICAL keyword is only for column store tables. Row store tables are always moved immediately.
<add_range_partition_clause>
<add_range_partition_clause> ::= ADD <range_partition_clause>
Adds a partition for tables partitioned with RANGE, HASH RANGE, ROUNDROBIN R ANGE.
<range_partition_clause> ::= {<from_to_spec> | <single_spec>} [, PARTITION OTHERS]
The range specifier for a new partition.
For syntax details please see partition range specifier below.
<drop_range_partition_clause>
SAP HANA Database - SQL Reference Manual
74 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 75/193
<drop_range_partition_clause> ::= DROP <range_partition_clause>
Drops a partition for tables partitioned with RANGE, HASH RANGE, ROUNDROBI N RANGE.
<partition_clause>
<partition_clause> ::= PARTITION BY <hash_partition> [, <range_partition> | , <hash
_partition>]
| PARTITION BY <range_partition>
| PARTITION BY <roundrobin_partition> [,<range_partition>]
The PARTITION BY option partitions a table using the selected rules.
For more information about partitioning please see the "Table Partitioning in the SAP HANA database"
section in the "SAP HANA Administration guide" available from the SAP HANA Appliance page.
<hash_partition> ::= HASH (<partition_expression> [{<partition_expression>,}...]) P
ARTITIONS {<num_partitions> | GET_NUM_SERVERS()}
Partitions the created table using a hash part itioning scheme.
<range_partition> ::= RANGE (<partition_expression>) (<range_spec>, ...)
Partitions the created table using a ra nge partitioning scheme.
<roundrobin_partition> ::= ROUNDROBIN PARTITIONS {<num_partitions> | GET_NUM_SERVER
S()} [, <range_partition>]
Partitions the created table using a round robin partitioning scheme.
GET_NUM_SERVERS()
Returns the number of servers available in the partitioning cluster.
<range_spec> ::= {<from_to_spec> | <single_spec>} [{{<from_to_spec> | <single_spec>
},} ...] [, PARTITION OTHERS]
The range specifier for a partition.
<from_to_spec> ::= PARTITION <lower_value> <= VALUES < <upper_value>
Specifies a partition using lower and upper values of a <partition_expression>.
<single_spec> ::= PARTITION VALUE = <target_value>
Specifies a partition using a single value of a <partition_expression>.
PARTITION OTHERS
Specifies that all other values that are not covered by the partition specification will be gathered into one
partition.
<partition_expression> ::= <column_name> | YEAR(<column_name>) | MONTH(<column_name
>)
The specifier used to segregate data into partitions.
<lower_value> ::= <string_literal> | <numeric_literal>
The lower value of a partition specifier.
<upper_value> ::= <string_literal> | <numeric_literal>
The upper value of a partition specifier.
<target_value> ::= <string_literal> | <numeric_literal>
The target value of a single partition specifier.
<num_partitions> ::= <unsigned_integer>
SAP HANA Database - SQL Reference Manual
75 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 76/193
The number of part itions to be created for the table.
<merge_partition_clause> ::= MERGE PARTITIONS
Merges all parts of a partitioned table into a non-partitioned table.
<persistent_merge_option>
<persistent_merge_option> ::= {ENABLE | DISABLE} PERSISTENT MERGE
Enables or disables persistent merging.
When enabled the merge-manager uses persistent merges for the given table. This is the default
behaviour.
When disabled the merge-manager uses main-memory merges instead of persistent merges for the
given table.
<delta_log_option>
<delta_log_option> ::= {ENABLE | DISABLE} DELTA LOG
Enables or disables delta logging for table.
After enabling, you have to perform a savepoint to be certain that a ll data is persisted. Also you have to
perform a data backup, otherwise it will not be possible to recover this data.
If logging is disabled, log entries will not be persisted for this table. Changes to this table will only be written
to the data store when a savepoint is carried out. This can cause loss of committed transaction should the
indexserver terminate. In the case of a termination, you have to truncate this table and insert all data again.
Note:
You should only use this option during initial load.
<auto_merge_option>
<auto_merge_option> ::= {ENABLE | DISABLE} AUTOMERGE
Enables or disables automatic delta merge on the specified table.
<unload_priority>
<unload_priority_option> ::= UNLOAD PRIORITY <unload_priority>
UNLOAD PRIORITY specifies that priority of table to be unloaded from memory.
<unload_priority> ::= <digit>
Sets the priority of table to be unloaded from memory. It can be 0 ~ 9, where 0 means not-unloadable and 9
means earliest unload.
<schema_flexibility_option>
<schema_flexibility_option> ::= {ENABLE | DISABLE} SCHEMA FLEXIBILITY
Enables or disables schema flexibility for the specified table.
Description
The ALTER TABLE statement changes the definition of a table.
Examples
You create Table t , and then alter default value of column b to 10.
CREATE TABLE t (a INT, b INT);
ALTER TABLE t ALTER (b INT DEFAULT 10);
You alter table t adding a new column c.
SAP HANA Database - SQL Reference Manual
76 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 77/193
ALTER TABLE t ADD (c NVARCHAR(10) DEFAULT 'NCHAR');
You create a primary key constraint, prim_key, on columns a and b of table t.
ALTER TABLE t ADD CONSTRAINT prim_key PRIMARY KEY (a, b);
You change the table type of table t to COLUMN storage.
ALTER TABLE t COLUMN;
You set the preload flags of column b and c on table t.
ALTER TABLE t PRELOAD (b, c);
You partition table t with a RANGE partit ion, and then add an additional partition.
ALTER TABLE t PARTITION BY RANGE (a) (PARTITION VALUE = 1, PARTITION OTHERS);
ALTER TABLE t ADD PARTITION 2 <= VALUES < 10;
You disable delta logging of table t.
ALTER TABLE t DISABLE DELTA LOG;
You change the unload priority of table t to 2:
ALTER TABLE t UNLOAD PRIORITY 2;
You create table R. Then you alter table R adding a unique constraint UK.
CREATE TABLE R (A INT PRIMARY KEY, B NVARCHAR(10));
ALTER TABLE R ADD CONSTRAINT UK UNIQUE (B);
You drop the unique constraint UK from table R.
ALTER TABLE R DROP CONSTRAINT UK;
You create table S. You add a referential constraint FK to table S that references column A of table R withdelete cascade option.
CREATE TABLE S (FA INT, B NVARCHAR(10));
ALTER TABLE S ADD CONSTRAINT FK FOREIGN KEY(FA) REFERENCES R(A) ON DELETE CASCADE;
You create t able T1 and t hen turn on the schema flexibility of the table. You t est the schema flexibility of
table T1 by inserting a new record. A new column F is automatically created a nd a record is inserted:
CREATE COLUMN TABLE T1 (C INT);
ALTER TABLE T1 ENABLE SCHEMA FLEXIBILITY;
INSERT INTO T1 (C, F) VALUES (1, 'NVAR1');
You create table T2 with a fuzzy search index and fuzzy search mode. You then switch off the fuzzy search
index of COL1 and finally reset fuzzy search mode of COL2.
CREATE COLUMN TABLE T2 (KEY INT, COL1 VARCHAR(10) FUZZY SEARCH INDEX ON, COL2 NVARC
HAR(10) FUZZY SEARCH MODE 'postcode');
ALTER TABLE T2 ALTER (COL1 VARCHAR(10) FUZZY SEARCH INDEX OFF);
ALTER TABLE T2 ALTER (COL2 NVARCHAR(10) FUZZY SEARCH MODE NULL);
CREATE AUDIT POLICY
Syntax
CREATE AUDIT POLICY <policy_name> AUDITING <audit_status_clause>
<audit_actions> LEVEL <audit_level>
Syntax Elements
<policy_name> ::= <identifier>
SAP HANA Database - SQL Reference Manual
77 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 78/193
The name of the audit policy to be created.
<audit_status_clause> ::= SUCCESSFUL | UNSUCCESSFUL | ALL
Defines whether successful, unsuccessful or all executions of the specified audit actions will be audited.
<audit_actions> ::= <actions_for_user_clause>
| <audit_action_list_clause>
| <target_audit_action_list_clause>
The audit actions for the audit policy.
<user_name> ::= <identifier>
The username of the user to be audited by the audit policy.
<actions_for_user_clause> ::= ACTIONS FOR <user_name>[{, <user_name>}...]
Audits actions for a user or a set of users.
<audit_action_list_clause> ::= <audit_action_list> [FOR <user_name>[{, <user_name>}
...] <audit_action_list> ::= <audit_action_name>[{, <audit_action_name>}...]
<audit_action_name> ::= GRANT PRIVILEGE | REVOKE PRIVILEGE
| GRANT STRUCTURED PRIVILEGE | REVOKE STRUCTURED PRIVI
LEGE
| GRANT APPLICATION PRIVILEGE | REVOKE APPLICATION PRIV
ILEGE
| 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 PRIVILE
GE
| ALTER STRUCTURED PRIVILEGE | CONNECT
| SYSTEM CONFIGURATION CHANGE | SET SYSTEM LICENSE
| UNSET SYSTEM LICENSE | ALTER USER
| REPOSITORY_ACTIVATE | DROP TABLE
Audits specific system actions, optionally limited to a user or a set of users. For more information on audit
actions see Audit Action Table.
<target_audit_action_list> ::= <target_audit_action_list> [FOR <user_name>[{, <user
_name>}...]
<target_audit_action_list> ::= <target_audit_action_name>[{, <target_audit_action_n
ame>}...] ON <object_name>[{, <object_name>}...]
<target_audit_action_name> ::= INSERT | UPDATE | DELETE | SELECT | EXECUTE
Audits actions on a database object or set of objects. Optionally this auditing can be limited to a user or a set
of users. Only objects of type table, view, and procedure can be specified in the <target_audit_action_list>.
Synonyms and sequences cannot be selected as objects for audit policies. Furthermore only these
<target_audit_action_name>s can be combined with an object. The following table shows an overview of
auditable actions on objects.
Action Table View Procedure
DELETE YES YES ---
INSERT YES YES ---
SELECT YES YES ---
UPDATE YES YES ---
EXECUTE --- --- YES
<object_name> ::= <table_name> | <view_name> | <procedure_name>
<table_name> ::= [<schema_name>.]<identifier>
<view_name> ::= [<schema_name>.]<identifier>
<procedure_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
Specifies a database object for the target audit action.
SAP HANA Database - SQL Reference Manual
78 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 79/193
<audit_level> ::= EMERGENCY | ALERT | CRITICAL | WARNING | INFO
Assigns an audit policy to an audit level. Possible levels, in decreasing order of importance, are:
EMERGENCY.ALERT.
CRITICAL.
WARNING.
INFO.
Description
The CREATE AUDIT POLICY statement creates a new audit policy. This audit policy can then be enabled and
will cause the auditing of the specified audit act ions to occur.
Only database users having the system privilege AUDIT ADMIN are allowed to create a n audit policy.
The specified audit policy name must be unique not match the name of an existing audit policy.
An audit policy defines which audit actions will be audited. Audit policies need to be enabled for auditing to
occur.
One audit policy can contain one of the following:
non-restricted auditing for n (>=1) usersauditing for actions not restricted to objects
auditing for actions which are restricted to objects.
For the last t wo alternatives listed, an optional restriction for user(s) is available.
For auditing to occur, audit policies have to be created and enabled. Also the configuration parameter
global_auditing_state (see below) has to be set to t rue.
Audit Actions
The table below contains the available audit actions. Each of the audit actions are in a specific group, audit
actions in the same group can be combined into one audit policy.
SAP HANA Database - SQL Reference Manual
79 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 80/193
Audit Action Name Group
Number Audit Operation Comment
GRANT PRIVILEGE 1 gra nti ng of pri vi leges to us ers or rol es
REVOKE PRI VI LEGE 1 re voki ng of pri vi le ge s from us ers or rol es
GRANT STRUCTUREDPRIVILEGE
1 granting of structured/analytical privileges tousers or roles
REVOKE STRUCTURED
PRIVILEGE1
revoking of structured/analytical privileges
from users or roles
GRANT APPLICATION
PRIVILEGE1
granting of appli cation privile ges to use rs or
roles
REVOKE APPLICATION
PRIVILEGE1
revoking of appl ication privileges from users
or roles
GRANT ROLE 1 granting of roles to us ers or roles
REVOKE ROLE 1 revoking of roles from users or roles
GRANT ANY 1granting of privileges, structured privileges or
roles to use rs or roles
REVOKE ANY 1revoking of privileges, structured privileges or
roles from users or roles
CREATE USER 2 creati on of users
DROP USER 2 dropping of users
ALTER USER 2 al teri ng of users
CREATE ROLE 2 creati on of roles
DROP ROLE 2 dropping of roles
CONNECT 3 creati on of a us er connection to the da tabase
SYSTEM
CONFIGURATION
CHANGE
4changes to the system configuration (e.g.
INIFILE)
ENABLE AUDI T POLI CY 5 a cti va ti on of a udi t pol ici es
DISABLE AUDIT
POLICY5 deactiva tion of audit pol i cies
CREATE STRUCTURED
PRIVILEGE6 cre ati on of s tru cture d/a na l yti ca l pri vi le ge s
DROP STRUCTURED
PRIVILEGE6 de structi on of structure d/a na l yti ca l pri vi le ge
ALTER STRUCTURED
PRIVILEGE6 cha nge of structure d/a na lyti ca l pri vi le ge
SET SYSTEM LICENSE 7 i ns ta ll ati on of a sys te m l icens e
UNSET SYSTEM
LICENSE7 deletion of l icenses
DROP TABLE 7 deletion of data ba se tables
REPOSITORY
ACTIVATE7 a cti va ti on o f re pos i tory de si gn ti me ob je cts
INSERT 7use of inse rt/repla ce/upsert statements on
tables and views
allows specification of
target objects
UPDATE 7use of update/replace/upsert statements on
tables and views
allows specification of
target objects
DELETE 7deletion of rows from tables/views a nd
truncation of tables
allows specification of
target objects
SELECT 7 us e of select statements on tables and viewsallows specification of
target objects
EXECUTE 7 procedure ca l lsallows specification of
target objects
ALL 7 al l actions a bovetypically used for
specific users
Configuration Parameter
Currently the configuration parameter for auditing are stored in g lobal.ini configuration file, in the auditing
configuration section.
global_auditing_state ( 'true' / 'false' )
Activates / deactivates auditing globally, regardless of the enabled state of the audit policies. The default is
SAP HANA Database - SQL Reference Manual
80 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 81/193
false, meaning: no auditing will occur.
default_audit_trail_type ( 'SYSLOGPROTOCOL' / 'CSVTEXTFILE' )
Specifies how to store the auditing results. SYSLOGPROTOCOL is the default.
CSVTEXTFILE should be used only for testing purposes.
default_audit_trail_path
Specifies the audit file storage location for the CSVTEXTFILE audit trail type.
As for all configuration parameters, these parameters can be selected in view M_INIFILE_CONTENTS,
assuming that the current user has the required privileges.
Note:
These parameters can only be seen if they have been explicitly set.
System and Monitoring Views
AUDIT_POLICY: shows all audit policies and their states
M_INIFILE_CONTENTS: shows the configuration parameter concerning auditing
Only database users with system privilege CATALOG READ, DATA ADMIN or INIFILE ADMI N can view
information in the M_INIFILE_CONTENTS view. For other database users this view will be empty.
Example
Your create a new audit policy named priv_audit that will audit successful granting and revoking of privileges
and roles. The 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
occur.
CREATE AUDIT POLICY priv_audit AUDITING SUCCESSFUL GRANT PRIVILEGE, REVOKE PRIVILEG
E, GRANT ROLE, REVOKE ROLE LEVEL CRITICAL;
You create a new audit policy named object_audit that will audit the inserts into the existing table
MY_SCHEMA.MY_TABLE. This policy has to be enabled explicity (see ALTER AUDIT POLICY) to make the
auditing of the audit policy occur. This policy is restricted to user FRED and uses the audit level INFO.
CREATE USER FRED PASSWORD Initial_1;
CREATE SCHEMA MY_SCHEMA OWNED BY system;
CREATE TABLE MY_SCHEMA.MY_TABLE (first_col int);
GRANT INSERT ON MY_SCHEMA.MY_TABLE to FRED;
CREATE AUDIT POLICY OBJECT_AUDIT AUDITING SUCCESSFUL INSERT ON MY_SCHEMA.MY_TABLE F
OR FRED LEVEL INFO
CREATE FULLTEXT INDEX
Syntax
CREATE FULLTEXT INDEX <index_name> ON <tableref> '(' <column_name> ')' [<fulltext_p
arameter_list>]
Syntax
<index_name> ::= <string_literal>
Specifies the name of the fulltext index.
<fulltext_parameter_list> ::= <fulltext_parameter> [, ...]
<fulltext_parameter> ::= LANGUAGE COLUMN <column_name>
| LANGUAGE DETECTION '(' <string_literal_list> ')'
| MIME TYPE COLUMN <column_name>
| <change_tracking_elem>
| FUZZY SEARCH INDEX <on_off>
| PHRASE INDEX RATIO <on_off>
| CONFIGURATION <string_literal>
| SEARCH ONLY <on_off>
| FAST PREPROCESS <on_off>
SAP HANA Database - SQL Reference Manual
81 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 82/193
<on_off> ::= ON | OFF
LANGUAGE COLUMN
Column where the language of a document is specified.
LANGUAGE DETECTIONSet of languages to be considered for language detection.
MIME TYPE COLUMN
Column where the mime-type of a document is specified.
FUZZY SEARCH INDEX
Specifies whether the fuzzy search index should be used.
PHRASE INDEX RATIO
Specifies the percentage of the phrase index. Value must be between 0.0 and 1.0
CONFIGURATION
Path to a custom configuration file for text analysis.
SEARCH ONLY
If set to ON the original document content is not stored.
FAST PREPROCESS
If set to ON, fast preprocessing is used, i.e. linguistic searches are not possible.
<change_tracking_elem> ::= SYNC[HRONOUS]
| ASYNC[HRONOUS] [FLUSH [QUEUE] <flush_queue_elem>]
SYNC
If specified a synchronous fulltext index is created.
ASYNC
If specified an asynchronous fulltext index is created.
<flush_queue_elem> ::= EVERY <integer_literal> MINUTES
| AFTER <integer_literal> DOCUMENTS
| EVERY <integer_literal> MINUTES OR AFTER <int
eger_literal> DOCUMENTS
Specifies when to update the fulltext index if an asynchronous index is used.
Description
The CREATE FULLTEXT INDEX statement creates an explicit fulltext index on the given table column.
Example
You create table A.
CREATE COLUMN TABLE A (A VARCHAR(10) PRIMARY KEY, B VARCHAR(10));
You create synchronous fulltext index named 'i'. Index i is on column 'A' of table 'A', where the fuzzy search
index is not used and the set of languages for language detection consists of 'EN','DE' and 'KR'.
CREATE FULLTEXT INDEX i ON A(A) FUZZY SEARCH INDEX OFFSYNC
LANGUAGE DETECTION ('EN','DE','KR')
CREATE INDEX
Syntax
CREATE [UNIQUE] [BTREE | CPBTREE] INDEX <index_name> ON <table_name> (<column_name_
order>, ...) [ASC | DESC]
Syntax Elements
<index_name> ::= [<schema_name>.]<identifier>
<column_name_order> ::= <column_name> [ASC | DESC]
SAP HANA Database - SQL Reference Manual
82 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 83/193
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.
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.
B+-tree is a tree which maintains sorted data that performs efficient insertion, deletion and search of
records.
CPB+-tree stands for Compressed Prefix B+-Tree, which is based on pkB-tree. CPB+-tree is a very small index
because it uses 'partial key' that is only part of full key in index nodes. CPB+-tree shows better performance
than B+-Tree for larger keys.
When column data types are character string types, binary string types, decimal types, or when the
constraint is a composite key, or a non-unique constraint, the default index type is CPBTREE; otherwise,
BTREE is used.
If neither BTREE nor CPBTREE keyword is specified, then SAP HANA database chooses the appropriate index
type.
ASC | DESC
Specifies whether the index should be created in ascending or descending order.These keywords can be only used in the btree index, and can be specified only once for each column.
Description
The CREATE INDEX statement creates an index.
Example
Table t is created, then CPBTREE index idx is created on column b of table t with ascending order:
CREATE TABLE t (a INT, b NVARCHAR(10), c NVARCHAR(20));
CREATE INDEX idx ON t(b);
CPBTREE index idx1 is created on column a of table t with ascending order and column b with desceding
order:
CREATE CPBTREE INDEX idx1 ON t(a, b DESC);
CPBTREE index idx2 is created on column a and c of table t with desceding order:
CREATE INDEX idx2 ON t(a, c) DESC;
UNIQUE CPBTREE index idx3 is created on column b and c of table t with ascending order:
CREATE UNIQUE INDEX idx3 ON t(b, c);
UNIQUE BTREE index idx4 is created on column a of table t with ascending order:
CREATE UNIQUE INDEX idx4 ON t(a);
CREATE SCHEMA
Syntax
CREATE SCHEMA <schema_name> [OWNED BY <user_name>]
Syntax Elements
<schema_name> ::= <identifier>
<user_name> ::= <simple_identifier>
OWNED BY
Specifies the name of the schema owner. If omitted, the current user will be the owner of the schema.
Description
The CREATE SCHEMA statement creates a schema in the current database.
SAP HANA Database - SQL Reference Manual
83 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 84/193
Example
CREATE SCHEMA my_schema OWNED BY system;
CREATE SEQUENCE
Syntax
CREATE SEQUENCE <sequence_name> [<common_sequence_parameter_list>] [RESET BY <subqu
ery>]
Syntax Elements
<sequence_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
<common_sequence_parameter_list> ::= <common_sequence_parameter>, ...
<common_sequence_parameter> ::= <sequence_parameter_start_with>
| <basic_sequence_parameter>
<basic_sequence_parameter> ::= INCREMENT BY n | MAXVALUE n
| NO MAXVALUE
| MINVALUE n
| NO MINVALUE
| CYCLE
| NO CYCLE
<sequence_parameter_start_with> ::= START WITH n
INCREMENT BY
Defines the amount the next sequence value is incremented from the last value assigned. The default is 1.
Specify a negative value to generate a descending sequence. An error is returned if the INCREMENT BY value
is 0
START WITH
Defines the starting sequence value. If you do not specify a value for the START WITH clause, MINVALUE is
used for ascending sequences and MAXVALUE is used for descending sequences.
MAXVALUEDefines 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
The CREATE SEQUENCE statement is used to create a sequence.
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.
SAP HANA Database - SQL Reference Manual
84 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 85/193
Example
Example 1:
Sequence seq is created, then CURRVAL and NEXTVAL are used to get the values from the sequence:
CREATE SEQUENCE seq START WITH 11;
NEXTVAL returns 11:
SELECT seq.NEXTVAL FROM DUMMY;
CURRVAL returns 11:
SELECT seq.CURRVAL FROM DUMMY;
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 TABLE r (a INT);
CREATE SEQUENCE s RESET BY SELECT IFNULL(MAX(a), 0) + 1 FROM r;
SELECT s.NEXTVAL FROM DUMMY;
CREATE SYNONYM
Syntax
CREATE [PUBLIC] SYNONYM <synonym_name> FOR <object_name>
Syntax Elements
<synonym_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
The name of the synonym to be created, with optional schema name.
<object_name> ::= <table_name>
| <view_name>
| <procedure_name>
| <sequence_name>
<table_name> ::= [<schema_name>.]<identifier>
<view_name> ::= [<schema_name>.]<identifier>
<sequence_name> ::= [<schema_name>.]<identifier>
<procedure_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
Description
The CREATE SYNONYM creates an a lternate 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 sequenceswithout needing to re-write the function or stored procedure.
The optional PUBLIC element allows for the creation of a public synonym. A public synonym can be accessed
by any users, but the users that have proper privilege on its base object can access the base object.
Example
You create table A.
CREATE TABLE A (A INT PRIMARY KEY, B INT);
You create a synonym for table A, a_synonym.
CREATE SYNONYM a_synonym FOR A;
SAP HANA Database - SQL Reference Manual
85 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 86/193
CREATE TABLE
Syntax
CREATE [<table_type>] TABLE <table_name> <table_contents_source> [<logging_option>] [<auto_merge_option>]
[<unload_priority_clause>] [<schema_flexibility_option>] [<partition_clause>
] [<location_clause>]
Syntax elements:
<table_type>
<table_contents_source>
<logging_option>
<auto_merge_option>
<unload_priority_clause>
<schema_flexibility_option>
<partition_clause>
<location_clause>
Syntax Elements
<table_type>
<table_type> ::= COLUMN
| ROW
| HISTORY COLUMN
| GLOBAL TEMPORARY
| LOCAL TEMPORARY
Defines the type of table storage organization. The default value is ROW.
ROW, COLUMN
If the majority of table access will be through a large number of tuples, with only a few selected attributes,
COLUMN-based storage should be used. If the majority of table access involves selecting a few records, with
all att ributes selected, ROW-based storage is preferable. The SAP HANA database uses a combination of
table types to enable storage and interpretation in both ROW and COLUMN forms.
HISTORY COLUMN
Creates a table with a particular t ransaction session type called 'HISTORY'. Tables with session type HISTORY
support time travel queries. Time travel queries are queries against historical states of the database.
For more information on utilizing history time travel please see: HISTORY time travel
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 g lobal 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 sessionis terminated. Global temporary table can be dropped only when the table does not have any record in it.
Supported operations on Global Temporary Table:
1. Create without a primary key
2. Rename table
3. Rename column
4. Truncate
5. Drop
6. Create or Drop view on top of global temporary table
7. Create synonym
8. Select
9. Select into or Insert
10. Delete
11. Update
12. Upsert or Replace
SAP HANA Database - SQL Reference Manual
86 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 87/193
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 a llowed 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.
Supported operations on Local Temporary Table:
1. Create without a primary key
2. Truncate
3. Drop
4. Select
5. Select into or Insert
6. Delete
7. Update
8. Upsert or Replace
<table_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
For descriptions on schema name and identifier, please refer to Identifiers.
<table_contents_source>
<table_contents_source> ::= (<table_element>, ...)
| <like_table_clause>
| [(<column_name>, ...)] <as_table_subquery>
You can create a table in the following ways:
Describing the table elements, see below.
Basing the new table like an existing table, see CREATE TABLE LIKE.
From the result of a subquery, see CREATE TABLE AS <subquery>.
<table_element> ::= <column_definition> [<column_constraint>] | <table_constraint>
Defines a table column with associated column or table constraint.
For column constraint please see column constraint.
For table constraint please see table constraint.
<column_definition> ::= <column_name> {<data_type> | <lob_data_type>} [<column_stor
e_data_type>] [<ddic_data_type>] [DEFAULT <default_value>]
[GENERATED ALWAYS AS <expression>] [<schema_flexibility>] [
<fuzzy_search_index>] [<fuzzy_search_mode>]
Defines a table column.
<column_name> ::= <identifier>
The table column name.
<data_type> ::= DATE | TIME | SECONDDATE | TIMESTAMP | TINYINT | SMALLINT | INTEGER
| BIGINT | SMALLDECIMAL | DECIMAL
| REAL | DOUBLE | VARCHAR | NVARCHAR | ALPHANUM | SHORTTEXT | VARBINA
RY | TEXT
<lob_data_type> ::= <lob_type_name> [MEMORY THRESHOLD <memory_threshold_value>]
<lob_type_name> ::= BLOB | CLOB | NCLOB
<column_store_data_type> ::= CS_ALPHANUM | CS_INT | CS_FIXED | CS_FLOAT | CS_DOUBLE
| CS_DECIMAL_FLOAT | CS_FIXED(p-s, s)
| CS_SDFLOAT | CS_STRING | CS_UNITEDECFLOAT | CS_DATE |
CS_TIME | CS_FIXEDSTRING | CS_RAW
| CS_DAYDATE | CS_SECONDTIME | CS_LONGDATE | CS_SECONDDA
TE
<ddic_data_type> ::= DDIC_ACCP | DDIC_ALNM | DDIC_CHAR | DDIC_CDAY | DDIC_CLNT | DD
SAP HANA Database - SQL Reference Manual
87 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 88/193
IC_CUKY | DDIC_CURR | DDIC_D16D
| DDIC_D34D | DDIC_D16R | DDIC_D34R | DDIC_D16S | DDIC_D34S | DD
IC_DATS | DDIC_DAY | DDIC_DEC
| DDIC_FLTP | DDIC_GUID | DDIC_INT1 | DDIC_INT2 | DDIC_INT4 | DD
IC_INT8 | DDIC_LANG | DDIC_LCHR
| DDIC_MIN | DDIC_MON | DDIC_LRAW | DDIC_NUMC | DDIC_PREC | DD
IC_QUAN | DDIC_RAW | DDIC_RSTR
| DDIC_SEC | DDIC_SRST | DDIC_SSTR | DDIC_STRG | DDIC_STXT | DD
IC_TIMS | DDIC_UNIT | DDIC_UTCM
| DDIC_UTCL | DDIC_UTCS | DDIC_TEXT | DDIC_VARC | DDIC_WEEK
The available data types. Please see Data Types.
<memory_threshold_value> ::= <unsigned_integer> | NULL
Controls if LOB data should be stored in memory or not according to the following conditions:
If <memory_threshold_value> is not provided, lob is stored in memory by default.
If <memory_threshold_value> is provided and its LOB size is bigger than memory threshold value, LOB
data is stored on disk.
If <memory_threshold_value> is provided and its LOB size is equal or less than memory threshold
value, LOB data is stored in memory.
If <memory_threshold_value> is NULL, all LOB data is stored in memory.
If <memory_threshold_value> is 0, all LOB data is stored in disk.
DEFAULT <default_value> ::= NULL | <string_literal> | <signed_numeric_literal> | <u
nsigned_numeric_literal>
Specifies a value to be assigned to the column if an INSERT statement does not provide a value for the
column.
GENERATED ALWAYS AS <expression>
Specifies the expression to generate the column value in runtime.
LOB DATA TYPE in column definition
Avaliable lob data types are BLOB, CLOB and NCLOB.
If MEMORY THRESHOLD option is not given, lob is stored in memory as default.
If MEMORY THRESHOLD is given and its LOB size is bigger than memory threshold value, LOB data is stored
in disk. If MEMORY THRESHOLD is given and its LOB size is equal or less than memory threshold value, LOBdata is stored in memory. If memory threshold is NULL, all LOB data is stored in memory. If memory
threshold is 0, all LOB data is stored in disk.
<schema_flexibility> ::= {ENABLE | DISABLE} SCHEMA FLEXIBILITY
Specifies the column is dynamic:
ENABLE produces a dynamic column.
DISABLE (default value) produces a stat ic column.
<fuzzy_search_index> ::= FUZZY SEARCH INDEX {ON | OFF}
Turns a fuzzy search index on or off. OFF is the default.
<fuzzy_search_mode> ::= FUZZY SEARCH MODE [<string_literal> | NULL]
Sets the fuzzy search mode with the value of <string_literal>. I f NULL is specified, the fuzzy search mode is
reset.
<column_constraint> ::= NULL
| NOT NULL
| <unique_specification>
| <references_specification>
The column constraint rules.
For NULL, NOT NULL and <unique_specification>, see below.
For <references_specification>, see References Specification
NULL
If NULL is specified it is not considered a constraint, it represents that a column that may contain a null value.
SAP HANA Database - SQL Reference Manual
88 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 89/193
The default is NULL.
NOT NULL
The NOT NULL constraint prohibits a column value from being NULL.
<unique_specification> ::= UNIQUE [<unique_tree_type_index>]
| PRIMARY KEY [<unique_tree_type_index>]
Specifies unique constraints. If the index type is omitted, the SAP HANA database chooses the appropriate
index by considering the column data type. If the index type is not specified, the SAP HANA database will
automatically select an index type as follows:
Index type Criteria
CPBTREE
- character string types.
- binary string types.
- decimal types.
- when the constraint i s a composite key.
- when the constraint i s a non-unique constraint
B TR EE A ll oth e r ca s e s th a n s p e ci fi e d f or CPB TR EE
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.
<unique_tree_type_index> ::= BTREE | CPBTREE;
Specifies the index type.
BTREE
BTREE specifies a B+-tree index. B+-tree is a tree that maintains sorted data which performs efficient
insertion, deletion and search of records.
CPBTREE
CPBTREE specifies a CPB+-tree index. CPB+-tree stands for Compressed Prefix B+-Tree, which is based on pkB-
tree. CPB+-tree is a very small index because it uses 'partial key' that is only part of full key in index nodes.
CPB+-tree shows better performance than B+-Tree for larger keys.
<table_constraint> ::= <unique_constraint_definition> | <referential_constraint_def
inition>
The table constraint can be either a unique constraint or a referential constraint.
<unique_constraint_definition> ::= <unique_specification> (<unique_column_name_list>)
The unique specification see Unique specifcation
<unique_column_name_list> ::= <unique_column_name>[{, <unique_column_name>}...]
Speicfies the unique column name list which can have one or more column names.
<unique_column_name> ::= <identifier>
A column name identifier.
<referential_constraint_definition> ::= FOREIGN KEY (<referencing_column_name_list>
) <references_specification>
Specifies a referential constraint.
SAP HANA Database - SQL Reference Manual
89 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 90/193
<referencing_column_name_list> ::= <referencing_column_name>[{, <referencing_column
_name>}...]
Specifies the referencing column name list which can have one or more column names.
<referencing_column_name> ::= <identifier>
The identifier of a referencing column.
<references_specification> ::= REFERENCES <referenced_table> [(<referenced_column_n
ame_list>)] [<referential_triggered_action>]
Specifies the referenced table, with optional column name list and trigger act ion. If
<referenced_column_name_list> is specified, there will be one-to-one correspondence between
<column_name> of <column_definition> (see column defintion) and <referenced_column_name>. If it is not
specified, there will be one-to-one correspondence between <column_name> of <column_definition> and the
column name of the referenced table's primary key.
<referenced_column_name_list> ::= <referenced_column_name>[{, <referenced_column_na
me>}...]
Specifies the referenced column name list, which can have one or more column names.
<referenced_table> ::= <identifier>
The indentifier of a table to be referenced.
<referenced_column_name> ::= <identifier>
The identifier of the column name to be referenced.
<referential_triggered_action> ::= <update_rule> [<delete_rule>]
| <delete_rule> [<update_rule>]
Specifies an update rule with optional delete rule or a delete rule with optional update rule. The order in
which they are provided provides an order of precedence for execution.
<update_rule> ::= ON UPDATE <referential_action>
<referential_action> ::= CASCADE | RESTRICT | SET DEFAULT | SET NULL
The following UPDATE referential actions are possible:
Action
Name Update Action
RESTRICTAny updates to a referenced table are prohibited if there are any matched records in the
referencing table. This i s the defa ult action.
CASCADEIf a record is updated in the referenced table, the corresponding records in the referencing table
are als o updated with the same values.
SET NULLIf a record is updated in the referenced table, the corresponding records in the referencing table
are als o updated with null values.
SET
DEFAULT
If a record is updated in the referenced table, the corresponding records in the referencing table
are als o updated with their default values
<delete_rule> ::= ON DELETE <referential_action>
The following D ELETE referential actions are possible:
SAP HANA Database - SQL Reference Manual
90 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 91/193
Action
Name Delete Action
RESTRICTAny deletions to a referenced table are prohibited if there are any matched records in the
referencing table. This i s the defa ult action.
CASCADE If a record in the referenced tabl e i s deleted, the corresponding records i n the referencing tableare also dele ted.
SET NULLIf a record in the referenced tabl e i s deleted, the corresponding records i n the referencing table
are set to null.
SET
DEFAULT
If a record in the referenced tabl e i s deleted, the corresponding records i n the referencing table
are set to their default values.
<like_table_clause> ::= LIKE <like_table_name> [WITH [NO] DATA] [<like_without_opti
on>]
Creates a table that has the same definition as like_table_name, unless corresponding property or WITHOUT
option is specified. All the column definitions with constraints, default values and other properties such as
generated column, schema flexibility, etc are copied from the table <like_table_name>. All table constraints,
indexes, fulltext indexes and table location are also copied.
<like_table_name> ::= <table_name>
<table_name> ::= <identifier>
The identifier of the table that will be duplicated.
WITH [NO] DATA
The WITH D ATA option specifies that data is copied from the <like_table_name> table. The default value of
WITH NO DATA does not copy the table data .
<like_without_option> ::= WITHOUT AUTO MERGE | WITHOUT HISTORY | WITHOUT NO LOGGING
| WITHOUT PARTITION | WITHOUT SCHEMA FLEXIBILITY
| WITHOUT UNLOAD | WITHOUT PRELOAD | WITHOUT UNLOAD PRIORIT
Y | WITHOUT INDEX | WITHOUT FUZZY SEARCH INDEX
| WITHOUT FUZZY SEARCH MODE
Specifies which properties will not be copied from the <like_table_name> table. For example when WITHOUT
PARTITION is specified, the t able will not be partitioned.
<as_table_subquery> ::= AS (<subquery>) [WITH [NO] DATA]
Creates a table and fills it with the data computed by the <subquery> (See sql_subquery). Only NOT NULL
constraints are copied by this clause. If column_names are specified, specified column_names override the
column names from <subquery>.
WITH [NO] DATA
The WITH DATA option specifies that data is copied from <subquery>. The default is WITH DATA. WITH NO
DATA option does not copy the data from <subquery>.
<logging_option>
<logging_option> ::= LOGGING
| NO LOGGING [RETENTION <retention_period>]
Specifies logging options for the created table.
LOGGING
Specifies that ta ble logging is activated. This is the default logging option.
NO LOGGING
Specifies that logging is deactivated. A NO LOGGING table means that the definition of the table is persistent
SAP HANA Database - SQL Reference Manual
91 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 92/193
and globally available, data is temporary and global.
RETENTION <retention_period>
<retention_period> ::= <unsigned_integer>
Specifies the retention time in seconds of the column table created by NO LOGGING. After the specifiedretention period has elapsed, the table will be dropped if used physical memory of the host is above 80%.
<auto_merge_option>
<auto_merge_option> ::= [NO] AUTO MERGE
AUTO MERGE (default value) specifies that a utomatic delta merge is trigg ered. NO AUTO MERGE disables
automatic delta merging.
<unload_priority_clause>
<unload_priority_clause> ::= UNLOAD PRIORITY <unload_priority>
UNLOAD PRIORITY specifies that priority of table to be unloaded from memory.
<unload_priority> ::= <digit>
<unload_priority> can be 0 ~ 9, where 0 means not-unloadable and 9 means earliest unload.
<schema_flexibility_option>
<schema_flexibility_option> ::= WITH SCHEMA FLEXIBILITY
Specifies that the table schema is flexible.
<partition_clause>
<partition_clause> ::= PARTITION BY <hash_partition> [, <range_partition> | , <hash
_partition>]
| PARTITION BY <range_partition>
| PARTITION BY <roundrobin_partition> [,<range_partition>]
The PARTITION BY option partitions a table using the selected rules.
For more information about partitioning please see the "Table Partitioning in the SAP HANA database"
section in the "SAP HANA Administration guide" available from the SAP HANA Appliance page.
<hash_partition> ::= HASH (<partition_expression> [{<partition_expression>,}...]) P
ARTITIONS {<num_partitions> | GET_NUM_SERVERS()}
Partitions the created table using a hash part itioning scheme.
<range_partition> ::= RANGE (<partition_expression>) (<range_spec>, ...)
Partitions the created table using a ra nge partitioning scheme.
<roundrobin_partition> ::= ROUNDROBIN PARTITIONS {<num_partitions> | GET_NUM_SERVER
S()} [, <range_partition>]
Partitions the created table using a round robin partitioning scheme.
GET_NUM_SERVERS()
Returns the number of servers available in the partitioning cluster.
<range_spec> ::= {<from_to_spec> | <single_spec>} [{{<from_to_spec> | <single_spec>
},} ...] [, PARTITION OTHERS]
The range specifier for a partition.
<from_to_spec> ::= PARTITION <lower_value> <= VALUES < <upper_value>
Specifies a partition using lower and upper values of a <partition_expression>.
SAP HANA Database - SQL Reference Manual
92 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 93/193
<single_spec> ::= PARTITION VALUE = <target_value>
Specifies a partition using a single value of a <partition_expression>.
PARTITION OTHERS
Specifies that all other values that are not covered by the partition specification will be gathered into one
partition.
<partition_expression> ::= <column_name> | YEAR(<column_name>) | MONTH(<column_name
>)
The specifier used to segregate data into partitions.
<lower_value> ::= <string_literal> | <numeric_literal>
The lower value of a partition specifier.
<upper_value> ::= <string_literal> | <numeric_literal>
The upper value of a partition specifier.
<target_value> ::= <string_literal> | <numeric_literal>
The target value of a single partition specifier.
<num_partitions> ::= <unsigned_integer>
The number of part itions to be created for the table.
<location_clause>
<location_clause> ::= AT [LOCATION] {'<host>:<port>' | ('<host>:<port>', ...)}
<host> ::= <string_literal>
<port> ::= <unsigned_integer>
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 scheme. Duplicates in the list will beremoved. 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 part itions 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 will be distributed across all servers evenly. 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 relationship to each other.
A table can be created in the specified location with <host>:<port>. <location_clause> can be specified when
creating partitioned tables that are distributed on multiple instances. When <location_clause> is provided
without <partition_clause>, the table is created on the first locat ion 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 along with the WITH DATA option.
Examples
You create Table A that has I NTEGER-type column A and B. Column A has a primary key constraint.
CREATE TABLE A (A INT PRIMARY KEY, B INT);
You create a partitioned table P1 that has DATE-type column U. Column U has a primary key constraint and is
used as RANGE-partitioning column.
CREATE COLUMN TABLE P1 (U DATE PRIMARY KEY) PARTITION BY RANGE (U) (PARTITION '2010
SAP HANA Database - SQL Reference Manual
93 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 94/193
-02-03' <= VALUES < '2011-01-01', PARTITION VALUE = '2011-05-01');
You create a partitioned table P2 that has INTEGER-type column I, J and K. Column I and J make the primary
key constraint and are used as HASH-partitioning column. Column K is used as a sub HASH-partitioning
column.
CREATE COLUMN TABLE P2 (I INT, J INT, K INT, PRIMARY KEY(I, J)) PARTITION BY HASH (
I, J) PARTITIONS 2, HASH (K) PARTITIONS 2;
You create table C1 that has the same definition as table A. Table C1 also has the same records as table A.
CREATE COLUMN TABLE C1 LIKE A WITH DATA;
You create table H1 that has the same definition as table H. Table H1 also has the same records as table H.
You create a column table H2 from the definition of table H without history property and without any
records.
CREATE HISTORY COLUMN TABLE H (A INT);
CREATE TABLE H1 LIKE H WITH DATA;
CREATE TABLE H2 LIKE H WITH NO DATA WITHOUT HISTORY;
You create table C2 that has the same column data type and NOT NULL constraint as table A without anydata.
CREATE TABLE C2 AS (SELECT * FROM A) WITH NO DATA;
You create table F that has a foreign key that references column A of table R with update cascade option.
CREATE TABLE R (A INT PRIMARY KEY, B NVARCHAR(10));
CREATE TABLE F (FK INT, B NVARCHAR(10), FOREIGN KEY(FK) REFERENCES R ON UPDATE CASC
ADE);
You create a flexible table T.
CREATE COLUMN TABLE T(A INT) WITH SCHEMA FLEXIBILITY;
You create table T2 with fuzzy search index and a fuzzy search mode.
CREATE COLUMN TABLE T2 (KEY INT, COL1 VARCHAR(10) FUZZY SEARCH INDEX ON, COL2 NVARC
HAR(10) FUZZY SEARCH MODE 'POSTCODE');
HISTORY time travel
You can utlitize the HI STORY COLUMN table type time travel feature in the following ways:
Session level time travel
A database session can be set back to a certain point-in-time. The input parameter of the statement is either
a utc-timestamp or a commitid.
SET HISTORY SESSION TO UTCTIMESTAMP = <timestamp>
<timestamp> ::= <string_literal>
or
SET HISTORY SESSION TO COMMIT ID = <commit_id>
<commit_id> ::= <unsigned_integer>
The timestamp has to be in format 'YYYY-MM-DD HH:MM:SS[.FF7]'. 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 t ransaction commit:
SELECT LAST_COMMIT_ID FROM M_TRANSACTIONS;
WHERE CONNECTION_ID = CURRENT_CONNECTION;
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
SAP HANA Database - SQL Reference Manual
94 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 95/193
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, a n explicit COMMIT or ROLLBACK has
to be executed on the DB connection.
Statement level time travel
<subquery> AS OF UTCTIMESTAMP <timestamp>
<subquery> AS OF COMMIT ID <commit_id>
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
details on <subquery>, please refer to 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.
CREATE TRIGGER
Syntax
CREATE TRIGGER <trigger_name> <trigger_action_time> <trigger_event>
ON <subject_table_name> [REFERENCING <transition_list>]
[<for_each_row>]
BEGIN
[<trigger_decl_list>]
[<proc_handler_list>]
<trigger_stmt_list>
END
Syntax Elements
<trigger_name> ::= <identifier>
The name of trigger you create.
<subject_table_name> ::= <identifier>
The name of table your trigger is defined on.
For descriptions on identifier, see Identifiers.
<trigger_action_time> ::= BEFORE | AFTER
Specify when trigger a cction occur.
BEFORETrigger is executed before the subject table operation.
AFTER
Trigger is executed after the subject table operation.
<trigger_event> ::= INSERT | DELETE | UPDATE
Specify which data modification command activate trigger action.
<transition_list> ::= <transition> | <transition_list> , <transition>
<transition> ::= <trigger_transition_old_or_new> <trigger_transition_var_or_table
> <trans_var_name>
| <trigger_transition_old_or_new> <trigger_transition_var_or_table
> AS <trans_var_name>
When trigger transition variable is declared, trigger ca n access records that are being changed by trigger
SAP HANA Database - SQL Reference Manual
95 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 96/193
triggering DML.
While row level trigger execution, <trans_var_name>.<column_name> represents corresponding column
record being changed in trigger.
Here <column_name> is subject table's column name. See example of transition variable
<trigger_transition_old_or_new> ::= OLD | NEW
<trigger_transition_var_or_table> ::= ROW
<trans_var_name> ::= <identifier>
OLD
You can access old record of DML in trigger, which is to-be-replaced-by-update old record or deleted-old-
record.
UPDATE trigger and DELETE trigger can have OLD ROW transition variable.
NEW
You can access new record of DML in trigger, which is to-be-inserted new record or to-be-updated new
record.
UPDATE trigger and INSERT trigger can have NEW ROW transition variable.
Only transition variable is supported.
Transition table is not supported feature.
If you put 'TABLE' as <trigger_transition_var_or_table>, you will see not-supported-feature error.
<for_each_row> ::= FOR EACH ROW
Defines that the trigg er will be called in a row-wise fashion.
Statement level trigger execution is the default mode when FOR EACH ROW is not defined.
Currently statement-wise trigger is not supported.
<trigger_decl_list> ::= DECLARE <trigger_decl>
| <trigger_decl_list> DECLARE <trigger_decl>
<trigger_decl> ::= <trigger_var_decl> | <trigger_condition_decl>
<trigger_var_decl> ::= <var_name> CONSTANT <data_type> [<not_null>] [<trigger_defa
ult_assign>] ;
| <var_name> <data_type> [<not_null>] [<trigger_default_assig
n>] ;
<var_name> ::= <identifier>
<data_type> ::= DATE | TIME | SECONDDATE | TIMESTAMP | TINYINT | SMALLINT | INTEGER
| BIGINT | SMALLDECIMAL | DECIMAL | REAL | DOUBLE
| VARCHAR | NVARCHAR | ALPHANUM | SHORTTEXT | VARBINARY | BLOB | CLOB
| NCLOB | TEXT
<not_null> ::= NOT NULL
<trigger_default_assign> ::= DEFAULT <expression>
| := <expression>
<trigger_condition_decl> ::= <condition_name> CONDITION ;
| <condition_name> CONDITION FOR <sql_error_code> ;
<condition_name> ::= <identifier>
<sql_error_code> ::= SQL_ERROR_CODE <int_const>
trigger_decl_list
You can declare trigger variable or condition.
Declared variable can be used scalar value assignment or referenced in trigger SQL statement.
Declared condition name can be referenced when exception handler.
CONSTANT
When CONSTANT kewword was given, you cannot change the variable while trigger execution.
<proc_handler_list> ::= <proc_handler>
| <proc_handler_list> <proc_handler>
<proc_handler> ::= DECLARE EXIT HANDLER FOR <proc_condition_value_list> <trigger_s
SAP HANA Database - SQL Reference Manual
96 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 97/193
tmt>
<proc_condition_value_list> ::= <proc_condition_value>
| <proc_condition_value_list> , <proc_condition_val
ue>
<proc_condition_value> ::= SQLEXCEPTION
| SQLWARNING
| <sql_error_code>
| <condition_name>
Exception handler can be declared for catching with existing sql exception,
specific error code number or condition name declared on condition variable.
<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>
| <trigger_sql>
Trigger body syntax is a part of procedure body syntax.
See detail of create procedure definition in SAP HANA database SQLScript guide.
The syntax of trigger body complies with that of procedure, which are nested block(proc_block),
scalar variable 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),
and sql statement(proc_sql).
<proc_block> ::= BEGIN
[<trigger_decl_list>]
[<proc_handler_list>]
<trigger_stmt_list>
END ;
You can add another 'BEGIN .. . END; ' block in a nested way.
<proc_assign> ::= <var_name> := <expression> ;
var_name is variable name, which should be declared previously.
<proc_if> ::= IF <condition> THEN <trigger_stmt_list>
[<proc_elsif_list>]
[<proc_else>]
END IF ;
<proc_elsif_list> ::= ELSEIF <condition> THEN <trigger_stmt_list>
<proc_else> ::= ELSE <trigger_stmt_list>
For descriptions on condition, refer to <condition> in SELECT.
Using IF ... THEN .. . ELSEIF . .. END IF, you can control execution flow with condition.
<proc_loop> ::= LOOP <trigger_stmt_list> END LOOP ;
<proc_while> ::= WHILE <condition> DO <trigger_stmt_list> END WHILE ;
<proc_for> ::= FOR <column_name> IN [<reverse>] <expression> <DDOT_OP> <expressio
n>
DO <trigger_stmt_list>
END FOR ;
<column_name> ::= <identifier>
<reverse> ::= REVERSE
<DDOT_OP> ::= ..
<proc_foreach> ::= FOR <column_name> AS <column_name> [<open_param_list>] DO
<trigger_stmt_list>
END FOR ;
SAP HANA Database - SQL Reference Manual
97 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 98/193
<open_param_list> ::= ( <expr_list> )
<expr_list> ::= <expression> | <expr_list> , <expression>
<proc_signal> ::= SIGNAL <signal_value> [<set_signal_info>] ;
<proc_resignal> ::= RESIGNAL [<signal_value>] [<set_signal_info>] ;
<signal_value> ::= <signal_name> | <sql_error_code>
<signal_name> ::= <identifier>
<set_signal_info> ::= SET MESSAGE_TEXT = '<message_string>'
<message_string> ::= <identifier>
SET MESSAGE_TEXT
If you set your own message with SET MESSAGE_TEXT,
the message is delivered to users when specified error is thrown from trigger execution.
SIGNAL stat ement provide raise an exception explicitly.
User-defined range (10000 ~ 19999) will be allowed for the error code to issue.
RESIGNAL statement provide raise an exception on the action statement in exception handler.If error code is not specified, RESIGNAL will t hrow up the catched exception.
<trigger_sql> ::= <select_into_stmt>
| <insert_stmt>
| <delete_stmt>
| <update_stmt>
| <replace_stmt>
| <upsert_stmt>
For descriptions on insert_stmt, refer to INSERT.
For descriptions on delete_stmt, refer to DELETE.
For descriptions on update_stmt, refer to UPDATE.
For descriptions on replace_stmt and upsert_stmt, refer to REPLACE | UPSERT.
<select_into_stmt> ::= SELECT <select_list> INTO <var_name_list>
<from_clause > [<where_clause>]
[<group_by_clause>]
[<having_clause>]
[{<set_operator> <subquery>, ... }]
[<order_by_clause>]
[<limit>]
<var_name_list> ::= <var_name> | <var_name_list> , <var_name>
<var_name> ::= <identifier>
For descriptions on select_list, from_clause, where_clause, group_by_clause, having_clause,
set_operator, subquery, order_by_clause, limit, refer to SELECT.
var_name is scalar variable name which should be declared before.
You can assign selected item value to the scalar variable.
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 <subject_table_name> are allowed to create
a trigger for that table.
Current trigger limitation is described below:
INSTEAD_OF trigger is not supported.
Access of subject table which is table that trigger is defined on, is not allowed in trigger body,
SAP HANA Database - SQL Reference Manual
98 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 99/193
which means any insert/update/delete/replace/select for table which trigger is on is not allowed.
Only row level trigger is supported. Statement level trigger is not supported.
Row level trigger means trigger action will be executed for every row changes.
Statement level trigger means trigger action will be executed once for a statement execution.
Syntax 'FOR EACH ROW' means row-wise trigger execution and it is default mode. Even when 'FOR
EACH ROW' is not defined, it is still row level trigger.Transition table (OLD/NEW TABLE) is not supported.
When trigger SQL statement want to refer to data that are being changed by trigger-triggering-event
like insert/update/delete,
transition variable/table will be a way SQL statement in trigger body access old and new data.
Transition variable is used by row level trigger while transition table is used by statement level trigg er.
Trigger execution on partitioned table to multiple host or table in slave node is not supported.
Not supported trigger action feature(while procedure does) :
resultset assignment(select resultset assignment to tabletype),
exit/continue command(execution flow control),
cursor open/fetch/close(get each record data of search result by cursor and access record in loop),
procedure call(call another proecedure),
dynamic sql execution(build SQL statements dynamically at runtime of SQLScript),
return(end SQL statement execution)
System and Monitoring Views
TRIGGER S is system view for trigger.
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
You first need table which trigger is defined on.
CREATE TABLE TARGET ( A INT);
You also need tables which trigger accesses and modifies.
CREATE TABLE SAMPLE ( A INT);
Following is example of create trigger.
CREATE TRIGGER TEST_TRIGGER
AFTER INSERT ON TARGET FOR EACH ROW
BEGIN
DECLARE SAMPLE_COUNT INT;
SELECT COUNT(*) INTO SAMPLE_COUNT FROM SAMPLE;
IF :SAMPLE_COUNT = 0
THEN
INSERT INTO SAMPLE VALUES(5);
ELSEIF :SAMPLE_COUNT = 1
THEN
INSERT INTO SAMPLE VALUES(6);
END IF;
END;
Trigger TEST_TRIGGER will be executed after any record insert execution for TARGET table.
Since SAPMLE table record count is zero in the first insert try, the trigger TEST_TRIGGER will insert 5 to
SAMPLE table.
In the second insertion to TARGET table, the trigger insert 6 to SAMPLE table because its count is two.
INSERT INTO TARGET VALUES (1);
SELECT * FROM SAMPLE;
5
INSERT INTO TARGET VALUES (2);
SELECT * FROM SAMPLE;
5
6
Followings are more example of create trigg er. FOR/WHILE Example
SAP HANA Database - SQL Reference Manual
99 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 100/193
CREATE TABLE TARGET ( A INT);
CREATE TABLE SAMPLE ( A INT);
CREATE TRIGGER TEST_TRIGGER_WHILE_UPDATE
AFTER UPDATE ON TARGET
BEGIN
DECLARE found INT := 1;
DECLARE val INT := 1;
WHILE :found <> 0 DO
SELECT count(*) INTO found FROM sample WHERE a = :val;
IF :found = 0 THEN
INSERT INTO sample VALUES(:val);
END IF;
val := :val + 1;
END WHILE;
END;
CREATE TABLE TARGET ( A INT);
CREATE TABLE control_tab(id INT PRIMARY KEY, name VARCHAR(30), payment INT);
CREATE TABLE message_box(message VARCHAR(200), log_time TIMESTAMP);
CREATE TRIGGER TEST_TRIGGER_FOR_INSERT
AFTER INSERT ON TARGET
BEGINDECLARE v_id INT := 0;
DECLARE v_name VARCHAR(20) := '';
DECLARE v_pay INT := 0;
DECLARE v_msg VARCHAR(200) := '';
DELETE FROM message_box;
FOR v_id IN 100 .. 103 DO
SELECT name, payment INTO v_name, v_pay FROM control_tab WHERE id = :v_id;
v_msg := :v_name || ' has ' || TO_CHAR(:v_pay);
INSERT INTO message_box VALUES (:v_msg, CURRENT_TIMESTAMP);
END FOR;
END;
handler Examples
CREATE TABLE TARGET ( A INT);
CREATE TABLE MYTAB (I INTEGER PRIMARY KEY);
CREATE TRIGGER MYTRIG_SQLEXCEPTION
AFTER INSERT ON TARGET
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT ::SQL_ERROR_CODE, ::SQL_ERROR_MESS
AGE FROM DUMMY;
INSERT INTO MYTAB VALUES (1);
INSERT INTO MYTAB VALUES (1); -- expected unique violation error: 301
-- not reached
END;
CREATE TRIGGER MYTRIG_SQL_ERROR_CODE
AFTER UPDATE ON TARGET
BEGIN
DECLARE EXIT HANDLER FOR SQL_ERROR_CODE 301 SELECT ::SQL_ERROR_CODE, ::SQL_ERRO
R_MESSAGE FROM DUMMY;
INSERT INTO MYTAB VALUES (1);
INSERT INTO MYTAB VALUES (1); -- expected unique violation error: 301
-- not reached
END;
CREATE TRIGGER MYTRIG_CONDITION
AFTER DELETE ON TARGET
BEGIN
DECLARE MYCOND CONDITION FOR SQL_ERROR_CODE 301;
DECLARE EXIT HANDLER FOR MYCOND SELECT ::SQL_ERROR_CODE, ::SQL_ERROR_MESSAGE FR
OM DUMMY;
INSERT INTO MYTAB VALUES (1);
INSERT INTO MYTAB VALUES (1); -- expected unique violation error: 301
-- not reached
END;
SIGNAL/RESIGNAL Examples
CREATE TABLE TARGET ( A INT);
CREATE TABLE MYTAB (I INTEGER PRIMARY KEY);
CREATE TABLE MYTAB_TRIGGER_ERR (err_code INTEGER, err_msg VARCHAR(30));
SAP HANA Database - SQL Reference Manual
100 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 101/193
CREATE TRIGGER MYTRIG_SIGNAL
AFTER INSERT ON TARGET
BEGIN
DECLARE MYCOND CONDITION FOR SQL_ERROR_CODE 10001;
DECLARE EXIT HANDLER FOR MYCOND INSERT INTO MYTAB_TRIGGER_ERR VALUES (::SQL_ERR
OR_CODE, ::SQL_ERROR_MESSAGE);
INSERT INTO MYTAB VALUES (1);
SIGNAL MYCOND SET MESSAGE_TEXT = 'my error';
-- not reached
END;
CREATE TRIGGER MYTRIG_RESIGNAL
AFTER UPDATE ON TARGET
BEGIN
DECLARE MYCOND CONDITION FOR SQL_ERROR_CODE 10001;
DECLARE EXIT HANDLER FOR MYCOND RESIGNAL;
INSERT INTO MYTAB VALUES (1);
SIGNAL MYCOND SET MESSAGE_TEXT = 'my error';
-- not reached
END;
Transition variable Example
CREATE TABLE TARGET ( A INT, B VARCHAR(10));
CREATE TABLE SAMPLE_OLD ( A INT, B VARCHAR(10));
CREATE TABLE SAMPLE_NEW ( A INT, B VARCHAR(10));
INSERT INTO TARGET VALUES ( 1, 'oldvalue');
CREATE TRIGGER TEST_TRIGGER_VAR_UPDATE
AFTER UPDATE ON TARGET
REFERENCING NEW ROW mynewrow, OLD ROW myoldrow
FOR EACH ROW
BEGIN
INSERT INTO SAMPLE_new VALUES(:mynewrow.a, :mynewrow.b);
INSERT INTO SAMPLE_old VALUES(:myoldrow.a, :myoldrow.b);
END;
UPDATE TARGET SET b = 'newvalue' WHERE A = 1;
SELECT * FROM SAMPLE_NEW;
1, 'newvalue'
SELECT * FROM SAMPLE_OLD;
1, 'oldvalue'
CREATE VIEW
Syntax
CREATE VIEW <view_name> [(<column_name>, ... )] AS <subquery>
Syntax Elements
<view_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
<column_name> ::= <identifier>
Description
The CREATE VIEW statement effectively creates virtual table based on the results of an SQL statement. I t isnot 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)
SAP HANA Database - SQL Reference Manual
101 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 102/193
. 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
You create table A.
CREATE TABLE A (A INT PRIMARY KEY, B INT);
You create a view v that selects all records from table A.
CREATE VIEW v AS SELECT * FROM A;
DROP AUDIT POLICY
Syntax
DROP AUDIT POLICY <policy_name>
Syntax Elements
<policy_name> ::= <identifier>
Description
The DROP AUDI T 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.
System and Monitoring Views
AUDIT_POLICY: shows all audit policies and their states
M_INIFILE_CONTENTS: shows the configuration parameter concerning auditing
Only database users with system privilege CATALOG READ, DATA ADMIN or INIFILE ADMI N can see any info
out of the view M_INI FILE_CONTENTS. For other database users this view will be empty.
Example
Assuming that the creation of an audit policy happened before using the following statement:
CREATE AUDIT POLICY priv_audit AUDITING SUCCESSFUL GRANT PRIVILEGE, REVOKE PRIVILEG
E, GRANT ROLE, REVOKE ROLE LEVEL CRITICAL;
Now this audit policy has to be dropped.
DROP AUDIT POLICY priv_audit;
DROP FULLTEXT INDEX
Syntax
DROP FULLTEXT INDEX <fulltext_index_name>
Syntax Elements
<fulltext_index_name> ::= <identifier>
Specifies the index to be dropped.
SAP HANA Database - SQL Reference Manual
102 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 103/193
Description
The DROP FULLTEXT INDEX statement removes a fulltext index.
Example
You create table A and then add an index i on column b of table A.
CREATE TABLE A (a INT, b NVARCHAR(10), c NVARCHAR(20));
CREATE INDEX i ON A(b);
You drop index i.
DROP FULLTEXT INDEX i;
DROP INDEX
Syntax
DROP INDEX <index_name>
Syntax Elements
index_name ::= <identifier>
The index name identifier specifies the index to be dropped.
Description
The DROP INDEX statement removes an index.
Example
You create table A and then add an index i on column b of table A.
CREATE TABLE A (a INT, b NVARCHAR(10), c NVARCHAR(20));
CREATE INDEX i ON A(b);
You drop index i.
DROP INDEX i;
DROP SCHEMA
Syntax
DROP SCHEMA <schema_name> [<drop_option>]
Syntax Elements
<drop_option> ::= CASCADE | RESTRICT
When <drop_option> is not specified a non-cascaded drop will be performed. This will only drop the specified
schema, dependent objects of the schema will be invalidated but not dropped.
The invalidated object can be revalidated when an object that has same schema name is created.
CASCADE
Drops the schema and dependent objects.
RESTRICT
Drops the schema only when dependent objects do not exist. If this drop option is used and a dependent
object exists an error will be thrown.
Description
SAP HANA Database - SQL Reference Manual
103 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 104/193
The DROP SCHEMA statement removes a schema.
Example
You create schema my_schema and a table my_schema.t.
CREATE SCHEMA my_schema;
CREATE TABLE my_schema.t (a INT);
You drop my_schema with a CASCADE option.
DROP SCHEMA my_schema CASCADE;
DROP SEQUENCE
Syntax
DROP SEQUENCE <sequence_name> [<drop_option>]
Syntax Elements
<sequence_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
The name of the sequence to be dropped, with optional schema name.
<drop_option> ::= CASCADE | RESTRICT
When <drop_option> is not specified a non-cascaded drop will be performed. This will only drop the specified
sequence, dependent objects of the sequence will be invalidated but not dropped.
The invalidated objects can be revalidated when an object that has same schema and object name is creat ed.
CASCADE
Drops the sequence and dependent objects.
RESTRICT
Drops the sequence only when dependent objects do not exist. If this drop option is used and a dependent
object exists an error will be thrown.
Description
The DROP SEQUENCE statement removes a sequence.
Example
You create a sequence seq.
CREATE SEQUENCE seq START WITH 11;
You drop the sequence seq.
DROP SEQUENCE seq;
DROP SYNONYM
Syntax
DROP [PUBLIC] SYNONYM <synonym_name> [<drop_option>]
Syntax Elements
PUBLIC
When specified allows the removal of a public synonym.
SAP HANA Database - SQL Reference Manual
104 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 105/193
<synonym_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
The name of the synonym to be dropped, with optional schema name.
<drop_option> ::= CASCADE | RESTRICT
When <drop_option> is not specified a non-cascaded drop will be performed. This will only drop the specified
synonym, dependent objects of the synonym will be invalidated but not dropped.
The invalidated object can be revalidated when an object that has same schema and object name is created.
CASCADE
Drops the synonym and dependent objects.
RESTRICT
Drops the synonym only when dependent objects do not exist. If this drop option is used and a dependent
object exists an error will be thrown.
Description
The DROP SYNONYM statement removes a synonym.
Example
You create a table 'a', then a synonym a_synonym and a public synonym pa_synonym for the table.
CREATE TABLE a (c INT);
CREATE SYNONYM a_synonym FOR a;
CREATE PUBLIC SYNONYM pa_synonym FOR a;
You drop both synonym a_synonym and public synonym pa_synonym using a non-cascaded drop in both cases.
DROP SYNONYM a_synonym;
DROP PUBLIC SYNONYM pa_synonym;
DROP TABLE
Syntax
DROP TABLE <table_name> [<drop_option>]
Syntax Elements
<table_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
The name of the table to be dropped, with optional schema name.
<drop_option> ::= CASCADE | RESTRICT
When <drop_option> is not specified a non-cascaded drop will be performed. This will only drop the specified
table, dependent objects of the table will be invalidated but not dropped.
The invalidated objects can be revalidated when an object that has same schema and object name is creat ed.
CASCADE
Drops the table and dependent objects.
RESTRICT
Drops the table only when dependent objects do not exist. If this drop option is used and a dependent object
exists an error will be thrown.
Description
SAP HANA Database - SQL Reference Manual
105 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 106/193
The DROP TABLE statement removes a table from the database.
Example
You create table A and then drop it directly afterwards.
CREATE TABLE A(C INT);
DROP TABLE A;
DROP TRIGGER
Syntax
DROP TRIGGER <trigger_name>
Syntax Elements
<trigger_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
The name of the trigger t o be dropped, with optional schema name.
<drop_option> ::= CASCADE | RESTRICT
When <drop_option> is not specified a non-cascaded drop will be performed. This will only drop the specified
trigger, dependent objects of the trigger will be invalidated but not dropped.
The invalidated object can be revalidated when an object that has same schema and object name is created.
CASCADE
Drops the tr igger a nd dependent objects.
RESTRICT
Drops the trigger only when dependent objects do not exist. If this drop option is used and a dependentobject exists an error will be thrown.<b
Description
The DROP TRIGGER statement deletes a trigger.
Only database users having the TRIGGER privilege for the table on which the trigger was defined are allowed
to drop a trigger for that table.
Example
You create two tables, target and sample, and a trigger called test.
CREATE TABLE target ( A INT);
CREATE TABLE sample ( A INT);
CREATE TRIGGER test
AFTER UPDATE ON target
BEGIN
INSERT INTO sample VALUES(3);
END;
You drop the trigger called test.
DROP TRIGGER test;
DROP VIEW
Syntax
DROP VIEW <view_name> [<drop_option>]
Syntax Elements
SAP HANA Database - SQL Reference Manual
106 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 107/193
<view_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
The name of the view to be dropped, with optional schema name.
<drop_option> ::= CASCADE | RESTRICT
When <drop_option> is not specified a non-cascaded drop will be performed. This will only drop the specified
view, dependent objects of the view will be invalidated but not dropped.
The invalidated objects can be revalidated when an object that has same schema and object name is creat ed.
CASCADE
Drops the view and dependent objects.
RESTRICT
Drops the view only when dependent objects do not exist. If this drop option is used and a dependent object
exists an error will be thrown.
Description
The DROP VIEW statement removes a view from the database.
Example
You create table t, then a view v that selects all records from table t.
CREATE TABLE t (a INT);
CREATE VIEW v AS SELECT * FROM t;
You drop view v from the database.
DROP VIEW v;
RENAME COLUMN
Syntax
RENAME COLUMN <table_name>.<old_column_name> TO <new_column_name>
Syntax Elements
<table_name> ::= <identifier>
The name of the table where the column is to be renamed.
<old_column_name> ::= <identifier>
<new_column_name> ::= <identifier>
The old and new column names respectively.
Description
The RENAME COLUMN statement changes the name of a column.
For the information on column name, please refer to Identifiers.
Example
You create table tab with two columns named A and B.
CREATE TABLE tab (A INT PRIMARY KEY, B INT);
You display the column names for table tab stored in the SAP HANA database.
SELECT COLUMN_NAME, POSITION FROM TABLE_COLUMNS WHERE SCHEMA_NAME = CURRENT_SCHEMA
SAP HANA Database - SQL Reference Manual
107 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 108/193
AND TABLE_NAME = 'tab' ORDER BY POSITION;
You rename column A to C.
RENAME COLUMN tab.A TO C;
You display the column names for table ta b after the renaming.
SELECT COLUMN_NAME, POSITION FROM TABLE_COLUMNS WHERE SCHEMA_NAME = CURRENT_SCHEMA
AND TABLE_NAME = 'tab' ORDER BY POSITION;
RENAME INDEX
Syntax
RENAME INDEX <old_index_name> TO <new_index_name>
Syntax Elements
<old_index_name> ::= <identifier>
<new_index_name> ::= <identifier>
Description
The RENAME INDEX statement changes the name of an index.
For the information on index name, please refer to Identifiers.
Example
Table B is creat ed, then index idx is created on column B of ta ble B:
CREATE TABLE B (A INT PRIMARY KEY, B INT);
CREATE INDEX idx on B(B);
The list of index names in table B is shown:
SELECT INDEX_NAME FROM INDEXES WHERE SCHEMA_NAME = CURRENT_SCHEMA AND TABLE_NAME =
'B';
Index idx is renamed to new_idx:
RENAME INDEX idx TO new_idx;
The list of index names in table B after renaming is shown:
SELECT INDEX_NAME FROM INDEXES WHERE SCHEMA_NAME = CURRENT_SCHEMA AND TABLE_NAME =
'B';
RENAME TABLE
Syntax
RENAME TABLE <old_table_name> TO <new_table_name>
Syntax Elements
<old_table_name> ::= <identifier>
<new_table_name> ::= <identifier>
Description
The RENAME TABLE statement changes the name of a table to new_table_name in the same schema.
For the information on table name, please refer to Identifiers.
Example
SAP HANA Database - SQL Reference Manual
108 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 109/193
Table A is created in current schema:
CREATE TABLE A (A INT PRIMARY KEY, B INT);
The list of table names in current schema is shown:
SELECT TABLE_NAME FROM TABLES WHERE SCHEMA_NAME = CURRENT_SCHEMA;
Table A renamed to B:
RENAME TABLE A TO B;
The list of table names in current schema after renaming is shown:
SELECT TABLE_NAME FROM TABLES WHERE SCHEMA_NAME = CURRENT_SCHEMA;
Schema mySchema is created, then ta ble mySchema.A is created:
CREATE SCHEMA mySchema;
CREATE TABLE mySchema.A (A INT PRIMARY KEY, B INT);
The list of table names in schema mySchema is shown:
SELECT TABLE_NAME FROM TABLES WHERE SCHEMA_NAME = 'MYSCHEMA';
Table mySchema.A is renamed to B:
RENAME TABLE mySchema.A TO B;
The list of table names in schema mySchema after renaming is shown:
SELECT TABLE_NAME FROM TABLES WHERE SCHEMA_NAME = 'MYSCHEMA';
Data Manipulation Statements
DELETE
Syntax
DELETE [HISTORY] FROM <table_name> [WHERE <condition>]
Syntax Elements
HISTORY
Marks the selected records of the history storage of a history-table for deletion.
<table_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
For descriptions on identifier, please refer to Identifiers.
<condition> ::= <condition> OR <condition>
| <condition> AND <condition>
| NOT <condition>
| ( <condition> )
| <predicate>
For descriptions on predicates, please refer to Predicates.
Description
The DELETE statement deletes records from a table where the <condition> is met. If the WHERE clause is
omitted, then DELETE removes all records from a table.
When using the DELETE HISTORY command time travel queries referencing the deleted rows may still access
these rows. In order to physically delete these rows the following statements have to be executed:
SAP HANA Database - SQL Reference Manual
109 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 110/193
ALTER SYSTEM RECLAIM VERSION SPACE;
MERGE HISTORY DELTA of <table_name>;
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:
SELECT * FROM <table_name> WHERE <condition> WITH PARAMETERS ('REQUEST_FLAGS'=
('ALLCOMMITTED','HISTORYONLY'));
Note:
The "WITH PARAMETERS ('REQUEST_FLAGS'= ('ALLCOMMITTED','HISTORYONLY'))" clause may only
be used for the purpose of validating the result of using the DELETE HISTORY statement.
Example
Example 1 - Standard delete operation.
You create a ta ble and insert some data.
CREATE TABLE T (KEY INT PRIMARY KEY, VAL INT);
INSERT INTO T VALUES (1, 1);
INSERT INTO T VALUES (2, 2); INSERT INTO T VALUES (3, 3);
You delete from table T where the key column is equal to 1;
DELETE FROM T WHERE KEY = 1;
After executing the above query the contents of table T is as follows:
KEY VAL
2 2
3 3
From this result we can see that one row was deleted.
Example 1 - Standard delete operation.
You first create a history table and insert a value.
CREATE HISTORY COLUMN TABLE HIST(KEY INT PRIMARY KEY, VAL INT);
INSERT INTO HIST VALUES (1, 1);
COMMIT;
You update the row we inserted at the previous step.
UPDATE HIST SET VAL=42 WHERE KEY=1;
COMMIT;
You merge in the table delta storage with the table main storage.
MERGE DELTA OF HIST;
Assuming the merge statement has moved the updated record into the history storage of the history table,you can now delete the updated record history.
DELETE HISTORY FROM HIST WHERE KEY=1;
EXPLAIN PLAN
EXPLAIN PLAN
EXPLAIN PLAN [SET STATEMENT_NAME = <statement_name>] FOR \ref sql_subquery
Syntax Elements
<statement_name> ::= string literal used to identify the name of a specific executi
on plan in the output table for a given SQL statement.
SAP HANA Database - SQL Reference Manual
110 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 111/193
It is set to NULL if the SET STATEMENT_NAME is not specified.
Description
The EXPLAIN PLAN statement is used to evaluate the execution plan that the SAP HANA data base 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.
SELECT * FROM EXPLAIN_PLAN_TABLE;
Columns in EXPLAIN_PLAN_TABLE view:
Table 1: Column name and description
Column Name Descripti on
STATEMENT_NAMEThe s tring speci fied as STATEMENT_NAME on executing the EXPLAIN PLAN command. Thisis us ed to distinguish pla ns from each other when there are multiple pl ans i n the
EXPLAIN_PLAN_TABLE view .
OPERATOR_NAME Name of an operator. Details are described in the following section.
OPERATOR_DETAILSDetails of an operator. Predicates and e xpress ions us ed by the operator are shown
here.
S CH EMA_ NA ME N a me of th e s ch e ma of th e a cce s s e d ta b l e.
TABLE_NAME Na me of the a cce ss ed ta bl e.
TABLE_TYPEType of the accesse d tabl e. One of the foll owing option s: COLUMN TABLE, ROW TABLE,
MONITORING VIEW, JOIN VIEW, OLAP VIEW, CALCULATION VIEW and HIERARCHY VIEW.
TABLE_SI ZE Es ti ma te d n umbe r of rows in the acce ss ed ta bl e
O UTPU T_ SI ZE Es ti m ate d n um be r o f ro ws pro du ce d b y a n o pe ra to r
SUBTREE_COSTEstimated cost of executing the subtree starting from an operator. This value is only for
relative comparison.
O PER ATO R_I D I D of a n op e ra to r u ni q ue i n a p l a n. I Ds a re i n te ge rs s t a rti n g f ro m 1.
PARENT_OPERATOR_ID
OPERATOR_ID of the parent of an operator. The shape of an SQL plan is a tree and the
topology of the tree can be reconstructed usi ng OPERATOR_ID and
PARENT_OPERATOR_ID. PARENT_OPERATOR_ID of the root operator i s shown as NULL.
LEVELLevel from the root operator. Level of the root opera tor is 1, level of a chil d of the root
operator is 2 and so on. This can be util ized for output indentation.
POSITIONPosition in the parent operator. Position of the first child is 1, position of the s econd
child is 2 and so on.
HOST The hostname where an operator was executed
PORT The TCP/IP port used to connect to the hos t
TI MES TAMP D ate a nd ti me w he n th e EXPLAI N PLAN co mma nd wa s e xe cu te d.
CONNECTION_ID ID of the connection where the EXPLAIN PLAN command was executed.
EXECUTION_ENGINE Type of the execution engine where an operator is 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.
Operator Name Description
COLUMN
SEARCHStarting position of column engine operators. OPERATOR_DETAILS lists projected columns.
LI MI T Ope ra to r fo r l imi ti ng the numbe r o f ou tpu t ro ws
O RD ER B Y O pe ra to r f or s o rti n g o utp ut ro ws
HAVING Operator for f i l tering with pred icates on top of grouping and aggregation
G ROU P B Y O pe ra to r f or g ro up i ng a nd a gg re ga ti o n
D IS TI NCT Op era to r fo r d up li ca te el i mi na ti on
FI LTER Ope ra to r fo r fi l te ri ng wi th pre di ca te s
JOIN Opera tor for joi ni ng i nput re la ti ons
COLUMN TABLE Information about accessed column table
MULTIPROVIDEROperator for producing union-al l of multiple results ha ving the same grouping and
aggregation
SAP HANA Database - SQL Reference Manual
111 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 112/193
Table 3. List of row engine operators shown in the OPERATOR_NAME column.
Operator
NameDescription
ROW SEARCH Starting position of row engine operators. OPERATOR_DETAILS lists projected columns.
LI MI T Op era to r f or l i mi ti ng n umb er o f o utp ut ro ws
ORDER BY Operator for sort ing output rows
HAVING Operator for f i l tering with pred icates on top of grouping and aggregation
GROUP B Y Operator for grouping and aggregation
MERGE
AGGREGATIONOperator for merging the results of multipl e pa rallel grouping and aggregations
D I STI NCT Op e ra to r f or d up l i ca te el i mi n a ti o n
F ILTER Op era to r f or f il te ri ng w ith p re di ca te s
UNION ALL Operator for producing union-all of input relations
MATERIALIZED
UNION ALLOperator for producing union-all of input relations with intermediate result ma terial ization
BTREE INDEX
JOIN
Operator for joining input relations through B-tree index searches. Join type suffix can be
added. For example, B-tree index join for left outer join is shown as BTREE INDEX JOIN (LEFT
OUTER). Join without join type suffix means inner join.CPBTREE
INDEX JOIN
Operator for joining input relations through CPB-tree index searches. Join type suffix can be
added.
HASH JOINOperator for joining input relations through probing hash table built on the fly. Join type suffix
can be added.
NESTED LOOP
JOINOperator for joining input relations through nested looping. Join type suffix can be added.
MIXED
INVERTED
INDEX JOIN
Operator for joining an input relation of row store format with a column table without format
conversion using an inverted index of the column table. Join type suffix can be added.
BTREE INDEX
SEARCHTable access through B-tree index s earch
CPBTREE
INDEX SEARCHTable access through CPB-tree index search
TAB LE SCAN Table access through scann ing
AGGR TABLE Operator for aggregating base table directly
MONITOR
SEARCHMonitoring view access through search
MONITOR
SCANMonitoring view access through scanning
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) a nd 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) a nd 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
OPERATOR_NAME OPERATOR_ID PARENT_OPERATOR_ID LEVEL POSITION
COLUMN SEARCH 1 NULL 1 1
LIMIT 2 1 2 1
ORDER BY 3 2 3 1
GROUP BY 4 3 4 1
JOIN 5 4 5 1
COLUMN TABLE 6 5 6 1
<font
color="BLUE">ROW SEARCH</font>
<font
color="BLUE">7</font>
<font
color="BLUE">5</font>
<font
color="BLUE">6</font>
<font
color="BLUE">2</font>
BTREE INDEX JOIN 8 7 7 1
BTREE INDEX JOIN 9 8 8 1
<font
color="RED">COLUMN SEARCH</font>
<font
color="RED">10</font>
<font
color="RED">9</font>
<font
color="RED">9</font>
<font
color="RED">1</font>
FILTER 11 10 10 1
SAP HANA Database - SQL Reference Manual
112 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 113/193
COLUMN TABLE 12 11 11 1
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.
DELETE FROM explai n_pla n_table WHERE stateme nt_name = 'TPC-H Q10';
EXPLAIN PLAN SET S TATEMENT_NAME = 'TPC-H Q10' FOR
SELECT TOP 20
c_custkey,
c_name,
SUM(l_extendedprice * (1 - l_dis count)) AS revenue,
c_acctbal,
n_name,
c_address,
c_phone,
c_comment
FROM
customer,
orders,
l ineitem,
nation
WHERE
c_custkey = o_custkey
AND l_orderkey = o_orderkey
AND o_orderda te >= '1993-10-01'
AND o_orderda te < ADD_MONTHS('1993-10-01',3)
AND l_returnflag = 'R'
AND c_nationkey = n_nationke y
GROUP BY
c_custkey,
c_name,
c_acctbal,
c_phone,
n_name,
c_address,
c_comment
ORDER BY
revenue DESC;
SELECT operator_name, operator_details, table_name
FROM explain_plan_table
WHERE state ment_name = 'TPC-H Q10';
The following is the plan explanation of the above query.
OPERATOR_NAME OPERATOR_DETAILS TABLE_NAME
ROW SEARCH
CUSTOMER.C_CUSTKEY, CUSTOMER.C_NAME, SUM(LINEITEM.L_EXTENDEDPRICE * (1 -
LINEI TEM.L_DIS COUNT)), CUSTOMER.C_ACCTBAL, N ATION.N_NAME, CUSTOMER.C_ADDRESS , CUSTOMER.C_PHONE, CUSTOMER.C_
COMMENT
None
LIMIT NUM RECORDS: 20
ORDER BY SUM(LINEITEM.L_EXTENDEDPRICE * (1 - LINEITEM.L_DISCOUNT)) DESC None
MERGE AGGREGATION NUM PARTITIONS: 4 None
GROUP BYGROUPING: N ATION.N_NAME, R_CUSTOMER.C_CUSTKEY, AGGREGATION: SUM(LINEI TEM.L_EXTENDEDPRICE * (1 -
LINEITEM.L_DISCOUNT))None
CPBTREE INDEX JOIN
INDEX NAME: _SYS_TREE_RS_279_#0_#P0,
INDEX CONDITION: ORDERS.O_ORDERKEY = LINEITEM.L_ORDERKEY,
INDEX FILTER: 'R' = LINEITEM.L_RETURNFLAG
LINEITEM
BTREE INDEX JOININDEX NAME: _SYS_TREE_RS_285_#0_#P0,
INDEX CONDI TION: CUSTOMER.C_NATIONKEY = NATION.N_NATIONKEYNATION
BTREE INDEX JOININDEX NAME: _SYS_TREE_RS_283_#0_#P0,
INDEX CONDITION: ORDERS.O_CUSTKEY = CUSTOMER.C_CUSTKEYCUSTOMER
TABLE SCAN FILTER CONDITION: ORDERS.O_ORDERDATE < '1994-01-01' AND ORDERS.O_ORDERDATE >= '1993-10-01'ORDERS
This means that:
1. TABLE SCAN will be executed on ORDERS with the FILTER CONDITION.
2. BTR EE INDEX JOIN will be executed with the B-tree index of CUSTOMER and the result of the below TABLE
SCAN.
3. BTR EE INDEX JOIN will be executed with the B-tree index of NATION and the result of the below BTREE
INDEX JOIN.
4. CPBTREE INDEX JOIN will be executed with the CPB-tree index of LINEITEM and the result of the below
BTREE INDEX JOIN.
SAP HANA Database - SQL Reference Manual
113 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 114/193
5. GROUP BY will be executed with the result of the below CPBTREE INDEX JOIN, with 4 threads.
6. MERGE AGGREGATI ON will be executed with the result of the GROUP BY below.
INSERT
Syntax
INSERT INTO <table_name> [ <column_list_clause> ] { <value_list_clause> | <subquery
> }
Syntax Elements
<table_name> ::= [ <schema_name>. ]<identifier>
<schema_name> ::= <identifier>
<column_list_clause> ::= ( <column_name>, ... )
<column_name> ::= <identifier>
For descriptions on identifier, please refer to Identifiers.
<value_list_clause> ::= VALUES ( <expression>, ... )
For descriptions on expressions, please refer to Expressions .
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. The column which isn't included in the
column list will be shown as a default value. If the column list is omitted, the database inserts all columns in
the table.
Example
You create table T:
CREATE TABLE T (KEY INT PRIMARY KEY, VAL1 INT, VAL2 NVARCHAR(20));
You insert a row into table T.
INSERT INTO T VALUES (1, 1, 'The first');
KEY VAL1 VAL2
1 1 The fi rst
You insert a new row into table T using column list to specify which columns should receive the input values.
INSERT INTO T (KEY, VAL2) VALUES (2,3);
KEY VAL1 VAL2
1 1 The fi rst
2 0 NULL
You insert a row into table T using a subquery.
INSERT INTO T SELECT 3, 3, 'The third' FROM DUMMY;
KEY VAL1 VAL2
1 1 The fi rst
2 0 3
3 3 The third
LOAD
Syntax
LOAD <table_name> [HISTORY] {DELTA | ALL | (<column_name>, ...)}
SAP HANA Database - SQL Reference Manual
114 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 115/193
Syntax Elements
<table_name> ::= [<schema_name>.]<identifier>
<schema_name>::= <identifier>
The name of the table to be loaded into memory, with optional schema name.
HISTORY
You can use the HI STORY option when <table_name> is the name of a history table. The default operation of
the LOAD command loads the current state of the given table into memory. If you explicitly require the table
history to be loaded into memory, a separate LOAD statement with the HISTORY option enabled has to be
executed. So to load a history completely into memory, two LOAD statements have to be executed, with a nd
without HISTORY option enabled.
Note:
If you do not explicitly load table history into memory the SAP HANA database will automatically
load this data upon first access.
DELTA
DELTA specifies that the delta part of a column store table is loaded into memory. As the column store is readoptimized and compressed, deltas are used to optimize insert or update operations.
ALL
ALL current data of the column store table, including its delta, is loaded into memory.
Note:
This option will not load the table history.
<column_name> ::= <identifier>
The name of the column to be loaded into memory.
Description
The LOAD statement explicitly loads column store table data into memory instead of upon first access.A LOAD statement without HISTORY option only loads the current table data and the table delta into
memory, but not the history-delta and history-main.
System Tables and Monitoring Views
m_cs_tables shows the current table load status.
Examples
You create column table A.
CREATE COLUMN TABLE A (A INT, B INT);
You load table A into memory.
LOAD A all;
You load the columns A and B of table A into memory.
LOAD A (A,B);
You query the load status of table A using the m_cs_tables monitoring view.
select loaded from m_cs_tables where table_name = 'A'
MERGE DELTA
Syntax
MERGE [HISTORY] DELTA OF <table_name> [PART n] [WITH PARAMETERS (<parameter_list>,
...)]
SAP HANA Database - SQL Reference Manual
115 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 116/193
Syntax Elements
HISTORY
Merges the history-delta storage of a table into the history-main storage for column store temporal tables.
PART
Merge the delta of a specific table part ition to the tables main storage.
<table_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
The table name where the delta merge will occur, with optional schema name.
<parameter_list> ::= <parameter> [{, <parameter>}...]
<parameter> ::= <parameter_name> = <parameter_setting>
<parameter_name> ::= 'SMART_MERGE' | 'MEMORY_MERGE'
<parameter_setting> ::= 'ON' | 'OFF'
Column store-specific options are passed using the "WITH PARAMETERS" clause.
SMART_MERGE
When SMART_MERGE is ON, the database does a smart merge based on merge criteria specified in
automerge section of indexserver configuration. When SMART_MERGE is OFF, smart merging is disabled.
MEMORY_MERGE
When MEMORY_MERGE is ON the SAP HANA database merges the table delta storage in memory only, it
will not be persisted. When MEMORY_MERGE is OFF, memory merging is disabled.
Description
The MERGE DELTA statement merges the column store table delta storage to the tables main storage. As a
column store table is read optimized and compressed deltas are introduced to optimize insert or update
operations. All insertions are passed to the delta storage. At a certain point in time the delta changes to atable can be merged into the ta ble main storage.
The UPDATE privilege on the column store table is required for performing a delta merge.
Examples
You create history column table A.
CREATE HISTORY COLUMN TABLE A(c NVARCHAR(1000)) PARTITION BY ROUNDROBIN PARTITIONS
2;
You merge the column store table delta storage to the tables main storage.
MERGE DELTA OF A;
You merge the column store table A using a smart merge.
MERGE DELTA OF A WITH PARAMETERS('SMART_MERGE' = 'ON');
You smart merge the column store table A delta storage to main storage in memory only. This merge will not
be persisted to disk.
MERGE DELTA OF A WITH PARAMETERS('SMART_MERGE' = 'ON', 'MEMORY_MERGE' = 'ON');
You merge table A delta storage of partition 1 to the main storage of partion 1.
MERGE DELTA OF A PART 1;
You merge table A history-delta storage into its history-main storage.
MERGE HISTORY DELTA OF A;
SAP HANA Database - SQL Reference Manual
116 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 117/193
You merge table A partition 1 history-delta storage to its history-main storage.
MERGE HISTORY DELTA OF A PART 1;
REPLACE | UPSERT
Syntax
UPSERT <table_name> [ <column_list_clause> ] { <value_list_clause> [ WHERE <condit
ion> | WITH PRIMARY KEY ] | <subquery> }
REPLACE <table_name> [ <column_list_clause> ] { <value_list_clause> [ WHERE <condit
ion> | WITH PRIMARY KEY ] | <subquery> }
Syntax Elements
<table_name> ::= [ <schema_name>. ]<identifier>
<schema_name> ::= <identifier>
<column_list_clause> ::= ( <column_name>, ... )
<column_name> ::= <identifier>
For descriptions on identifier, please refer to Identifiers.
<value_list_clause> ::= VALUES ( <expression>, ... )
For descriptions on expressions, please refer to Expressions .
<condition> ::= <condition> OR <condition>
| <condition> AND <condition>
| NOT <condition>
| ( <condition> )
| <predicate>
For descriptions on predicates, please refer to Predicates.
Description
Descriptions to detailed syntax elements of this SQL Command.
The UPSERT or REPLACE statement without a subquery is similar to the UPDATE statement. The only
difference is when the WHERE clause condition 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
You create table T.
CREATE TABLE T (KEY INT PRIMARY KEY, VAL INT);
You insert a new value.
UPSERT T VALUES (1, 1);
KEY VAL
1 1
You insert a new value if the condition in the WHERE clause is false or update the current row values if
WHERE evaluates to true.
SAP HANA Database - SQL Reference Manual
117 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 118/193
UPSERT T VALUES (2, 2) WHERE KEY = 2;
KEY VAL
1 1
2 2
You update the table row where KEY is equal to 1.
UPSERT T VALUES (1, 9) WHERE KEY = 1;
KEY VAL
1 9
2 2
You use the "WITH PRIMARY KEY" keyword to update the table using the primary key value in the VALUES
clause.
UPSERT T VALUES (1, 8) WITH PRIMARY KEY;
KEY VAL
1 8
2 2
You insert values using a subquery.
UPSERT T SELECT KEY + 2, VAL FROM T;
KEY VAL
1 8
2 2
3 8
4 2
SELECT
Syntax
<select_statement> ::= <subquery> [ <for_update> | <time_travel> ]
| ( <subquery> ) [ <for_update> | <time_travel> ]
<subquery> ::= <select_clause>
<from_clause>
[<where_clause>]
[<group_by_clause>]
[<having_clause>]
[{<set_operator> <subquery>, ... }]
[<order_by_clause>]
[<limit>]
Syntax Elements
SELECT clause
The select clause specifies an output to be returned either to the caller or to an outer select clause if oneexists.
<select_clause> ::= SELECT [TOP <unsigned_integer>] [ ALL | DISTINCT ] <select_list
>
The select clause.
TOP <unsigned_integer>
Specifies that that the first <unsigned_integer> records from the SQL statement should be returned.
DISTINCT
Specifies that only one copy of each set of duplicate records selected should be returned.
SAP HANA Database - SQL Reference Manual
118 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 119/193
ALL
Specifies that all rows selected, including all copies of duplicates should be returned. This is the default
option.
<select_list> ::= <select_item>[, ...]
The list of columns to be retrieved.
<select_item> ::= [<table_name>.] <asterisk>
| <expression> [ AS <column_alias> ]
The details of the column to be retrieved.
<table_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
The table name which will be the source for the selected columns, with optional schema name.
<column_alias> ::= <identifier>
The column alias used to refer to an expression.
<asterisk> ::= *
You use an asterisk (*) to select all columns from all tables or views listed in the FROM clause. If you provide a
schema name or a table name with an asterisk(*), it is used to limit the scope of the result set to the specified
table.
FROM clause
The from clause specifies inputs such as tables, views, and subqueries to be used in the select statement.
<from_clause> ::= FROM <table>[{, <table>}...]
The list of tables where the SELECT data is sourced from.
<table> ::= <table_name> [ [AS] <table_alias> ] | <subquery> [ [AS] <table_alias> ] | <joined_table>
The table, subquery or join which will be the data source for the query.
<table_alias> ::= <identifier>
The alias identifier for a table, subquery or joined table.
<joined_table> ::= <table> [<join_type>] JOIN <table> ON <predicate>
| <table> CROSS JOIN <table> | <joined_table>
Specifies how tables should be joined.
ON <predicate>
Specifies a join predicate.
CROSS JOIN
Specifies that a cross join shoul be performed.
Note:
A cross join produces the cross-product of two tables.
<join_type> ::= INNER | { LEFT | RIGHT | FULL } [OUTER]
Specifies the type of join to be performed:
LEFT defines a left outer join.
RIGHT defines a right outer join.
FULL indicates a full outer join.
SAP HANA Database - SQL Reference Manual
119 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 120/193
OUTER
Specifies that an outer join should be performed.
WHERE clause
<where_clause> ::= WHERE <condition>
The WHERE clause is used to specify predicates on inputs in the FROM clause,
<condition> ::= <condition> OR <condition> | <condition> AND <condition>
| NOT <condition> | ( <condition> ) | <predicate>
<predicate> ::= <comparison_predicate>| <range_preciate>
| <in_predicate> | <exist_predicate>
| <like_predicate> | <null_predicate>
<comparison_predicate> ::= <expression> { = | != | <> | > | < | >= | <= }
[ ANY | SOME | ALL ] ({<expression_list> | <subquery>})
<range_predicate> ::= <expression> [NOT] BETWEEN <expression> AND <expression>
<in_predicate> ::= <expression> [NOT] IN ( { <expression_list> | <subquery> } )
<exist_predicate> ::= [NOT] EXISTS ( <subquery> )
<like_predicate> ::= <expression> [NOT] LIKE <expression> [ESCAPE <expression>]
<null_predicate> ::= <expression> IS [NOT] NULL
<expression_list> ::= {<expression>, ... }
GROUP BY clause
<group_by_clause> ::= GROUP BY { <group_by_expression_list> | <grouping_set> }
The GROUP BY clause is used to group the selected rows based on the values in the specified columns.
<group_by_expression_list> ::= { <expression>, ... }
<grouping_set> ::= { GROUPING SETS | ROLLUP | CUBE }
[BEST <signed_integer>]
[LIMIT <unsigned_integer>[OFFSET <unsigned_integer>] ]
[WITH SUBTOTAL] [WITH BALANCE] [WITH TOTAL]
[TEXT_FILTER <filterspec> [FILL UP [SORT MATCHES TO TOP]]]
[STRUCTURED RESULT [WITH OVERVIEW] [PREFIX <prefix_table_name>]
| MULTIPLE RESULTSETS]
( <grouping_expression_list> )
<grouping_expression_list> ::= { <grouping_expression>, ... }
<grouping_expression> ::= <expression> | ( <expression>, ... )
| ( ( <expression>, ... ) <order_by_clause> )
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 produced will be the same as a UNION ALL of the aggrega tion of
each specified group.
For example
select col1, col2, col3, * count(*) from t group by grouping sets ( (col1, col2), (
col1, col3) )
\encode
is equivalent to
\code 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
SAP HANA Database - SQL Reference Manual
120 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 121/193
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 sets that result set contains
is the number of columns in ROLLUP list plus one for a 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 sets 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 <signed_integer>
Returns only the top-n grouping sets sorted in descending order of the number of rows aggregated in each
grouping set. <signed_integer> can be zero, positive, and negative. When n is zero, it is the same as the BEST
option not being set. When n is negative, it means sorting in ascending order.
LIMIT <unsigned_integer> [OFFSET <unsigned_integer>]
Returns the first <unsigned_integer> grouped records after skipping OFFSET<unsigned_integer> for each
grouping set.
WITH SUBTOTAL
Returns an additional subtotal for each grouping set in the returned results controlled by OFFSET or LIMI T.
Unless OFFSET and LIMIT are specified, the value is the same as WITH TOTAL.
WITH BALANCE
Returns for each grouping set a n additional aggregated value of the remaining values not returned by
OFFSET or LIMI T.
WITH TOTAL
Returns for each grouping set an additional row that is the aggregated total value. OFFSET and LIMIT options
do not change this value.
TEXT_FILTER <filterspec>
Performs text filtering or highlighting on the grouping columns using a <filterspec>, which is a single-quoted
string that follows the below syntax.
<filterspec> ::= '[<prefix>]<element>{<subsequent>, ...}'
<prefix> ::= + | - | NOT
<element> ::= <token> | <phrase>
<token> ::= !! Unicode letters or digits
<phrase> ::= !! double-quoted string that does not contain double quotat
ions inside
<subsequent> ::= [<prefix_subsequent>]<element>
<prefix_subsequent> ::= + | - | NOT | AND | AND NOT | OR
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 in a case-insensitive
SAP HANA Database - SQL Reference Manual
121 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 122/193
manner. For example, 'ab' matches 'ab cd' and 'cd Ab' but does not match 'abcd'. A token can contain the
wildcard character ‘*’ that matches any string and ‘?’ that matches any character. Inside a phrase ‘*’ and ‘?’
do not function as wildcard characters. With tokens and phrases logical operators AND, OR and NOT ca n be
used together. As OR is the default operator, 'ab cd' is the same as 'ab OR cd'
Note:Logical operators should be written in uppercase characters.
Prefixes '+' and '-' mean inclusion (AND) and exclusion (AND NOT), respectively. For example, 'ab -cd' is the
same as 'ab AND NOT cd'. If FILL UP is not specified, only grouped records that have matching values are
returned.
Note:
A filter is applied only to the first grouping column in each grouping set.
FILL UP
Returns not only matched grouped records, but also non-matched records. TEXT_FILTER is useful to identify
which records have been matched. See 'Related Functions' below.
SORT MATCHES TO TOP
Returns matching values before non-matching values for each grouping set. This option cannot be used with
SUBTOTAL, BALANCE and TOTAL.
STRUCTURED RESULT
Returns results as temporary tables. For each grouping set a single temporary table is created. If the WITH
OVERVIEW option is set, an additional temporary table is created for the overview of the grouping sets. The
names of the temporary tables are specified by the PREFIX option.
WITH OVERVIEW
Returns an overview in a separate additional table.
PREFIX <prefix_table_name>
<prefix_table_name> ::= #<identifier>
Specifies a prefix for naming the temporary tables. <prefix_table_name> must start with "#", which means atemporary table. I f PREFIX is not specified, the default prefix is "#GN" followed by a nonnegative integer
number. See 'Return Format' below.
MULTIPLE RESULTSETS
Specifies that results should be returned in multiple result sets.
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 ofall 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.
HAVING clause
<having_clause> ::= HAVING <condition>
Selects the specified groups that satisfy the predicates. If this clause is omitted, all g roups are selected.
SAP HANA Database - SQL Reference Manual
122 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 123/193
SET OPERATORS
The set operators enable multiple select statements to be combined but return only one result set.
<set_operator> ::= UNION [ ALL | DISTINCT ] | INTERSECT [DISTINCT] | EXCEPT [DISTIN
CT]
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 has the same function as UNION DI STINCT.
INTERSECT [DISTINCT]
Returns records that exist in all select statement results.
EXCEPT [DISTINCT]
Returns all unique records from the first select statements after removing the duplicates in the following
select statements.
ORDER BY clause
<order_by_clause> ::= ORDER BY { <order_by_expression>, ... }
The ORDER BY clause is used to sort records by expressions or positions.
<order_by_expression> ::= <expression> [ ASC | DESC ] [ NULLS FIRST | NULLS LAST ]
| <position> [ ASC | DESC ] [ NULLS FIRST | NULLS LAST ]
<position> ::= <unsigned_integer>
<position> uses the entries in the select list to define the ordering required. For example:
SELECT col1, col2 FROM t ORDER BY 2
"ORDER BY 2" indicates that ordering should be undertaken using the second expression in the select list,
which in this case is "col2".
[ ASC | DESC ]
\encode
Default: ASC
ASC sorts records in ascending order. DESC sorts records in descending order.<br>
\code
[ NULLS FIRST | NULLS LAST ]
Specifies where in the results set NULL values should appear. By default for ascending ordering NULL values
are returned first, and for descending they are returned last. You ca n override this behavior using NULLS
FIRST or NULLS LAST to explicitly specify NULL value ordering.
LIMIT
<limit> ::= LIMIT <unsigned_integer> [ OFFSET <unsigned_integer> ]
Limits the number of output records. For example:
LIMIT 3 [OFFSET 5]
Returns the first 3 records after skipping 5 records.
FOR UPDATE
<for_update> ::= FOR UPDATE [OF <update_column_name_list>]
Locks the selected records so that other users cannot lock or change the records until end of this transaction.
SAP HANA Database - SQL Reference Manual
123 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 124/193
<update_column_name_list>> ::= ( <column_name>[{, <column_name>}...] )
A list of columns is used to specify which table or view in the FROM clause should be locked. If there is only a
single table or view, FOR UPDATE will suffice. However, if there are two objects (e.g., tables, views, and,
subqueries), OF should be used.
Note:
A table used in a subquery cannot be locked. Also that only one table/view can be currently locked.
The lock is released when the corresponding transaction is finished by commit or rollback.
create column table x ( a int, b int );
insert into x values (1,1);
insert into x values (2,2);
create column table y ( a int, b int );
insert into y values (1,1);
insert into y values (2,2);
select * from x where a=1 for update; --> OK
commit;
select * from x where a=1 for update of x.c; --> error because c column does not ex
ist in table x.
select * from x where a=1 for update of x.a; --> OK
commit;
select * from x, y where a=1 for update; --> error because "OF" is not used to spec
ify which one of x and y is locked.
select * from x, y where a=1 for update of y.b; --> OK
commit;
select * from x, (select * from y) where a=1 for update of y.b; --> error because
y is inside subquery
commit;
TIME TRAVEL
Keywords related with time travel can be used for statement-level time travel to go back to the snapshot
specified by commit_id or utctimestamp.
<time_travel> ::= AS OF { { COMMIT ID <commit_id> } | { UTCTIMESTAMP <timestamp> }
}
Time travel is possible only with a history column table. <commit_id> can be obtained fromm_history_index_last_commit_id after each commit and its related <timestamp> can be obtained from
sys.m_transaction_history.
For example:
create history column table x ( a int, b int ); // after turnning off auto commit
insert into x values (1,1);
commit;
select last_commit_id from m_history_index_last_commit_id where session_id = curren
t_connection; // e.g., 10
insert into x values (2,2);
commit;
select last_commit_id from m_history_index_last_commit_id where session_id = curren
t_connection; // e.g., 20
delete from x;
commit;
select last_commit_id from m_history_index_last_commit_id where session_id = curren
t_connection; // e.g., 30
select * from x as of commit id 30; // return nothing
select * from x as of commit id 20; // return two records (1,1) and (2,2)
select * from x as of commit id 10; // return one record (1,1)
select commit_time from sys.transaction_history where commit_id = 10; // e.g., '201
2-01-01 01:11:11'
select commit_time from sys.transaction_history where commit_id = 20; // e.g., '201
2-01-01 02:22:22'
select commit_time from sys.transaction_history where commit_id = 30; // e.g., '201
2-01-01 03:33:33'
select * from x as of utctimestamp '2012-01-02 02:00:00'; // return one record (1,1
)
select * from x as of utctimestamp '2012-01-03 03:00:00'; // return two records (1,
1) and (2,2)
select * from x as of utctimestamp '2012-01-04 04:00:00'; // return nothing
SAP HANA Database - SQL Reference Manual
124 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 125/193
Examples
You create column table t1 and populate it with some example data.
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);
Example 1 - GROUPING SETS
You use grouping sets to analyze the customer data.
Note:
The this query is equivalent to example 3 below.
select customer, year, product, sum(sales)
from t1
group by GROUPING SETS
(
(customer, year),
(customer, product)
);
select customer, year, NULL, sum(sales)
from t1
group by customer, year
union all
select customer, NULL, product, sum(sales)
from t1
group by customer, product;
Observe that the two groups inside grouping sets in the first query are specified in each GROUP BY clause in
the second query.
Example 2 - ROLLUP
You use ROLLUP to generates results with multiple levels of aggrega tion.
Note:
The following ROLLUP query is equivalent to Example 4 below.
select customer, year, sum(sales)
from t1
group by ROLLUP(customer, year);
select customer, year, sum(sales)
from t1
group by grouping sets
(
(customer, year),
(customer) )
union all
select NULL, NULL, sum(sales)
from t1;
Example 3 - CUBE
You use CUBE to generates results with multiple levels of aggregation.
Note:
The following CUBE query is equivalent to the query in Example 5.
select customer, year, sum(sales)
from t1
group by CUBE(customer, year);
SAP HANA Database - SQL Reference Manual
125 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 126/193
select customer, year, sum(sales)
from t1
group by grouping sets
(
(customer, year),
(customer),
(year)
)
union all
select NULL, NULL, sum(sales)
from t1;
Example 4 - BEST 1
You use BEST 1 to return only the best group of results.
select customer, year, product, sum(sales)
from t1
group by grouping sets BEST 1
(
(customer, year),
(product)
);
In this example, 4 records exist for (customer, year) group and 2 records exist for (product) group, so the
former 4 records are returned. If you used 'BEST -1' instead of 'BEST 1', the latter 2 records would be
returned.
Example 5 - LIMIT
You use LIMIT 2 to limit the number of records to a maximum 2 for each group.
select customer, year, product, sum(sales)
from t1
group by grouping sets LIMIT 2
(
(customer, year),
(product)
);
For the (customer, year) group, the number of records are 4, so only first 2 records will be returned. For the
(product) group, the number of records are 2, in this case all the records will be returned.
Example 6 - WITH SUBTOTAL
you use WITH SUBTOTAL to produce an additional record for each group that displays a subtotal of returned
records. These subtotal records are NULL for the customer, year, product columns and the sum of sum(sales)
values in the select list.
select customer, year, product, sum(sales)
from t1
group by grouping sets LIMIT 2 WITH SUBTOTAL
(
(customer, year),
(product)
);
Example 7 - WITH BALANCE
You use WITH BALANCE to produce an additional record for each group that displays a subtotal of unreturned
records.
select customer, year, product, sum(sales)
from t1
group by grouping sets LIMIT 2 WITH BALANCE
(
(customer, year),
(product)
);
Example 8 - WITH TOTAL
You use WITH TOTAL to produce an additional record for each group that displays a total of all grouped
SAP HANA Database - SQL Reference Manual
126 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 127/193
records.
select customer, year, product, sum(sales)
from t1
group by grouping sets LIMIT 2 WITH TOTAL
( (customer, year),
(product)
);
Example 9 - TEXT_FILTER
You use TEXT_FILTER to retrieve the first column of each g roup with a g iven <filterspec>. The following query
will search for columns ending with '2'. This will be applied to customers for in first grouping set and products
in the second. Only three matched records will be returned.
select customer, year, product, sum(sales), text_filter(customer), text_filter(prod
uct)
from t1
group by grouping sets TEXT_FILTER '*2'
(
(customer, year),
(product) );
Example 10 - FILL UP
You use FILL UP to return both matched and non-matched records with <filterspec>. The following query
returns six records whereas the previous example only returned three.
select customer, year, product, sum(sales), text_filter(customer), text_filter(prod
uct)
from t1
group by grouping sets TEXT_FILTER '*2' FILL UP
(
(customer, year),
(product)
);
Example 11 - SORT MATCHES TO TOP
SORT MATCHES TO TOP is used to raise matched records up. For each grouping set, its grouped records will
be sorted.
select customer, year, product, sum(sales), text_filter(customer), text_filter(prod
uct)
from t1
group by grouping sets TEXT_FILTER '*2' FILL UP SORT MATCHES TO TOP
(
(customer, year),
(product)
);
Example 12 - STRUCTURED RESULT
You use STRUCTURED RESULT to create temporary tables, one for each grouping set and an additional table
for the overview table.
select customer, year, product, sum(sales)
from t1
group by grouping sets STRUCTURED RESULT
(
(customer, year),
(product)
);
select * from "#GN1";
select * from "#GN2";
"#GN1" table is for (customer, year) g rouping set and "#GN2" table is for (product) one.
Note:
Each table contains only related columns. That is to say, "#GN1" table does not have "product"
SAP HANA Database - SQL Reference Manual
127 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 128/193
column and "#GN2" table does not have "customer" and "year" columns.
You use WITH OVERVIEW to create a temporary table "#GN0" for the overview table.
drop table "#G1";
drop table "#G2";
select customer, year, product, sum(sales)
from t1
group by grouping sets structured result WITH OVERVIEW
(
(customer, year),
(product)
);
select * from "#GN0";
select * from "#GN1";
select * from "#GN2";
You change the names of temporary tables by using the PREFIX keyword.
Note:
the names of tables must still must start with '#' which is the prefix used for temporary tables.
select customer, year, product, sum(sales)
from t1
group by grouping sets STRUCTURED RESULT WITH OVERVIEW PREFIX '#MYTAB'
(
(customer, year),
(product)
);
select * from "#MYTAB0";
select * from "#MYTAB1";
select * from "#MYTAB2";
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.
select * from m_temporary_tables;
Example 13 - MULTIPLE RESULTSETS
You use MULTIPLE RESULTSETS to return multiple result sets. The following query will return three result
sets, one for the overview table and two for the grouping sets.
select customer, year, product, sum(sales)
from t1
group by grouping sets MULTIPLE RESULTSETS
(
(customer, year),
(product)
);
TRUNCATE TABLE
Syntax
TRUNCATE TABLE <table_name>
Description
Deletes all rows from a table. TRUNCATE is faster than DELETE FROM when deleting all records from a table,
but TRUNCATE cannot be rolled back. To rollback from deleting records, "DELETE FROM <table_name>"
should be used.
HISTORY tables can also be truncated in the same way as normal tables by executing this command. All parts
of the history table (main, delta, history main and history delta) will be deleted and the content will be lost.
Example
You create table A.
SAP HANA Database - SQL Reference Manual
128 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 129/193
CREATE TABLE A (A INT PRIMARY KEY, B INT);
You truncate the contents of table A.
TRUNCATE TABLE A
UNLOAD
Syntax
UNLOAD <table_name>
Syntax Elements
<table_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
The name of the table to be unloaded from memory
Description
The UNLOAD statement unloads the column store table from memory. This can be done to free up memory.
The table will be loaded again on next access.
Example
You create column table A.
CREATE COLUMN TABLE A (A INT, B INT);
You load table A into memory.
LOAD A all;
You unload table A from memory.
UNLOAD A;
You check the load status of table A.
select loaded from m_cs_tables where table_name = 'A'
UPDATE
Syntax
UPDATE <target_table> <set_clause> [ <from_clause> ] [ WHERE <condition> ]
Syntax Elements
<target_table> ::= <table_name> | <alias_name>
<table_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
<alias_name> ::= [AS] <identifier>
For descriptions on identifier, please refer to Identifiers.
<set_clause> ::= SET {<column_name> = <expression>},...
For descriptions on expressions, please refer to Expressions .
<from_clause> ::= FROM {<table>, ...}
For detailed descriptions on from_clause, please refer to FROM clause.
<condition> ::= <condition> OR <condition>
| <condition> AND <condition>
SAP HANA Database - SQL Reference Manual
129 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 130/193
| NOT <condition>
| ( <condition> )
| <predicate>
For descriptions on predicates, please refer to Predicates.
Description
The UPDATE statement changes the values of the records of a table where the condition is met. The FROM
clause can specify that a table, view, or derived object that is used to provide the criteria for the update
operation. If the FROM clause exists and the object being updated is included in the FROM clause, there is
only one reference to the object being updated. If the WHERE clause condition is true, the result of
expression is assigned to that column. I f the WHERE clause is omitted, then it updates all records of a table.
Examples
You create table T, and insert two rows into it.
CREATE TABLE T (KEY INT PRIMARY KEY, VAL INT);
INSERT INTO T VALUES (1, 1);
INSERT INTO T VALUES (2, 2);
You update the rows of table T if the condition in the WHERE clause is true.
UPDATE T SET VAL = VAL + 1 WHERE KEY = 1;
KEY VAL
1 2
2 2
You update all rows of table T because a where clause is not specified as part of the update statement.
UPDATE T SET VAL = KEY + 10;
KEY VAL
1 11
2 12
You create table T2, and insert two rows into it.
CREATE TABLE T2 (KEY INT PRIMARY KEY, VAR INT);
INSERT INTO T2 VALUES (1, 2);
INSERT INTO T2 VALUES (3, 6);
You update the values of table T by joining the targ et table T with table T2.
UPDATE T SET VAL = T2.VAR FROM T, T2 WHERE T.KEY = T2.KEY;
KEY VAL
1 2
2 2
System Management Statements
ALTER SYSTEM ALTER CONFIGURATION
Syntax
ALTER CONFIGURATION (<filename>, <layer>[, <layer_name>]) SET | UNSET
<parameter_key_value_list> [ WITH RECONFIGURE]
Syntax Elements
<filename> ::= <string_literal>
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.
SAP HANA Database - SQL Reference Manual
130 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 131/193
<layer> ::= <string_literal>
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.
<layer_name> ::= <string_literal>
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> ::=
{(<section_name>,<parameter_name>) = <parameter_value>},...
Specifies the section, key and value of the ini file parameter to be altered as follows:
<section_name> ::= <string_literal>
The section name of the parameter to be altered.
<parameter_name> ::= <string_literal>
The name of the parameter to be a ltered.
<parameter_value> ::= <string_literal>
The value of the parameter to be a ltered.
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 thedatabase. 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.
The following is an example of ini file locations:
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.
System and Monitoring Views
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
You set a parameter new_test_value in the alt_sys_test section of the golbal.ini file.
SAP HANA Database - SQL Reference Manual
131 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 132/193
ALTER SYSTEM ALTER CONFIGURATION ('global.ini', 'SYSTEM') SET ('alt_sys_test', 'new
_test_value') = 'test';
You check the setting of the parameter in the SAP HANA studio. In t he Navigator you right click on the
system where you made the change and select Administration then select the Configuration tab. Expandthe global.ini configuration file and then the alt_sys_test section.
You unset the new_test_value parameter set in the previous step.
ALTER SYSTEM ALTER CONFIGURATION ('global.ini', 'SYSTEM') UNSET ('alt_sys_test', 'n
ew_test_value');
You check the removal of the parameter by clicking refresh on the Configuration page in the SAP HANA
studio.
ALTER SYSTEM ALTER SESSION SET
Syntax
ALTER SYSTEM ALTER SESSION <session_id> SET <key> = <value>
Syntax Elements
<session_id> ::= <unsigned_integer>
The session ID of the session where the variable should be set.
<key> ::= <string_literal>
The key of a session variable. The maximum length of key is 32 characters.
<value> ::= <string_literal>
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 database sessions.
Note:
There are several 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 ALTER SYSTEM
ALTER SESSION UNSET command.
Example
Note:
Please run each command in this example in the same SQL Editor in the SAP HANA studio. This is
because you need to use the same database session to make the example work properly.
You obtain your current session ID.
SELECT connection_id FROM m_connections WHERE OWN = 'TRUE';
You set the variable MY_VAR to 'some_value' in your session. In the command below replace
<your_session_id> with the session ID that you discovered from the command above.
ALTER SYSTEM ALTER SESSION <your_session_id> SET 'MY_VAR'= 'some_value';
You check the current value of MY_VAR in your session.
SELECT SESSION_CONTEXT('MY_VAR') FROM dummy;
ALTER SYSTEM ALTER SESSION UNSET
Syntax
SAP HANA Database - SQL Reference Manual
132 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 133/193
ALTER SYSTEM ALTER SESSION <session_id> UNSET <key>
Syntax Elements
<session_id> ::= <unsigned_integer>
The session ID of the session where the variable should be unset.
<key> ::= <string_literal>
The key of a session variable. The maximum length of key is 32 characters.
Description
With this command you can unset session variables of database sessions.
Note:
There are several read-only session variables that you cannot change with this command:
APPLICATION, APPLICATIONUSER, TRACEPROFILE.
Session variables can be retrieved using SESSION_CONTEXT function.
Example
You set the session variable MY_VAR to 'abc' in your database session.
SET 'MY_VAR' = 'abc';
You get a list of all the session variables of the current session.
SELECT * FROM M_SESSION_CONTEXT WHERE CONNECTION_ID = CURRENT_CONNECTION
You remove the session variable from the specified session. In the command below replace <your_session_id>
with the session ID that you discovered from the command above.
ALTER SYSTEM ALTER SESSION <your_session_id> UNSET 'MY_VAR';
You get a list of all the session variables of the current session.
SELECT * FROM M_SESSION_CONTEXT WHERE CONNECTION_ID = CURRENT_CONNECTION
From the results of this command you can see that the MY_VAR variable has been unset.
ALTER SYSTEM CANCEL [WORK IN] SESSION
Syntax
ALTER SYSTEM CANCEL [WORK IN] SESSION <session_id>
Syntax Elements
<session_id> ::= <string_literal>
The session ID of the required session.
Description
Cancels the currently executing statement of a session. The transaction of the cancelled session will be rolled
back. The statement that was executing will return error code 139 (current operation cancelled by request
and transaction rolled back).
Example
You use the following query to obtain current database connection IDs and to view the statements that the
sessions are executing.
SELECT C.CONNECTION_ID, PS.STATEMENT_STRING
SAP HANA Database - SQL Reference Manual
133 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 134/193
FROM M_CONNECTIONS C JOIN M_PREPARED_STATEMENTS PS
ON C.CONNECTION_ID = PS.CONNECTION_ID AND C.CURRENT_STATEMENT_ID = PS.STATEM
ENT_ID
WHERE C.CONNECTION_STATUS = 'RUNNING'
AND C.CONNECTION_TYPE = 'Remote'
Using the connection ID information you obtained using the query above, you can now cancel a running
query. In the statement below you replace <connection_id> with a connection ID from the query above.
ALTER SYSTEM CANCEL SESSION '<connection_id>'
ALTER SYSTEM CLEAR SQL PLAN CACHE
Syntax
ALTER SYSTEM CLEAR SQL PLAN CACHE
Description
The SQL PLAN CACHE stores plans generated by previous SQL statement executions. The plan cache is used by
the SAP HANA database to speed up query exectution if the same SQL statement is executed aga in.The plan
cache also collects some statistics regarding plan preparation and execution.
You can find details about the contents of the SQL plan cache from the following monitoring views:
M_SQL_PLAN_CACHE, M_SQL_PLAN_CACHE_OVERVIEW
The ALTER SYSTEM CLEAR SQL PLAN CACHE statement removes all the SQL plans that are not currently
executing from the plan cache. The command also removes all plans having reference count of '0' from the
plan cache and resets all the stat istics of the remaining plans. Lastly the command also reset the contents of
M_SQL_PLAN_CACHE_OVERVIEW monitoring view.
Example
You clear the SQL plan cache.
ALTER SYSTEM CLEAR SQL PLAN CACHE
ALTER SYSTEM CLEAR TRACES
Syntax
ALTER SYSTEM CLEAR TRACES (<trace_type_list>)
Syntax Elements
<trace_type_list> ::= <trace_type> [,...]
You can clear multiple traces simultaneously by adding multiple trace_types in a comma delimited list.
<trace_type> ::= <string_literal>
You can selectively clear specific trace files by setting the trace_type to one of the following types:
<trace_type> Trace Files
ALERT *alert_*.trc
CLIENT l oca lcl i ent_*.trc
CRASHDUMP *.cra shdump.*
EMERGENCYDUMP *.emergencydump.*
* a l l *.trc fi les of servi ces l i s ted bel ow
INDEXSERVER,NAMESERVER,...,DAEMON open *.trc files of a single service type
Description
You use the ALTER SYSTEM CLEAR TRACES to clear trace contents from trace files. When you use this
command all trace files that were opened by the SAP HANA data base will be removed or cleared. On
distributed systems, this command will clear all trace files on all hosts.
SAP HANA Database - SQL Reference Manual
134 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 135/193
Use this command to reduce disk space used by large tracefiles, e. g. when trace components are set to INFO
or DEBUG.
You can monitor trace files and trace file contents using the M_TRACEFILES, M_TRACEFILE_CONTENTS
system tables respectively.
Examples
You clear the alert trace file.
ALTER SYSTEM CLEAR TRACES('ALERT');
You clear the alert and client trace files.
ALTER SYSTEM CLEAR TRACES('ALERT', 'CLIENT');
ALTER SYSTEM DISCONNECT SESSION
Syntax
ALTER SYSTEM DISCONNECT SESSION <session_id>
Syntax Elements
<session_id> ::= <string_literal>
The session ID of the session to be disconnected.
Description
You use ALTER SYSTEM DISCONNECT SESSION to disconnect a specified session from the database. Before
disconnection any currently running operations associated with the session will be terminated.
Example
You use the command below to obtain the session IDs of idle sessions.
SELECT CONNECTION_ID, IDLE_TIME FROM M_CONNECTIONS
WHERE CONNECTION_STATUS = 'IDLE' AND CONNECTION_TYPE = 'Remote'
ORDER BY IDLE_TIME DESC
You disconnect a session. In the statement below you replace <connection_id> with a connection ID from the
query above.
ALTER SYSTEM DISCONNECT SESSION '<connection_id>'
ALTER SYSTEM LOGGING
Syntax
ALTER SYSTEM LOGGING <on_off>
Syntax Elements
<on_off> ::= ON | OFF
ON
Enable logging.
OFF
Disable logging.
Description
You used this command to Enable or disable logging.
While logging is disabled no log entries will be persisted, only the data area will be written when a savepoint
SAP HANA Database - SQL Reference Manual
135 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 136/193
is reached. This can cause loss of committed transactions, when the indexserver terminated in the middle of
a LOAD operation. In case of a t ermination, you will have to truncate and insert all data again.
After enabling logging you have to perform a savepoint to be sure that all data will be persisted. You will also
have to perform a data backup, otherwise you will be unable to recover this data.
ALTER SYSTEM LOGGING waits for the end (commit/rollback) of existing active write transactions. During the
execution this command write transactions are blocked. In the event that there is a long-running write
transaction, this command can be failed with a lock wait t imeout error. Starting a new write transaction also
can be blocked and failed with the same error.
Due to the potential generation of the errors mentioned above you should only use this command for initial
load. If used at other t imes data loss can occur if the indexserver is terminated whilst logging is disabled.
Consequently, in a running system, the logging mode should be always ON and should not be altered.
You can also adjust the logging settings for single column tables with ALTER TABLE <table_name> [ENABLE |
DISABLE] DELTA LOG
Example
You disable system logging.
ALTER SYSTEM LOGGING OFF;
You enable system logging.
ALTER SYSTEM LOGGING ON;
See Also
ALTER TABLE
ALTER SYSTEM PERSISTENCE ENCRYPTION
Syntax
ALTER SYSTEM PERSISTENCE ENCRYPTION <encrypt_option>
Syntax Elements
<encrypt_option> ::= ON
| OFF
| CREATE NEW KEY
| APPLY CURRENT KEY
ON
Switch on encryption.
OFF
Switch off encryption.
CREATE NEW KEY
Force the creation of a new random encryption key.
APPLY CURRENT KEYForce all existing old data to be encrypted using the current encryption key.
Description
You use ALTER SYSTEM PERSISTENCE ENCRYPTION to define if persistent data should be stored on disk in
encrypted or non-encrypted format. You can also use this command to recreate the random encryption key.
When you switch on encryption, a random encryption key is prepared and an asynchronous background task
is started which encrypts all disk data with this key.
When you switch off encryption, an asynchronous background task is started which decrypts all encrypted
disk data.
When you use CREATE NEW KEY, the instance is forced to prepare a new random encryption key. This key will
begin to be used after the next savepoint has occurred. The time in which this takes to occur is depending on
the current workload of the SAP HANA database. No changes will be made to old written disk data.
SAP HANA Database - SQL Reference Manual
136 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 137/193
When you invoke APPLY CURRENT KEY, disk data that is encrypted with an old key is implicitly decrypted
using the old key and then encrypted again with the current key. You may wish to do this if an old key was
compromised or if you want to consolidate a set of old keys. When new key has been created with CREATE
NEW KEY and then APPLY CURRENT KEY is called, a savepoint is internally triggered so that the new key can
be used for encryption of old data.
Note:
Currently only the finally written disk data will be encrypted. The redo log is not affected by this
command. For more information about the redo log please see the "Backing Up and Recovering the
SAP HANA database" section in the "SAP HANA Administration guide" available from the SAP HANA
Appliance page.
Example
You cause a non-encrypted instance to begin the asynchronous task of encrypting disk data.
ALTER SYSTEM PERSISTENCE ENCRYPTION ON
*
See Also
For more information about the use of Encryption in the SAP HANA database please see the "Managing Da ta
Volume Encryption" section in the "SAP HANA Administration guide" available from the SAP HANA Appliance
page.
ALTER SYSTEM RECLAIM DATAVOLUME
Syntax
ALTER SYSTEM RECLAIM DATA VOLUME [SPACE] [<host_port>] <percentage_of_overload_si
ze> <shrink_mode>
Syntax Elements
<host_port> ::= 'host_name:port_number'
Specifies the server on which the size of the persistency should be reduced.
<percentage_of_overload_size> ::= <int_const>
Specifies to which percentage of the overload size the data volume should be reduced.
<shrink_mode> ::= DEFRAGMENT | SPARSIFY
Specifies the strategy to reduce the persistency size. DEFRAGEMENT is the default. Please note that
SPARSIFY is not supported yet and reserved for future use.
Description
The command should be used when unused space inside the persistencies should be freed. It 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 volumewill be truncated.
If <host_port> is omitted the statement is distributed to all servers with persistence.
Example
In the example below the persistencies of all servers in the landscape are defragmented and reduced to
120% of the overload size.
ALTER SYSTEM RECLAIM DATAVOLUME 120 DEFRAGMENT
ALTER SYSTEM RECLAIM LOG
Syntax
SAP HANA Database - SQL Reference Manual
137 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 138/193
ALTER SYSTEM RECLAIM LOG
Description
You use this command when the database has accumulated a lot of log segments and you want to reclaim
disk space of currently unused log segments.
Log segment accumulation can be caused in several ways. For example, when the automatic log backup is
not operational for a long period or the log savepoint is blocked for an extended time. When such an issue
occurs you use the ALTER SYSTEM RECLAIM LOG command only after the root cause of the log accumulation
has been fixed.
Example
You reclaim disk space of currently unused log segments using the following command:
ALTER SYSTEM RECLAIM LOG
ALTER SYSTEM RECLAIM VERSION SPACE
Syntax
ALTER SYSTEM RECLAIM VERSION SPACE
Description
This command triggers the row-store garbage collector to free up memory space and enhance system
responsiveness.
You do not need to use this command if only short transactions are being executed on the system. This is
because the garbage collector is automatically trigg ered when a transaction ends. If there are long-running
transactions on the system, this command helps overall system performance if the m_mvcc_tables
monitoring view shows a large number of row-store versions(e.g. over 1M).
System Tables and Monitoring Views
m_mvcc_tables shows the number of row-store versions in the system.
Example
You check the number of row-store versions on the system using the m_mvcc_tables monitoring view.
SELECT * FROM m_mvcc_tables
You trigger row-store garbage collection.
ALTER SYSTEM RECLAIM VERSION SPACE
ALTER SYSTEM RECONFIGURE SERVICE
Syntax
ALTER SYSTEM RECONFIGURE SERVICE (<service_name>,<host>,<port>)
Syntax Element
<service_name> ::= <string_literal>
The name of the service you wish to reconfigure. See M_SERVICE_TYPES monitoring view for a list of
available service types.
<host> ::= <string_literal>
<port> ::= <unsigned_integer>
The host and port number where you would like to reconfigure a service.
Description
SAP HANA Database - SQL Reference Manual
138 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 139/193
You use ALTER SYSTEM R ECONFIGURE SERVICE to reconfigures a specified service by applying the current
configuration parameters.
This command is used after changing multiple configuration parameters with the ALTER CONFIGURATION
command without the RECONFIGURE option set. See ALTER SYSTEM ALTER CONFIGURATION
To reconfigure a specific service specify <host> and <port> and leave <service_name> empty.
To reconfigure all services of a type, specify <service_name> and leave <host> and <port> empty.
To reconfigure all services, leave all parameters empty.
Example
You use the following command to reconfigure all services on the hana.hana.com host using port number
30303:
ALTER SYSTEM RECONFIGURE SERVICE ('','hana.yourcompany.com',30303)
You use the following command to reconfigure all services of type indexserver:
ALTER SYSTEM RECONFIGURE SERVICE ('indexserver','',0)
See Also
ALTER SYSTEM ALTER CONFIGURATION
ALTER SYSTEM REMOVE TRACES
Syntax
ALTER SYSTEM REMOVE TRACES (<host>, <trace_type_name_list>)
Syntax Elements
<host> :== <string_literal>
The name of the host where the traces are to be removed.
<trace_type_name_list> ::= <trace_file> [{, trace_file>}...]
The trace file types to be removed.
<trace_file> :== !!see table below.
You set the <trace_file> parameter to one of the file specifications shown in the table below.
Trace Type <trace_file>
ALERT *alert_*.trc
CLIENT l oca lcl i ent_*.trc
CRASHDUMP *.cra shdump.*
EMERGENCYDUMP *.emergencydump.*
* a l l *.trc fi les of servi ces l i s ted bel ow
INDEXSERVER,NAMESERVER,...,DAEMON open *.trc files of a single service type
Description
You use this command to Delete the trace files on a specified host to reduce disk space used by large trace
files. When a service has a trace file open it cannot be deleted. In this case you can clear the trace file using
the ALTER SYSTEM CLEAR TRACES command.
Example
You use the command below to delete all of the ALERT traces from the lu873.sap.com host.
ALTER SYSTEM REMOVE TRACES ('lu873.sap.com', '*alert_*.trc');
SAP HANA Database - SQL Reference Manual
139 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 140/193
See Also
ALTER SYSTEM CLEAR TRACES
ALTER SYSTEM RESET MONITORING VIEW
Syntax
ALTER SYSTEM RESET MONITORING VIEW <view_name>
Syntax Elements
<view_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
The name of the resettable monitoring view to be reset.
Note:
Not all monitoring views can be reset using this command. You can identify a view as being able to
be reset as its view name will have the suffix "_RESET".
Description
You use this command to reset statistics data for the specified monitoring view.
You use this command to define a starting point for your measurements. First, you reset the monitoring view,
then execute an action. After the action is completed, query "_RESET" version of the monitor view to get the
statistical information gathered since the last reset.
Example
In the example below you reset the "SYS"."M_HEAP_MEMORY_RESET" monitoring view.
ALTER SYSTEM RESET MONITORING VIEW "SYS"."M_HEAP_MEMORY_RESET"
ALTER SYSTEM SAVE PERFTRACE
Note:
Performance tracing is only to be used in conjunction with SAP Support personnel. The collected
perftrace data cannot be analyzed by an end user.
Syntax
ALTER SYSTEM SAVE PERFTRACE [INTO FILE <file_name>]
Syntax Elements
INTO FILE <file_name>
<file_name> ::= <string_literal>
Specifies a file where raw performance data will be saved.
Description
You use this command to collect raw performance trace data from .prf files and save the information into a
single .tpt file. The . tpt file will be saved in the trace directory of your SAP HANA database instance. If you do
not specify a file name then 'perftrace.tpt' will be used.
The performance trace data (.tpt) file can be downloaded from SAP HANA Studio. To obtain the trace files in
the Navigator pane you right click on the system you wish to diagnose. You select Administration from the
context menu and in the dialog that appears you then select the Diagnosis Files tab. You right click on a
Trace file and select Download.
System Tables and Monitoring Views
The status of the performance trace can be monitored from M_PERFTRACE.
While a trace file is saving it is shown as 'Save PerfTrace' job in M_JOB_PROGRESS.
SAP HANA Database - SQL Reference Manual
140 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 141/193
Cancellation
Saving a perftrace can take some time. You can cancel the job shown in M_JOB_PROGRESS with ALTER
SYSTEM CANCEL [WORK IN] SESSION
Example
You save raw performance trace data into the 'mytrace.tpt' file.
ALTER SYSTEM SAVE PERFTRACE INTO FILE 'mytrace.tpt'
ALTER SYSTEM SAVEPOINT
Syntax
ALTER SYSTEM SAVEPOINT
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 to disk. The consistent image can be used to restart the database.
Normally a savepoint is executed periodically as configured by the configuration parameter
savepoint_interval_s in section [persistence]. For special (normally test) purposes, the savepoint can
be disabled. In this case, you can use this command to manually execute a savepoint.
System Tables and Monitoring Views
See M_SAVEPOINT_STATISTICS for savepoint statistics
Example
You execute a savepoint on the persistence manager.
ALTER SYSTEM SAVEPOINT
ALTER SYSTEM START PERFTRACE
Note:
Performance tracing is only to be used in conjunction with SAP Support personnel. The collected
perftrace data cannot be analyzed by an end user.
Syntax
ALTER SYSTEM START PERFTRACE [<user_name>] [<application_user_name>] [<application_
name>] [PASSPORT_TRACELEVEL <passport_level>]
[PLAN_EXECUTION] [FUNCTION_PROFILER] [DURATION <durati
on_seconds>]
Syntax Element
<user_name> ::= USER <identifier>
Restricts perftrace collection to an SQL user name
<application_user_name> ::= APPLICATIONUSER <identifier>
Restricts perftrace collection to the application user name.
<application_name> ::= APPLICATION <identifier>
Restricts perftrace collection to the application name.
<passport_level> ::= MEDIUM | HIGH
Specifies the level of trace data to be collected. This is effectively a filter controlling the amount of data
collected in end-to-end scenarios.
SAP HANA Database - SQL Reference Manual
141 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 142/193
PLAN_EXECUTION
Specifies that plan execution details should be traced.
FUNCTION_PROFILER
Specifies that function level details should be traced.
<duration_seconds> ::= <numeric literal>
The number of seconds which perftrace should be collected. After this period expires perftrace is
automatically stopped. I f you do not specify this parameter you must stop perftrace with the ALTER SYSTEM
STOP PERFTRACE statement.
Description
The ALTER SYSTEM START PERFTRACE command starts performance tracing.
Only one perftrace can be active at a time.
System Tables and Monitoring Views
The status of performance trace can be monitored from M_PERFTRACE.
Example
You start performance tracing for the user sql_user on application user name app_user for application
app_name. You also specify that plan execution and function level detail should be traced.
ALTER SYSTEM START PERFTRACE USER sql_user APPLICATIONUSER app_user APPLICATION app
_name PLAN_EXECUTION FUNCTION_PROFILER
ALTER SYSTEM STOP PERFTRACE
Note:
Performance tracing is only to be used in conjunction with SAP Support personnel. The collected
perftrace data cannot be analyzed by an end user.
Syntax
ALTER SYSTEM STOP PERFTRACE
Description
Stops an active performance trace. After stopping the trace, you collect and save the performance trace
data with ALTER SYSTEM SAVE PERFTRACE.
Example
You stop an active performance trace.
ALTER SYSTEM STOP PERFTRACE
ALTER SYSTEM STOP SERVICE
Syntax
ALTER SYSTEM STOP SERVICE <host_port> [IMMEDIATE [WITH COREFILE]]
Syntax Element
<host_port> ::= <host_name:port_number> | ('<host_name>',<port_number>)
Host and port of the service to be stopped.
IMMEDIATE
SAP HANA Database - SQL Reference Manual
142 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 143/193
Immediately stop the service without waiting for regular shutdown.
WITH COREFILE
Write a core dump file.
Description
Stop single or multiple services on the designated host.
Note:
Typically a service you stop will be automatically restarted by the SAP HANA database system.
You should use this command after changing a configuration parameter that can not be changed whilst the
SAP HANA database is running.
Example
You stop a service running on host hdb1.yourcompany.com on port 30303.
ALTER SYSTEM STOP SERVICE 'hdb1.yourcompany.com:30303'
SET SYSTEM LICENSE
Syntax
SET SYSTEM LICENSE <license key>
Syntax Elements
<license key> ::= <string_literal>
The license key to be set.
Description
Installs a license key to the database instance. The license key (<license key>="">) is to be copied and pastedfrom the license key file. The system privilege LICENSE ADMIN is required to execute this command.
Example
Note:
The license shown below does not contain a license key, so you cannot run this example.
You set the system license with a license code.
SET SYSTEM LICENSE '----- Begin SAP License -----
SAPSYSTEM=HD1
HARDWARE-KEY=K4150485960
INSTNO=0110008649
BEGIN=20110809
EXPIRATION=20151231
LKEY=...
SWPRODUCTNAME=SAP-HANA
SWPRODUCTLIMIT=2147483647
SYSTEM-NR=00000000031047460'
UNSET SYSTEM LICENSE ALL
Warning:
Running this command immediately locks down your SAP HANA database. You will require a new
license key before you can use the system further.
Syntax
UNSET SYSTEM LICENSE ALL
Description
SAP HANA Database - SQL Reference Manual
143 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 144/193
Deletes all currently installed license keys. After using this command the SAP HANA database 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
You delete all currently installed license keys.
UNSET SYSTEM LICENSE ALL
Session Management Statements
CONNECT
Syntax
CONNECT <connect_option>
Syntax Elements
<connect_option> ::= <user_name> PASSWORD <password>
| WITH SAML ASSERTION '<xml>'
<user_name> ::= <simple_identifier>
<password> ::= <letter_or_digit>...
Description
Connect to the database instance by specifying user_name and password or by specifying a SAML assertion.
Example
You create a SAML provider with the name ac_saml_provider specifying a subject and issuer for ACompany.
CREATE SAML PROVIDER ac_saml_provider
WITH SUBJECT 'CN = wiki.detroit.ACompany.corp,OU = ACNet,O = ACompany,C = EN' ISSUER 'E = [email protected],CN = ACNetCA,OU = ACNet,O = ACompany,C = EN';
You create a user called new_user with password Password1. The user can connect to the system using the
given password and with an assertion of the SAML provider ac_saml_provider.
CREATE USER new_user PASSWORD Password1 WITH IDENTITY ANY FOR SAML PROVIDER ac_saml
_provider;
You connect to the database with the user name new_user and password Password1.
CONNECT new_user PASSWORD Password1
SET HISTORY SESSION
Syntax
SET HISTORY SESSION TO <when>
Elements
<when>:
User should specify an exact moment when the session is to travel
<when> ::= NOW | COMMIT ID <commit_id> | UTCTIMESTAMP <timestamp>
<commit_id> ::= <unsigned_integer>
Description
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
SAP HANA Database - SQL Reference Manual
144 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 145/193
SET HISTORY SESSION command with a COMMIT ID or UTCTIMESTAMP is issued, current session sees an old
version of history tables. If NOW option is given, current session gets back to a normal session, and sees
current version of history tables. This command only works for history tables, and visibility on normal tables is
not affected.
System Tables and Monitoring Views
The last commit id can be obtained from m_history_index_last_commit_id after each commit.
The timestamp of the last commit can be obtained from m_transaction_history.
Example
You create a history column table x, so that you can time travel through the table's history.
create history column table x ( a int, b int ); // after turnning off auto commit
You insert some values into table x
insert into x values (1,1);
commit;
insert into x values (2,2);
commit;
You obtain the commit id of the last commit.
select last_commit_id from m_history_index_last_commit_id where session_id = curren
t_connection;
Note:
please replace <last_comit_id> in the steps below with the value you obtained in this step.
You delete all the data from table x.
delete from x;
commit;
You time travel into the history of table x before you deleted the data and perform a select.
set history session to commit id <last_comit_id>;
select * from x;
The select query above returns the two records (1,1) and (2,2), which existed before you deleted the
contents of table x.
You obtain the timestamp of <last_comit_id>.
select commit_time from sys.transaction_history where commit_id = <last_comit_id>;
Note:
please replace <commit_time> in the steps below with the value you obtained in this step.
You time travel into the history of table x using a timestamp and perform a select.
set history session to utctimestamp '<commit_time>';
select * from x;
The select query above returns the two records (1,1) and (2,2), which existed before you deleted the
contents of table x.
You set the history session to the current commit state and perform a select.
set history session to now;
select * from x;
The select query returns an empty table because, at the current state, the table has had all of its data
deleted.
SET SCHEMA
Syntax
SAP HANA Database - SQL Reference Manual
145 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 146/193
SET SCHEMA <schema_name>
Syntax Elements
<schema_name> ::= <string_literal>
The name of the schema that the session should change to.
Description
Changes the current schema of the session.
The current schema is used when SQL statements use database object names, for example table names, that
are not prefixed with a schema name.
Example
You create new schema called MY_SCHEMA.
CREATE SCHEMA MY_SCHEMA;
You change the current schema of the session to MY_SCHEMA.
SET SCHEMA MY_SCHEMA;
SET [SESSION]
Syntax
SET [SESSION] <key> = <value>
Syntax Elements
<key> ::= <string_literal>
The key of a session variable. The maximum length of key is 32 characters.
<value> ::= <string_literal>
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 database session by providing key and value
pairs.
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
You set the session variable MY_VAR to 'abc'.
SET 'MY_VAR' = 'abc';
You select the variable MY_VAR from the current session.
SELECT SESSION_CONTEXT('MY_VAR') FROM dummy;
You unset the session variable MY_VAR.
UNSET 'MY_VAR';
SAP HANA Database - SQL Reference Manual
146 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 147/193
UNSET [SESSION]
Syntax
UNSET [SESSION] <key>
Syntax Elements
<key> ::= <string_literal>
The key of a session variable. The maximum length of key is 32 characters.
Description
Using UNSET [SESSION] you can unset session variables of the current session.
Note:
There are several read-only session variables and they are APPLICATION, APPLICATIONUSER,
TRACEPROFILE.
Example
You set the session variable MY_VAR to 'abc'.
SET 'MY_VAR' = 'abc';
You select the variable MY_VAR from the current session.
SELECT SESSION_CONTEXT('MY_VAR') FROM dummy;
You unset the session variable MY_VAR.
UNSET 'MY_VAR';
Transaction Management Statements
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
LOCK TABLE <table_name> IN EXCLUSIVE MODE [NOWAIT]
Syntax Elements
<table_name> ::= [<schema_name>.]<identifier>
SAP HANA Database - SQL Reference Manual
147 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 148/193
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 149/193
You create a table T.
CREATE TABLE T (KEY INT PRIMARY KEY, VAL INT);
You insert three rows into table T.
INSERT INTO T VALUES (1, 1);
INSERT INTO T VALUES (2, 2);
INSERT INTO T VALUES (3, 3);
You rollback the current transaction.
ROLLBACK;
You select the data in table T.
SELECT * FROM T;
The SELECT command above returns an empty table. From this you can see that the data definition language
(DDL) command used to create the ta ble has persisted, but the DML used to create the ta ble data has been
rolled back.
See Also
For more information on changing the autocommit status of your database session, please see "Customizing
the Administration Console" section in the "SAP HANA Administration guide" available from the SAP HANA
Appliance page.
SET TRANSACTION
Syntax
SET TRANSACTION <isolation_level> | <transaction_access_mode>
Syntax Elements
isolation_level ::= ISOLATION LEVEL <level>
The isolation level sets the statement level read consistency of the data in the database. If <isolation_level> is
ommited the default is READ COMMITTED
level ::= READ COMMITTED | REPEATABLE READ | SERIALIZABLE
READ COMMITTED
The READ COMMITTED isolation level provides statement level read consistency during a t ransaction. Each
statement in a t ransaction sees commited state of the data in the database as the execution of the
statement begins. This means that each statement in t he same transaction may see varying snapshots of the
data in the database as they are executed as data can be commited during the transaction.
REPEATABLE READ/SERIALIZABLE
The REPEATABLE READ/SERIALIZABLE isolation level provides transaction level snapshot isolation. All
statements of a transaction see the same snapshot of the database data. This snapshot contains all changes
that were committed at the time the transaction started along with the changes made by the transactionitself.
transaction_access_mode ::= READ ONLY | READ WRITE
The SQL-transaction access mode controls if a transaction can modify data during execution. I f
transaction_access_mode is ommited the default is READ ONLY.
READ ONLY
When READ ONLY access mode is set, then only read operations with SELECT statements are allowed. An
exception will be thrown if update or insert operations are attempted whilst in this mode.
READ WRITE
When READ WRITE access mode is set, statements within a transaction can freely read or make changes to
the database data as required.
Description
SAP HANA Database - SQL Reference Manual
149 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 150/193
The SAP HANA database uses multi-version concurrency control (MVCC) to ensure consistent read operations.
Concurrent read operations see a consistent view of the data base data without blocking concurrent write
operations. Updates are implemented by inserting new versions of data and not by overwriting existing
records.
The isolation level specified determines the lock operation type that will be used. 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.
During a transaction when rows are inserted, updated or deleted, the system sets exclusive locks on the
affected rows for the duration of the transaction. 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 rows of the
table are being updated. The database releases these locks at the end of the transaction.
Note:
Reading a row does not set any locks on either tables or rows within the database regardless of the
isolation level used.
Data Definition Language and Transaction Isolation
Data Definition Language (DDL) statements (CREATE TABLE, DROP TABLE, CREATE VIEW, etc) always take
an instantaneous effect on following SQL statements regardless of the transaction isolation level being used.
For an example of this behaviour please consider the following sequence:
1. A long running SERIALIZABLE isolation transaction begins operating on Table C.
2. From outside the transact ion some DDL is executed which adds a new column to Table C.
3. From within the SERIALIZABLE isolation transaction the new column will be accessible as soon as the
DDL statement completes. This access occurs regardless of the isolation level of the transaction.
Example
You set the transaction isolation level to READ COMMITTED to provide statement level read consistency
during the current transaction.
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
Access Control Statements
ALTER SAML PROVIDER
Syntax
ALTER SAML PROVIDER <saml_provider_name> SET SUBJECT <subject_distinguished_name> I
SSUER <issuer_distinguished_name>
Syntax Elements
<saml_provider_name> ::= <simple_identifier>
The identifier of a SAML provider to be altered.
<subject_distinguished_name> ::= <string_literal>
The subject name provided in the certificate of the SAML identity provider.
<issuer_distinguished_name> ::= <string_literal>
The issuer name provided in the certificate of the SAML identity provider.
Description
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 created using the CREATE SAML
PROVIDER command.
SAP HANA Database - SQL Reference Manual
150 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 151/193
Only database users having the system privilege USER ADMI N are allowed to change a SAML provider.
System and Monitoring Views
SAML_PROVIDERS: shows all SAML providers with their subject name and issuer_name.
Example
You create the ac_saml_provider SAML provider.
CREATE SAML PROVIDER ac_saml_provider
WITH SUBJECT 'CN = wiki.detroit.ACompany.corp,OU = ACNet,O = ACompany,C = EN'
ISSUER 'E = [email protected],CN = ACNetCA,OU = ACNet,O = ACompany,C = EN';
You view the current defined SAML providers in the SAP HANA database.
select * from sys.SAML_PROVIDERS
You alter the ac_saml_provider.
ALTER SAML PROVIDER ac_saml_provider
SET SUBJECT 'CN = wiki.detroit.BCompany.corp,OU = BCNet,O = BCompany,C = EN' ISSUER 'E = [email protected],CN = BCNetCA,OU = BCNet,O = BCompany,C = EN
';
You check the current defined SAML providers in the SAP HANA database. You should now see the updated
SAML provider.
select * from sys.SAML_PROVIDERS
See Also
CREATE SAML PROVIDER
ALTER USER
Syntax
ALTER USER <user_name> <alter_user_option>
Syntax Elements
<user_name> ::= <simple_identifier>
<alter_user_option> ::= PASSWORD <password> [<user_parameter_option>]
| <user_parameter_option>
| IDENTIFIED EXTERNALLY AS <external_identity> [<user_parame
ter_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
<password> ::= <letter_or_digit>...
<user_parameter_option> ::= <set_user_parameters> [<clear_user_parameter_option>]
| <clear_user_parameter_option>
<set_user_parameters> ::= SET PARAMETER CLIENT = <string_literal>
<clear_user_parameter_option> ::= CLEAR PARAMETER CLIENT
| CLEAR ALL PARAMETERS
<external_identity> ::= <simple_identifier>
| <string_literal>
SAP HANA Database - SQL Reference Manual
151 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 152/193
<authentication_mechanism> ::= PASSWORD | KERBEROS | SAML
<provider_identity> ::= <mapped_user_name> FOR SAML PROVIDER <saml_provider_name>
| <external_identity> FOR KERBEROS
<mapped_user_name> ::= ANY
| <string_literal>
<saml_provider_name> ::= <simple_identifier>
<provider_info> ::= FOR SAML PROVIDER <saml_provider_name>
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 a ll 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 bechanged.
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.
<user_parameter_option> can be used to set, change or clean the user parameter CLIENT.
<set_user_parameters> can be used to set the user parameter CLIENT for a user 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.
The <user_parameter_option> can not be specified by the user himself.
If the number of MAXIMUM_INVALID_CONNECT_ATTEMPTS (see monitoring view M_PASSWORD_POLICY) is
reached before a successful (correct user/password-combination) connect is done, then this user is locked for
some minutes before being allowed to connect (even with correct user/password-combination) again. With
the command
ALTER USER <user_name> RESET CONNECT ATTEMPTS
a user with system privilege USER ADMIN can reset the number of invalid attempts to 0 and therefore allow
the user to connect immediately.
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.
With the commandALTER USER <user_name> DISABLE PASSWORD LIFETI ME
a user with system privilege USER ADMIN can exclude user <user_name> from all password-life-time-checks.
This should be used only for technical users, not for normal database users. Please check the description of
configuration parameters concerning the password policy.
With the command
ALTER USER <user_name> FORCE PASSWORD CHANGE
a user with system privilege USER ADMIN can force user <user_name> to change his password immediately
after the next connect before being allowed to work any further.
With the command
ALTER USER <user_name> DEACTIVATE USER NOW
a user with system privilege USER ADMIN can deactivate / lock the user account of user <user_name>. After
the user account is deactivated / locked, the user cannot connect to the SAP HANA database. To re-activate /
unlock user <user_name> a user with system privilege USER ADMIN has either to use the command ALTER
SAP HANA Database - SQL Reference Manual
152 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 153/193
USER <user_name> ACTIVATE USER NOW or, in case of a user with PASSWORD authentication mechanism,
to reset the user's password with ALTER USER <user_name> PASSWORD <password>.
With the command
ALTER USER <user_name> ACTIVATE USER NOW
a user with system privilege USER ADMIN can re-activate / unlock the user account of user <user_name>
who had been deactivated before.
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.
System and Monitoring Views
USERS: shows all users, their creator, creat ion 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.
Examples
You create a SAML provider named ac_saml_provider in the database specifying a subject and issuer for
ACompany.
CREATE SAML PROVIDER ac_saml_provider
WITH SUBJECT 'CN = wiki.detroit.ACompany.corp,OU = ACNet,O = ACompany,C = EN'
ISSUER 'E = [email protected],CN = ACNetCA,OU = ACNet,O = ACompany,C = EN';
You create user named new_user that can connect using a password or with an assertion of the SAML
provider ac_saml_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 ac_saml
_provider;
You force the user to change their password.
ALTER USER new_user FORCE PASSWORD CHANGE;
You disable SAML authentication for the user.
ALTER USER new_user DISABLE SAML;
You reset the number of invalid connect attempts to zero for new_user.
ALTER USER new_user RESET CONNECT ATTEMPTS;
You define the external identity for KERBEROS and enable KERBEROS for this user.
ALTER USER new_user ADD IDENTITY 'testkerberosName' FOR KERBEROS;
ALTER USER new_user ENABLE KERBEROS;
Note:
Adding an external identification mechanism to a user does not automatically enable it. You must do
this as a separate step as shown in this example.
You remove ac_saml_provider SAML provider identity from new_user.
ALTER USER new_user DROP IDENTITY FOR SAML PROVIDER ac_saml_provider;
You disable the account.
ALTER USER new_user DEACTIVATE;
CREATE ROLE
SAP HANA Database - SQL Reference Manual
153 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 154/193
Syntax
CREATE ROLE <role_name>
Syntax Elements
<role_name> ::= <identifier>
Description
The CREATE ROLE statement creates a new role.
Only database users with the system privilege ROLE ADMIN are allowed to create roles.
The specified role name must not be identical to the name of an existing user or role.
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 act ions, you can create a role, grant the needed privileges to
this role, and then grant t he role to the 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 5 roles that are delivered with the SAP HANA database:
PUBLIC
Every database user is granted this role automatically.
This role contains read-only access to system views, monitoring views and execute privileges for some
procedures. These privileges cannot be revoked.
This role can be gra nted further privileges which can then 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 addition that this role is allowed to
grant these privileges to other users. I n 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.
SUPPORT
This role is to be used for SAP support.
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. Additionally it contains the privileges to access the
base information of the system and monitoring views. This information is usually only accessible by the
SYSTEM user.
To ensure this role is used only for support there are some restrictions place on it:
it cannot be granted to database user SYSTEM
it cannot be granted to more than one database user at a time
it cannot be granted to another role
no role can be granted to it
only systemprivileges (see GRANT statement) can be granted to this role. However for securityreasons SAP recommends systemprivileges should be granted to the user and not to the SUPPORT
role.
with every upgrade of the SAP HANA database the privileges in this role are reset the default settings.
System and Monitoring Views
ROLES: displays all roles, their creator and creat ion date.
GRANTED_ROLES: displays the roles that are granted to users or roles.
GRANTED_PRIVILEGES: displays the privileges that are granted to users or roles.
Example
You create a role with the name role_for_work_on_my_schema.
SAP HANA Database - SQL Reference Manual
154 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 155/193
CREATE ROLE role_for_work_on_my_schema;
CREATE SAML PROVIDER
Syntax
CREATE SAML PROVIDER <saml_provider_name> WITH SUBJECT <subject_distinguished_name>
ISSUER <issuer_distinguished_name>
Syntax Elements
<saml_provider_name> ::= <simple_identifier>
The identifier of a SAML provider to be created.
<subject_distinguished_name> ::= <string_literal>
The subject name provided in the certificate of the SAML identity provider.
<issuer_distinguished_name> ::= <string_literal>
The issuer name provided in the certificate of the SAML identity provider
Description
The CREATE SAML PROVIDER statement defines a SAML provider that will be known to the SAP HANA
database. <saml_provider_name> has to be unique from 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 also allowed to drop any SAML provider.
A SAML provider is required to be able to provide a SAML connection facility for users.
The <subject_distinguished_name> and the <issuer_distinguished_name> are the X.500 distinguished names
corresponding to the subject and issuer of the X.509 certificate used by the SAML identity provider to sign
assertions. The syntax of these names can be found in ISO/IEC 9594-1.
A detailed description of the concepts of SAML can be found in Oasis SAML 2.0.
System and Monitoring Views
SAML_PROVIDERS: shows all SAML providers with their subject name and issuer name.
Example
You create a SAML provider with the name ac_saml_provider in the database specifying the subject and
issuer to belong to ACompany.
CREATE SAML PROVIDER ac_saml_provider
WITH SUBJECT 'CN = wiki.detroit.ACompany.corp,OU = ACNet,O = ACompany,C = EN'
ISSUER 'E = [email protected],CN = ACNetCA,OU = ACNet,O = ACompany,C = EN';
CREATE USER
Syntax
CREATE USER <user_name> [PASSWORD <password>]
[IDENTIFIED EXTERNALLY AS <external_identity>]
[WITH IDENTITY <provider_identity>...]
[<set_user_parameters>]
Syntax Elements
<user_name> ::= <simple_identifier>
<password> ::= <letter_or_digit>...
<external_identity> ::= <simple_identifier> | <string_literal>
<provider_identity> ::= <mapped_user_name> FOR SAML PROVIDER <saml_provider_name>
SAP HANA Database - SQL Reference Manual
155 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 156/193
| <external_identity> FOR KERBEROS
<mapped_user_name> ::= ANY | <string_literal>
<saml_provider_name> ::= <simple_identifier>
<set_user_parameters> ::= SET PARAMETER CLIENT = <string_literal>
Description
The CREATE USER statement creates a new database user.
Only database users having the system privilege USER ADMIN are allowed to create another database user.
The specified user name must not be identical to the name of an existing user, role, or schema.
There are some users, which are delivered with the SAP HANA database: SYS, SYSTEM, _SYS_REPO,
_SYS_STATISTICS.
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 dothe 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 g iven as mapped user name, the SAML assertion will contain the name of the database user, the
assertion is valid for.
<saml_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 ca n 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.
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.
System and Monitoring Views
USERS: shows all users, their creator, creat ion 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
Examples
Example 1 - Create user with password.
You create a user T12345 with a password Password123.
SAP HANA Database - SQL Reference Manual
156 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 157/193
CREATE USER T12345 PASSWORD Password123
Example 2 - Create user that uses an external authentication mechanism.
You create a SAML provider named ac_saml_provider in the database, specifying a subject and issuer for
ACompany.
CREATE SAML PROVIDER ac_saml_provider
WITH SUBJECT 'CN = wiki.detroit.ACompany.corp,OU = ACNet,O = ACompany,C = EN'
ISSUER 'E = [email protected],CN = ACNetCA,OU = ACNet,O = ACompany,C = EN';
You create a user called new_user with password Password1. The user can connect to the system using the
given password and with an assertion of the existing SAML provider ac_saml_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 ac_saml
_provider;
DROP ROLE
Syntax
DROP ROLE <role_name>
Syntax Elements
<role_name> ::= <identifier>
Description
The DROP ROLE statement drops a role. <role_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
cannot be dropped: PUBLIC, CONTENT_ADMIN, MODELING, MONITORING and SUPPORT.
If a role was granted to a user or role, it is revoked when the role is dropped. Revoking a role may lead t o
making some views inaccessible or making procedures not executable. This will occur if a view or procedures
depends on any privilege of the dropped role.
System and Monitoring Views
ROLES: displays all roles, their creator and creat ion date.
GRANTED_ROLES: displays the roles that are granted to users or roles.
GRANTED_PRIVILEGES: displays the privileges that are granted to users or roles.
Example
A role with the name role_for_work_on_my_schema is created and dropped immediately afterwards;
CREATE ROLE role_for_work_on_my_schema;
DROP ROLE role_for_work_on_my_schema;
DROP SAML PROVIDER
Syntax
DROP SAML PROVIDER <saml_provider_name>
Syntax Elements
<saml_provider_name> ::= <simple_identifier>
Description
SAP HANA Database - SQL Reference Manual
157 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 158/193
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 ADMI N are allowed to drop a SAML provider.
System and Monitoring Views
SAML_PROVIDERS: shows all SAML providers with their subject name and issuer_name.
Example
You create SAML provider named ac_saml_provider, specifying a subject and issuer for ACompany.
CREATE SAML PROVIDER ac_saml_provider
WITH SUBJECT 'CN = wiki.detroit.ACompany.corp,OU = ACNet,O = ACompany,C = EN'
ISSUER 'E = [email protected],CN = ACNetCA,OU = ACNet,O = ACompany,C = EN';
You drop the SAML provider ac_saml_provider.
DROP SAML PROVIDER ac_saml_provider
DROP USER
Syntax
DROP USER <user_name> [<drop_option>]
Syntax Elements
<user_name> ::= <simple_identifier>
<drop_option> ::= CASCADE | RESTRICT
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.
It is possible to delete a user even if an open session of this user exists.
System and Monitoring Views
The deleted user will be deleted in any of these views:
USERS: shows all users, their creator, creat ion 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.
* The deletion of objects may influence all of the system views describing objects, like TABLES, VIEWS,
PROCEDURES, ... .
SAP HANA Database - SQL Reference Manual
158 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 159/193
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 with, for example, this statemant:
CREATE USER new_user PASSWORD Password1;
The existing user new_user will now be dropped, together with all of his objects;
DROP USER new_user CASCADE;
GRANT
Syntax
GRANT <system_privilege>,... TO <grantee> [WITH ADMIN OPTION]
| GRANT <schema_privilege>,... ON SCHEMA <schema_name> TO <grantee> [WITH GRANT OPT
ION]
| GRANT <object_privilege>,... ON <object_name> TO <grantee> [WITH GRANT OPTION]
| GRANT <role_name>,... TO <grantee> [WITH ADMIN OPTION]
| GRANT STRUCTURED PRIVILEGE <privilege_name> TO <grantee>
Syntax Elements
<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
| TRUST ADMIN | USER ADMIN
| VERSION ADMIN| <identifier>.<identifier>
System privileges are used to restrict administrative tasks. The table below describes the supported system
privileges.
SAP HANA Database - SQL Reference Manual
159 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 160/193
System Privilege Privilege Purpose Comment
AUDIT ADMIN
Controls the execution of the
following auditing-related
commands: CREATE AUDIT POLICY,
DROP AUDIT POLICY and ALTER AUDIT
POLICY and the change s of the
auditing configuration.
BACKUP ADMIN
Authorizes the BACKUP command to
define and i nitiate a ba ckup process
or to perform a recovery process .
CATALOG READ
Authorizes use rs to have unfiltered
read-only access to al l s ystem and
monitoring views.
Normally, the content of these views is
filtered based on the privile ges of the
accessing user.
CREATE SCENARIO
Controls the creation of calculation
scenarios and cubes (calculation
database)
CREATE SCHEMA
Authorizes the creation of databas e
schema s us ing the CREATE SCHEMA
command.By default each user owns
one schema, with this privilege the
user is al lowed to create additional
schemas.
CREATE STRUCTURED
PRIVILEGE
Authorizes the crea tion of Structured
Privileges (Analytical Privileges )
Only the owner of an Analytical Privilege
can further grant or revoke tha t privile ge
to other users or roles.
DATA ADMIN
Authorizes reading all data in the
system and monitoring views. It a lso
enable s execution of any Data
Definition Language (DDL)
commands in the SAP HANA database
A user having this privilege cannot sel ect
or change data s tored table s for which
they do not have access privile ges, but
they can drop tables or modify table
definitions.
EXPORT
Authorizes e xport activity in the
database via the EXPORT TABLE
command.Note that besi de this
privilege the user requires the SELECT
privile ge on the s ource table s to be
exported.
IMPORT
Authorizes the i mport activity in the
databas e usi ng the IMPORT
commands.
Note that beside this privile ge the user
requires the INSERT privilege on the target
tables to be imported.
INIFILE ADMINAuthorizes changing of system
settings.
LICENSE ADMINAuthorizes the SET SYSTEM LICENSE
command install a new license.
LOG ADMIN
Authorizes the ALTER SYSTEM
LOGGING [ON|OFF] commands to
enable or disable the log flush
mechanism.
MONITOR ADMINAuthorizes the ALTER SYSTEM
commands for EVENTs.
OPTIMIZER ADMIN
Authorizes the ALTER SYSTEM
commands concerning SQL PLAN
CACHE a nd ALTER SYS TEM UPDATE
STATISTICS commands , which
influence the beha vior of the query
optimizer.
RESOURCE ADMIN
This privilege authorizes commands
concerning system resources, for
exampl e ALTER SYSTEM RECLAIM
DATAVOLUME and ALTER SYSTEM
RESET MONITORING VIEW. It als o
authorizes many of the commands
available in the Management
Console.
ROLE ADMIN
This privilege a uthorizes the creation
and dele tion of roles using the
CREATE ROLE and DROP ROLE
commands. It a lso authorizes the
granting and revocation of roles
usi ng the GRANT and REVOKE
commands.
Activated roles , meaning roles whose
creator is the pre-defined user _SYS_REPO,
can neither be granted to other roles or
users nor dropped directly. Not even users
having ROLE ADMIN privilege are able to
do so. Plea se check documentation
concerning activated objects.
SAVEPOINT ADMIN
Authorizes the execution of a
savepoint process us ing the ALTER
SAP HANA Database - SQL Reference Manual
160 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 161/193
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 162/193
Object Privilege Command
Types Privilege De scr ipt ion Com me nt
ALL PRIVILEGESDDL &
DML
This privile ge is a collection of all
Data Defini tion Language(DDL)
and Data Manipulation
Language(DML) privileges that the
grantor currently possess es and i s
al lowed to grant further. The
privile ge it grants is specific to the
particular object being acted
upon.
This privilege collection is
dynamicall y evaluated for the
given grantor a nd object. ALL
PRIVILEGES is applicabl e to a
table or view
ALTER DDLAuthorizes the ALTER command for
the object
DEBUG DML
Authorizes debug-functionality for
the procedure or calculation view
or for the procedures a nd
calculation views of a schema.
DELETE DML
Authorizes the DELETE and
TRUNCATE commands for the
object
DROP DDLAuthorizes the DR OP commands
for the object
EXECUTE DML
Authorizes the execution of an
SQLScript function or a database
procedure usi ng the CALLS or CALL
command respectively.
INDEX DDL
Authorizes the creation,
modification or dropping of
indexes for the object
INSERT DMLAuthorizes the INSERT command
for the obje ct.
The INSERT a nd UPDATE
privilege are both required on
the object to al low the REPLACE
and UPSERT commands to be
used.
REFERENCES DDL
Authorizes the usage of all tables
in this s chema or this table i n a
foreign key definition.
SELECT DML
Authorizes the SELECT command
for this object or the usage of asequence.
TRIGGER DDL
Authorizes the CREATE TRIGGER /
DROP TRIGGER command for the
specified table or the table s in
the specified schema.
UPDATE DMLAuthorizes the UPDATE command
for that object.
he INSERT and UPDATE privilege
are both required on the object
to al low the REPLACE and
UPSERT commands to be used.
The UPDATE privile ge is als o
required to perform delta
merges of column store tables
usi ng the MERGE DELTA
command.
<identi f ier>.<identi f ier> DDL
Components of the SAP HANA
databas e can create new s ystem
privile ges. These privileges usethe component-name as first
identifier of the s ystem privilege
and the component-privilege-
name as the second identifier.
Not all object privileges are applicable to all kinds of database objects. For details of which object types allow
which privilege to be used please see the table below.
SAP HANA Database - SQL Reference Manual
162 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 163/193
Privilege Schema Table View Sequence Function/Procedure
ALL PRIVILEGES --- YES YES --- ---
ALTER YES YES --- --- YES
CREATE ANY YES --- --- --- ---
DEBUG YES --- YES --- YES
DELETE YES YES YES --- ---
DROP YES YES YES YES YES
EXECUTE YES --- --- --- YES
INDEX YES YES --- --- ---
INSERT YES YES YES --- ---
REFERENCES YES YES --- --- ---
SELECT YES YES YES YES ---
TRIGGER YES YES --- --- ---
UPDATE YES YES YES --- ---
DELETE, INSERT and UPDATE on views are valid for updatable views only. Updatable views have the following
characteristics:
Does not use a join
Does not contain a UNION
Does not use aggregation
DEBUG is only valid for calculation views.
For synonyms, the same restrictions apply to the synonym as they would do for the object the synonym
represents.
<object_name> ::= <table_name> | <view_name>
| <sequence_name> | <procedure_name>
| <synonym_name>
Object privileges are used to restrict the access and modifications on database objects like tables, views,
sequences, procedures and synonyms.
<grantee> :: = <user_name> | <role_name>
The grantee can be a user or a role. I n case a privilege or role is granted to a role, then all user being granted
that role, will have the specified privilege or role.
A role is a named collection of privileges and can be granted to either a user or a role.
If you want to a llow several database users to perform the same actions, you should create a role, grant the
needed privileges to this role, and finally grant the role to the different database users.
When granting roles to roles, a tree of roles can be build. When granting a 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.
<user_name> ::= <simple_identifier>
The grantee username.
<role_name> ::= <identifier>
The grantee role name.
<schema_name> ::= <identifier>
The schema containing the database object to be acted upon.
<table_name> ::= [<schema_name>.]<identifier>
The database table object name.
<view_name> ::= [<schema_name>.]<identifier>
SAP HANA Database - SQL Reference Manual
163 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 164/193
The database view object name.
<sequence_name> ::= [<schema_name>.]<identifier>
The sequence object name.
<procedure_name> ::= [<schema_name>.]<identifier>
The procedure object name.
<synonym_name> ::= [<schema_name>.]<identifier>
The synonym name.
<privilege_name> ::= <identifier>
The name of the privilege to be granted.
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.
With GRANT STRUCTURED PRIVILEGE <privilege_name>
A previously defined analytical privilege based on a generic structured privilege is granted to a user or role.
This analytical privileges is used to restrict the access for read operations to certain data in Analytic,
Attribute, and Calculation Views by filtering the attribute values.
Description
GRANT is used to g rant privileges and structured privileges to users and roles. GRANT is a lso 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.
In order to use the GRANT command to grant privileges to other users and roles, a user must have the
privilege and also the permissions required to grant that privilege.
A user can not grant a privilege to themselves.
User SYSTEM has at all system privileges and the role PUBLIC. All other users have the role PUBLIC. These
privileges and roles cannot be revoked.
Although the SYSTEM user has many privileges, it cannot select or change data in other user's tables unless
this privilege has been explicitly granted.
All users have the privilege to create objects in their own default schema. The default schema for a user
always has the same schema name as the user.
For tables created by users, users have all privileges and may grant all privilges further to other users and
roles.
For objects which are dependent on other objects, like views being dependent on tables, it can occur the
owner of the dependent object does not have a complete set of privileges. This can occur if the user do not
have the privileges on the underlying objects on which their object depends.
Users can have privileges on an object, but may not have sufficient priviliges to grant them to other users and
roles.
System and Monitoring Views
USERS: shows all users, their creator, creat ion date and some info about their current states.
ROLES: shows all roles, their creator and creat ion 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.
Examples
You create a schema called my_schema.
SAP HANA Database - SQL Reference Manual
164 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 165/193
CREATE SCHEMA my_schema;
You create a table named work_done in the my_schema schema.
CREATE TABLE my_schema.work_done (t TIMESTAMP, user NVARCHAR (256), work_done VARCH
AR (256));
You create a new user named worker with password His_Password_1.
CREATE USER worker PASSWORD His_Password_1;
You create role called role_for_work_on_my_schema.
CREATE ROLE role_for_work_on_my_schema;
You grant the SELECT on any object privilege in my_schema to the role role_for_work_on_my_schema.
GRANT SELECT ON SCHEMA my_schema TO role_for_work_on_my_schema;
You grant the INSERT privilege for the work_done table to the role role_for_work_on_my_schema.
GRANT INSERT ON my_schema.work_done TO role_for_work_on_my_schema;
You grant the role_for_work_on_my_schema role to the worker user.
GRANT role_for_work_on_my_schema TO worker WITH ADMIN OPTION;
You grant DELETE privilige for this table to the worker user.
GRANT DELETE ON my_schema.work_done TO worker;
You grant the worker user the privilege to create any kind of object in the my_schema schema.
GRANT CREATE ANY ON SCHEMA my_schema TO worker;
The result of the above commands is that the worker user has the privilege to SELECT all tables and views in
schema my_schema, to INSERT into and DELETE from table my_schema.work_done and to create objects in
schema my_schema. Additionally the worker user is allowed to grant DELETE on the tablemyschema.work_done to other users and roles.
You grant the privileges INIFILE ADMIN and TRACE ADMIN to the user worker. You grant these privileges
along with the permission for the worker user to grant them further.
GRANT INIFILE ADMIN, TRACE ADMIN TO worker WITH ADMIN OPTION;
REVOKE
Syntax
REVOKE <system_privilege>,... FROM <grantee>
| REVOKE <schema_privilege>,... ON SCHEMA <schema_name> FROM <grantee>
| REVOKE <object_privilege>,... ON <object_name> FROM <grantee>
| REVOKE <role_name>,... FROM <grantee>
| REVOKE STRUCTURED PRIVILEGE <privilege_name> FROM <grantee> | REVOKE APPLICATION PRIVILEGE <privilege_name> FROM <grantee>
Syntax Elements
For the definition of syntax elements, please refer to GRANT.
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.
SAP HANA Database - SQL Reference Manual
165 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 166/193
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.
Revoking a privilege which had been granted with WITH GRANT OPTION or with WITH ADMIN OPTION willresult 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.
System and Monitoring Views
USERS: shows all users, their creator, creat ion date and some info about their current states.
ROLES: shows all roles, their creator and creat ion 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
You create new user named worker.
CREATE USER worker PASSWORD His_Password_1;
You create new role named role_for_work_on_my_schema.
CREATE ROLE role_for_work_on_my_schema;
You create new schema named my_schema.
CREATE SCHEMA my_schema OWNED BY system;
You create new table named work_done in the schema.
CREATE TABLE my_schema.work_done (t TIMESTAMP, user NVARCHAR (256), work_done VARCHAR (256) );
You grant the SELECT on any object privilege in my_schema to the role role_for_work_on_my_schema.
GRANT SELECT ON SCHEMA my_schema TO role_for_work_on_my_schema;
You grant the INSERT privilege for the work_done table to the role role_for_work_on_my_schema.
GRANT INSERT ON my_schema.work_done TO role_for_work_on_my_schema;
You grant the role_for_work_on_my_schema role to the worker user.
GRANT role_for_work_on_my_schema TO worker;
You grant TRACE ADMIN privilege for the worker user.
GRANT TRACE ADMIN TO worker WITH ADMIN OPTION;
You grant DELETE from work_done table to t he worker user.
GRANT DELETE ON my_schema.work_done TO worker WITH GRANT OPTION;
You revoke from the role role_for_work_on_my_schema the privilege to select from my_schema.
REVOKE SELECT ON SCHEMA my_schema FROM role_for_work_on_my_schema;
You revoke TRACE ADMIN privilege from the worker.
REVOKE TRACE ADMIN FROM worker;
Data Import Export Statements
SAP HANA Database - SQL Reference Manual
166 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 167/193
EXPORT
Syntax
EXPORT <object_name_list> AS <export_format> INTO <path> [WITH <export_option_list>
]
Syntax Elements
WITH <export_option_list>:
EXPORT options can be passed in using "WITH" clause.
<object_name_list> ::= <OBJECT_NAME>,... | ALL
<export_import_format> ::= BINARY | CSV
<path> ::= 'FULL_PATH'
<export_option_list> ::= <export_option> | <export_option_list> <export_option>
<export_option> ::=
REPLACE |
CATALOG ONLY |
NO DEPENDENCIES |
SCRAMBLE [BY <password>] |
THREADS <number_of_threads>
Description
The EXPORT command exports tables, views, column views, synonyms, sequences, or procedures in the
specified format as BI NARY or CSV. Data for temporary tables and "no logging" tables cannot be exported
using EXPORT.
OBJECT_NAME
SQL name of the object (table, view, etc) to export. To export all objects from all schemas you should use the
keyword ALL. If you want to export objects of a specific schema, you should use the schema name with the
asterisk, e.g. "SYSTEM"."*"
BINARY
Table data will be exported in internal binary format. Exporting in t his format is orders of magnitude faster
then exporting the same table in CSV format. Only column tables can be exported in binary format. The rowtables are a lways exported in CSV format, even if BINARY format is specified.
CSV
Table data will be exported in CSV format. The exported data can be imported only in any other database.
Additionaly, the exported data can be scramled. Both column and row tables can be exported in CSV format.
FULL_PATH
The server path to export to.
Note:
When using a distributed system, the FULL_PATH must point to a shared disk! For security reasons,
the path may not contain symbolic links and may not point inside the database instance folder,
except its 'backup' and 'work' subfolders. Examples for valid export path (assuming the database
instance is located at /usr/sap/HDB/HDB00):
'/tmp'<br>
'/usr/sap/HDB/HDB00/backup' <br>
'/usr/sap/HDB/HDB00/work'<br>
REPLACE
With REPLACE option, previously exported data will be removed and newly exported data will be 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
SAP HANA Database - SQL Reference Manual
167 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 168/193
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.
Number of threads to use
The given number of THREADS specifies how many objects will be exported in parallel (default is 1).
Increasing number of threads may reduce export time, but also can negat ively affect the system
performance.
Following should be considered:
For a single table THREADS has no effect.
For a view or procedure, 2 or more threads should be used (up to number of objects it depends on)
For a whole schema consider using more that 10 threads (up to number of cores in the system)
For a whole BW / ERP system (ALL keyword) with tens of thousands of tables, a large number of
threads can be reasonable (up to 256)
Number of threads to use
You can monitor the progress of the export using M_EXPORT_BINARY_STATUS system views.
You can abort the export session using the session ID from the corresponding view in the following command:
ALTER SYSTEM CANCEL [WORK IN] SESSION 'sessionId'
The detailed result of the export is stored in session-local temporary tables. #EXPORT_RESULT.
Number of threads to use
You create new schema named MY_SCHEMA.
CREATE SCHEMA MY_SCHEMA;
You export the information from MY_SCHEMA in CSV format with the REPLACE and SCRAMBLE options
enabled.
EXPORT "MY_SCHEMA"."*" AS CSV INTO '/tmp' WITH REPLACE SCRAMBLE THREADS 10
IMPORT
Syntax
IMPORT <object_name_list> [AS <import_format>] FROM <path> [WITH <import_option_lis
t>]
Syntax Elements
WITH <import_option_list>:
IMPORT options can be passed in using "WITH" clause.
<object_name_list> ::= <object_name>,... | ALL <import_format> ::= BINARY | CSV
<path> ::= 'FULL_PATH'
<import_option_list> ::= <import_option> | <import_option_list> <import_option>
<import_option> ::=
REPLACE |
CATALOG ONLY |
NO DEPENDENCIES |
THREADS <number_of_threads>
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 I MPORT command.
OBJECT_NAME
SQL name of the object (table, view, etc) to import. To import all objects from the import path you should use
SAP HANA Database - SQL Reference Manual
168 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 169/193
the keyword ALL. If you want to import objects of a specific schema, you should use the schema name with
the asterisk, e.g. "SYSTEM"."*"
BINARY | CSV
Format specification may be ommited during the import, since the format will be auto-detected during
import. The data will be imported in the same format in which it was exported.
FULL_PATH
The server path to import from.
Note:
When using a distributed system, the FULL_PATH must point to a shared disk! Examples for valid
import path (assuming the database instance is located at /usr/sap/HDB/HDB00):
'/tmp'<br>
'/usr/sap/HDB/HDB00/backup' <br>
'/usr/sap/HDB/HDB00/work'<br>
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 ONLYWith 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.
Number of threads to use
The given number of THREADS specifies how many objects will be imported in parallel (default is 1).
Increasing number of threads may reduce import time, but a lso can negatively affect the system
performance.
Following should be considered:
For a single table THREADS has no effect.For a view or procedure, 2 or more threads should be used (up to number of objects it depends on)
For a whole schema consider using more that 10 threads (up to number of cores in the system)
For a whole BW / ERP system (ALL keyword) with tens of thousands of tables, a large number of
threads can be reasonable (up to 256)
Number of threads to use
You can monitor the progress of the import using M_IMPORT_BI NARY_STATUS system views.
Also, you can abort the import session using the connection ID from the corresponding view in the following
command:
ALTER SYSTEM CANCEL [WORK IN] SESSION 'sessionId'
The detailed result of the import is stored in session-local temporary tables. #IMPORT_RESULT.
Example
IMPORT "SCHEMA"."*" AS CSV FROM '/tmp' WITH REPLACE THREADS 10
IMPORT FROM
Syntax
IMPORT FROM [<file_type>] <file_path> [INTO <table_name>] [WITH <import_from_option
_list>]
Syntax Elements
WITH <import_from_option_list>:
SAP HANA Database - SQL Reference Manual
169 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 170/193
IMPORT FROM options can be passed in using "WITH" clause.
<file_type> ::= CSV FILE | CONTROL FILE
The type of the file to be imported. You can specify either Comma-separated values or control file formats.
For details of CSV and control file formats please see the Examples.
<file_path> ::= <string_literal>
The complete path of the file and filename of the file to import.
<table_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
The target table name, with optional schema name, where the imported data will be stored.
WITH <import_from_option_list>
<import_from_option_list> ::= <import_from_option> ...
The optional WITH option list can have one or many of the options stated below.
<import_from_option> ::= THREADS <number_of_threads>
| BATCH <number_of_records_of_each_commit>
| TABLE LOCK
| NO TYPE CHECK
| SKIP FIRST <number_of_rows_to_skip> ROW
| COLUMN LIST IN FIRST ROW
| COLUMN LIST ( <column_name_list> )
| RECORD DELIMITED BY <string_for_record_delimiter>
| FIELD DELIMITED BY <string_for_field_delimiter>
| OPTIONALLY ENCLOSED BY <character_for_optional_enclosure>
| DATE FORMAT <string_for_date_format>
| TIME FORMAT <string_for_time_format>
| TIMESTAMP FORMAT <string_for_timestamp_format>
| ERROR LOG <file_path_of_error_log>
Import option parameters are detailed below.
THREADS <number_of_threads>
<number_of_threads> ::= <integer_literal>
The number of threads that can be used for concurrent import. The default value is 1 and maximum allowed
is 256.
BATCH <number_of_records_of_each_commit>
<number_of_records_of_each_commit> ::= <integer_literal>
The number of records to be inserted in each commit.
Note:
THREADS and BATCH can be used to achieve high loading performance by enabling parallel loading
and also by committing many records at once. I n general, for column tables, a good setting to use is
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.
SKIP FIRST <number_of_rows_to_skip> ROW
<number_of_rows_to_skip> ::= <integer_literal>
Skips to insert first n rows.
COLUMN LIST IN FIRST ROW
Indicates the column list is stored in the first row of the CSV import file.
COLUMN LIST ( <column_name_list> )
<column_name_list> ::= <column_name> [{, <column_name>}...]
<column_name> ::= <string_literal>
SAP HANA Database - SQL Reference Manual
170 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 171/193
The column list for the data being imported. The name list has one or more column names. The ordering of
the column names should match the order of the column data in the CSV file and the columns in the target
table.
RECORD DELIMITED BY <string_for_record_delimiter>
<string_for_record_delimiter> ::= <string_literal>
The record delimiter used in the CSV file being imported.
FIELD DELIMITED BY '<string_for_field_delimiter>'
<string_for_field_delimiter> ::= <string_literal>
Indicates the field delimiter of the CSV file
OPTIONALLY ENCLOSED BY <character_for_optional_enclosure>
<character_for_optional_enclosure> ::= <character_literal>
Indicates the optional enclosure character used to delimit field data
DATE FORMAT <string_for_date_format>
<string_for_date_format> ::= <string_literal>
The format that date strings are encoded with in the import data.
Y : year , MM : month , MON : name of month, DD : day
For example:
'YYYYMMDD' : 20120520 , 'YYYY-MM-DD' : 2012-05-20 , 'YYYY-MON-DD' : 2012-MAY-20
TIME FORMAT <string_for_time_format>
<string_for_time_format> ::= <string_literal>
The format that time strings are encoded with in the import data.
HH24 : hour , MI : minute , SS : second
For example:
'HH24MISS' : 143025 , 'HH24:MI:SS' : 14:30:25
TIMESTAMP FORMAT <string_for_timestamp_format>
<string_for_timestamp_format> ::= <string_literal>
The format that timestamp strings are encoded with in the import data.
For example:
'YYYY-MM-DD HH24:MI:SS' : 2012-05-20 14:30:25
ERROR LOG <file_path_of_error_log>
<file_path_of_error_log> ::= <string_literal>
You can store a log of errors that occur during import. Please ensure the file path you use is writeable by the
database.
Note:
All <string_literal>s in the <import_from_option> support UTF-8 except surrogate-pair encoding.
Description
The IMPORT FROM statement imports external data from a file into an existing table.
Examples
Example 1 -Importing CSV data
You create a ta ble MYTABLE to store the imported data.
CREATE TABLE MYTABLE ( A INT, B VARCHAR(10), C DATE, D TIME, E DECIMAL );
You create a CSV text file /data/data.csv and add the following contents.
1,"DATA1","2012-05-20","14:30:25",123456
2,"DATA2","2012-05-21","15:30:25",234567
3,"DATA3","2012-05-22","16:30:25",345678
4,"DATA4","2012-05-23","17:30:25",456789
SAP HANA Database - SQL Reference Manual
171 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 172/193
You execute the following command to import the data.
IMPORT FROM CSV FILE '/data/data.csv' INTO "MYTABLE" WITH RECORD DELIMITED BY '\n'
FIELD DELIMITED BY ',';
Example 2 - Importing using a control file
In the example below you import the CSV data from Example 1 using a control file:
You can create a control file /data/data.ct l and add the contents shown below to the file.
IMPORT DATA INTO TABLE "MYTABLE" FROM '/data/data.csv'
RECORD DELIMITED BY '\n'
FIELD DELIMITED BY ','
OPTIONALLY ENCLOSUED BY '"'
ERROR LOG '/data/data.err'
You execute the following command to import the data using the control file.
IMPORT FROM CONTROL FILE '/data/data.ctl';
Example 3 - Import using date formats
In the example below the date format is of the CSV import data is different to the default date format 'YYYY-
MM-DD'. In this import data the date format used is 'MM-DD-YYYY'.
You create a CSV text file /data/data_different_date.csv and add the following contents.
1,"DATA1","05-20-2012","14:30:25",123456
2,"DATA2","05-21-2012","15:30:25",234567
3,"DATA3","05-22-2012","16:30:25",345678
4,"DATA4","05-23-2012","17:30:25",456789
You execute the following command to import the data.
IMPORT FROM CSV FILE '/data/data_different_date.csv' INTO "MYTABLE" WITH RECORD DEL
IMITED BY '\n' FIELD DELIMITED BY ',' DATE FORMAT 'MM-DD-YYYY';
Example 4 - Import using COLUMN LIST
You create a ta ble called COLLIST to store the imported data.
CREATE TABLE COLLIST ( A INT, B VARCHAR(10), c DATE, D DECIMAL );
You create a CSV text file '/data/data_col_list.csv' and add the following contents.
1,"DATA1","2012-05-20",123456
2,"DATA2","2012-05-21",234567
3,"DATA3","2012-05-22",345678
4,"DATA4","2012-05-23",456789
You execute the following commands to import the data using a column list.
IMPORT FROM CSV FILE '/data/data_col_list.csv' INTO "COLLIST" WITH RECORD DELIMITED
BY '\n' FIELD DELIMITED BY ',' COLUMN LIST ("A", "B", "D");
IMPORT SCAN
Syntax
IMPORT SCAN <path>
Syntax Elements
<path> ::= <string_literal>
The path of the directory to be scanned for import data.
Description
SAP HANA Database - SQL Reference Manual
172 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 173/193
The IMPORT SCAN statement scans the path and fills the session-local temporary table
#IMPORT_SCAN_RESULT with the contents in the path.
Example
You scan the path '/data/import_path' for import data.
IMPORT SCAN '/data/import_path'
You select the data in the #IMPORT_SCAN_RESULT table to view the result of the scan.
SELECT * FROM #IMPORT_SCAN_RESULT;
Procedural Statements
ALTER PROCEDURE RECOMPILE
Syntax
ALTER PROCEDURE <proc_name> RECOMPILE [WITH PLAN]
Syntax Elements
<proc_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
The identifier of the procedure to be altered, with optional schema name.
WITH PLAN
Specifies that internal debug information should be created during execution of the procedure.
Description
The ALTER PROCEDURE R ECOMPILE statement manually triggers a recompilation of a procedure by
generating an updated execution plan. For production code a procedure should be compiled without theWITH PLAN option to avoid overhead during compilation and execution of the procedure.
Example
You trigger the recompilation of the my_proc procedure to produce debugging information.
ALTER PROCEDURE my_proc RECOMPILE WITH PLAN;
CALL
Syntax
CALL <proc_name> (<param_list>) [WITH OVERVIEW] [IN DEBUG MODE]
Syntax Elements
<proc_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
The identifier of the procedure to be called, with optional schema name.
<param_list> ::= <proc_param>[{, <proc_param>}...]
Specifies one or more procedure parameters.
<proc_param> ::= <identifier> | <string_literal> | <unsigned_integer> | <signed_int
eger>| <signed_numeric_literal> | <unsigned_numeric_literal>
Procedure parameters. For more information on these data types please see BNF Lowest Terms
Representations and Data Types.
SAP HANA Database - SQL Reference Manual
173 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 174/193
Parameters passed to a procedure are scalar constants and can be passed either as IN, OUT or INOUT
parameters. Scalar parameters are assumed to be NOT NULL. Arguments for IN parameters of table type
can either be physical tables or views. The actual value passed for tabular OUT parameters must be`?`.
WITH OVERVIEW
Defines that the result of a procedure call will be stored directly into a physical table.
Calling a procedure WITH OVERVIW will return one result set that holds the information of which table
contains the result of a particular table’s output variable. Scalar outputs will be represented as temporary
tables with only one cell. When you pass existing tables to the output parameters WITH OVERVIEW will insert
the result set tuples of the procedure into the provided tables. When you pass NULL to the output
parameters, temporary tables holding the result sets will be generated. These tables will be dropped
automatically once the database session is closed.
IN DEBUG MODE
When specified additional debug information will be created during the execution of the procedure. This
information can be used to debug the instantiation of the internal execution plan of the procedure.
Note: that this type of call implies additional runtime overhead and so it should only be used for debugging
purposes.
Description
Calls a procedure defined with CREATE PROCEDURE.
CALL conceptually returns list of result sets with one entry for every tabular result. An iterator ca n be used to
iterate over these results sets. For each result set you can iterate over the result table in the same way as for
query results. SQL statements that are not assigned to any table variable in the procedure body will be added
as result sets at the end of the list of result sets. The type of the result structures will be determined during
compilation time but will not be visible in the signature of the procedure.
CALL when executed by the client the syntax behaves in a way consistent with the SQL standard semantics,
e.g. Java clients can call a procedure using a JDBC CallableStatement. Scalar output variables will be a scalar
value that can be retrieved from the callable statement directly.
Note:
Unquoted identifiers are implicitly treated as upper case. Quoting identifiers will respect
capitalization and allow for using white spaces which are normally not allowed in SQL identifiers.
Examples
You call the getOutput procedure in debug mode.
CALL getOutput (1000, 'EUR', NULL, NULL) IN DEBUG MODE;
You call the procedure getOutput using the WITH OVERVIEW option.
CALL getOutput(1000, 'EUR', ot_publishers, NULL) WITH OVERVIEW;
CREATE FUNCTION
Syntax
CREATE FUNCTION <func_name> [(<parameter_clause>)] RETURNS <return_type> [LANGUAGE
<lang>] [SQL SECURITY <mode>]
AS
<local_scalar_variables>
BEGIN
<function_code>
END
Syntax Elements
<func_name > ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
SAP HANA Database - SQL Reference Manual
174 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 175/193
The identifier of the function to be created, with optional schema name.
<parameter_clause> ::= <parameter> [{,<parameter>}…]
The input parameters of the function.
<parameter> ::= [IN] <param_name> <datatype>
A function parameter with associated data type.
<param_name> ::= <identifier>
The variable name for a parameter.
<datatype> ::= <sql_type> | <table_type>
The input parameters of a function can have any of the primitive SQL types or a table type.
<sql_type> ::= BIGINT | INTEGER | SMALLINT | TINYINT | DATE | TIME | TIMESTAMP | SM
ALLDECIMAL | DECIMAL | REAL | DOUBLE
The data type of the variable. Please see Data Types.
<table_type> ::= <identifier>
A table type previously defined with the CREATE TYPE command. Please see CREATE TYPE.
<return_type> := <sql_type> | <return_table_type>
The returned results of a function can have any of the primitive SQL types or a return table type.
<return_table_type> := TABLE (<ret_column_list>)
Defines the structure of the returned table data.
<ret_column_list> := <ret_column_elem>[{, <ret_column_elem>}]
Defines the list of columns returned from the function.
<ret_column_elem> := <column_name> <sql_type>
<column_name> := <identifier>
Defines the name of column element with associated datatype.
LANGUAGE <lang>
<lang> ::= SQLSCRIPT
Default: SQLSCRIPT
Defines the programming language used in the function.
Note:
Only SQLScript functions can currently be defined.
SQL SECURITY <mode> <mode> ::= DEFINER | INVOKER
Default: DEFINER
Specifies the security mode of the function.
DEFINER
Specifies that the execution of the function is performed with the privileges of the definer of the function.
INVOKER
Specifies that the execution of the function is performed with the privileges of the invoker of the function.
<local_scalar_variables> ::= {<local_var>;}...
SAP HANA Database - SQL Reference Manual
175 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 176/193
Defines local scalar variables for the function.
<local_var> ::= <variable_name> <datatype>
<variable_name> ::= <identifier>
Defines a local function variable with associated scalar type. Please see Data Types.
<function_code> := !! function statements.
Defines the main body of the function.
Description
The CREATE FUNCTION statement creates a function read only function which is free of side-effects. That is
to say that neither DDL or D ML statements (INSERT, UPDATE, and DELETE) are allowed in the function body.
Also other functions or procedures selected/called from the body of the function must be read-only.
Example
You create an SQLScript function with the following definition.
CREATE FUNCTION scale (val INT) RETURNS TABLE (a INT, b INT) LANGUAGE SQLSCRIPT AS
BEGIN
RETURN SELECT a, :val * b AS b FROM mytab;
END;
You use the scale function with the following example select statements.
select * from scale(10);
select * from scale(10) as a, scale(10) as b where a.a = b.a
CREATE PROCEDURE
Syntax
CREATE PROCEDURE <proc_name> [(<parameter_clause>)] [LANGUAGE <lang>] [SQL SECURITY
<mode>] [READS SQL DATA [WITH RESULT VIEW <view_name>]] AS
<local_scalar_variables>
BEGIN
<procedure_code>
END
Syntax Elements
<proc_name > ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
The identifier of the procedure to be created, with optional schema name.
<parameter_clause> ::= <parameter> [{,<parameter>}…]
The input and output parameters of the procedure.
<parameter> ::= [<param_inout>] <param_name> <datatype>
A procedure parameter with associated data type.
<param_inout> ::= IN|OUT|INOUT
Default: IN
Each parameter is marked using the keywords IN/OUT/INOUT. Input and output parameters must be
explicitly typed (i.e. no un-typed tables are supported).
<param_name> ::= <identifier>
The variable name for a parameter.
<datatype> ::= <sql_type> | <table_type>
SAP HANA Database - SQL Reference Manual
176 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 177/193
The input and output parameters of a procedure can have any of the primitive SQL types or a table type.
INOUT parameters can only be of scalar type.
<sql_type> ::= DATE | TIME | SECONDDATE | TIMESTAMP | TINYINT | SMALLINT | INTEGER
| BIGINT | SMALLDECIMAL | DECIMAL
| REAL | DOUBLE | VARCHAR | NVARCHAR | ALPHANUM | SHORTTEXT | VARBINA
RY | BLOB | CLOB | NCLOB | TEXT
The data type of the variable. Please see Data Types.
<table_type> ::= <identifier>
A table type previously defined with the CREATE TYPE command. Please see CREATE TYPE.
LANGUAGE <lang>
<lang> ::= SQLSCRIPT | R
Default: SQLSCRIPT
Defines the programming language used in the procedure. It is good practice to define the language in all
procedure definitions.
SQL SECURITY <mode>
<mode> ::= DEFINER | INVOKER
Default: DEFINER
Specifies the security mode of the procedure.
DEFINER
Specifies that the execution of the procedure is performed with the privileges of the definer of the procedure.
INVOKER
Specifies that the execution of the procedure is performed with the privileges of the invoker of the
procedure.
READS SQL DATA
Marks the procedure as being read-only, side-effect free i.e. the procedure does not make modifications to
the database data or its structure. This means that the procedure does not contain DDL or DML statements,
and that the procedure only calls other read-only proceedures. The advantage of using this parameter is that
certain optimizations are available for read-only procedures.
WITH RESULT VIEW <view_name>
<view_name> ::= <identifier>
Specifies the result view to be used as the output of a read-only procedure.
When a result view is defined for a procedure, it can be called by an SQL statement in the same way as a
table or view. Please see Example 2 - Using a result view below.
<local_scalar_variables> ::= {<local_var>;}...
Defines local scalar variables for the procedure.
<local_var> ::= <variable_name> <datatype>
<variable_name> ::= <identifier>
Defines a local procedure variable with associated scalar type. Please see Data Types.
<procedure_code> := !! Procedure statements.
Defines the main body of the procedure according to the programming language selected.
For more information about SQLScript please see the "SQLScript reference". For more information on the R-
Language please see the "R-Language reference". Both reference documents are available from theSAP
HANA Appliance page.
Description
SAP HANA Database - SQL Reference Manual
177 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 178/193
The CREATE PROCEDURE statement creates a procedure using the specified programming language <lang>.
Examples
Example 1 - Creating an SQL Procedure
You create an SQLScript procedure with the following definition.
CREATE PROCEDURE orchestrationProc
LANGUAGE SQLSCRIPT AS
v_id BIGINT;
v_name VARCHAR(30);
v_pmnt BIGINT;
v_msg VARCHAR(200);
CURSOR c_cursor1 (p_payment BIGINT) FOR
SELECT id, name, payment FROM control_tab
WHERE payment > :p_payment
ORDER BY id ASC;
BEGIN
CALL init_proc();
OPEN c_cursor1(250000);
FETCH c_cursor1 INTO v_id, v_name, v_pmnt;
v_msg := :v_name || ' (id ' || :v_id || ') earns ' || :v_pmnt || ' $.';
CALL ins_msg_proc(:v_msg);
CLOSE c_cursor1;
END;
The procedure features a number of imperative constructs including the use of a cursor (with associated
state) and local scalar variables with assignments.
Example 2 - Using a result view
You create a procedure using a result view ProcView to return its results.
CREATE PROCEDURE ProcWithResultView(IN id INT, OUT o1 CUSTOMER)
LANGUAGE SQLSCRIPT
READS SQL DATA WITH RESULT VIEW ProcView AS
BEGIN
o1 = SELECT * FROM CUSTOMER WHERE CUST_ID = :id;
END;
You call this procedure from an SQL statement as follows.
SELECT * FROM ProcView WITH PARAMETERS ('placeholder' = ('$$id$$', '5'));
CREATE TYPE
Syntax
CREATE TYPE <type_name> AS TABLE (<column_definition>[{,<column_definition>}...])
Syntax Elements
<type_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
Identifies the table type to be created and, optionally, in which schema the creation should take place.
<column_definition> ::= <column_name> <data_type> [<column_store_data_type>] [<ddic
_data_type>]
Defines a table column.
<column_name> ::= <identifier>
The table column name.
<data_type> ::= DATE | TIME | SECONDDATE | TIMESTAMP | TINYINT | SMALLINT | INTEGER
| BIGINT | SMALLDECIMAL | DECIMAL
| REAL | DOUBLE | VARCHAR | NVARCHAR | ALPHANUM | SHORTTEXT | VARBINA
RY | BLOB | CLOB | NCLOB | TEXT
SAP HANA Database - SQL Reference Manual
178 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 179/193
<column_store_data_type> ::= CS_ALPHANUM | CS_INT | CS_FIXED | CS_FLOAT | CS_DOUBLE
| CS_DECIMAL_FLOAT | CS_FIXED(p-s, s)
| CS_SDFLOAT | CS_STRING | CS_UNITEDECFLOAT | CS_DATE |
CS_TIME | CS_FIXEDSTRING | CS_RAW
| CS_DAYDATE | CS_SECONDTIME | CS_LONGDATE | CS_SECONDDA
TE
<ddic_data_type> ::= DDIC_ACCP | DDIC_ALNM | DDIC_CHAR | DDIC_CDAY | DDIC_CLNT | DD
IC_CUKY | DDIC_CURR | DDIC_D16D
| DDIC_D34D | DDIC_D16R | DDIC_D34R | DDIC_D16S | DDIC_D34S | DD
IC_DATS | DDIC_DAY | DDIC_DEC
| DDIC_FLTP | DDIC_GUID | DDIC_INT1 | DDIC_INT2 | DDIC_INT4 | DD
IC_INT8 | DDIC_LANG | DDIC_LCHR
| DDIC_MIN | DDIC_MON | DDIC_LRAW | DDIC_NUMC | DDIC_PREC | DD
IC_QUAN | DDIC_RAW | DDIC_RSTR
| DDIC_SEC | DDIC_SRST | DDIC_SSTR | DDIC_STRG | DDIC_STXT | DD
IC_TIMS | DDIC_UNIT | DDIC_UTCM
| DDIC_UTCL | DDIC_UTCS | DDIC_TEXT | DDIC_VARC | DDIC_WEEK
The available data types. Please see Data Types
Description
The CREATE TYPE statement creates a user-defined type.
The syntax for defining table types follows the SQL syntax for defining new types. The table type is specified
using a list of attribute names and primitive data types. For each table type, attributes must have unique
names.
Example
You create a table type called tt _publishers.
CREATE TYPE tt_publishers AS TABLE (
publisher INTEGER,
name VARCHAR(50),
price DECIMAL,
cnt INTEGER);
You create a ta ble type called tt_years.
CREATE TYPE tt_years AS TABLE (
year VARCHAR(4),
price DECIMAL,
cnt INTEGER);
DROP FUNCTION
Syntax
DROP FUNCTION <func_name> [<drop_option>]
Syntax Elements
<func_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
The name of the function to be dropped, with optional schema name.
<drop_option> ::= CASCADE | RESTRICT
When <drop_option> is not specified a non-cascaded drop will be performed. This will only drop the specified
function, dependent objects of the function will be invalidated but not dropped.
The invalidated objects can be revalidated when an object that has same schema and object name is creat ed.
CASCADE
Drops the function and dependent objects.
RESTRICT
SAP HANA Database - SQL Reference Manual
179 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 180/193
Drops the function only when dependent objects do not exist. If this drop option is used and a dependent
object exists an error will be thrown.
Description
Drops a function created using CREATE FUNCTION from the database catalog.
Examples
You drop a function called my_func from the database using a non-cascaded drop.
DROP FUNCTION my_func;
DROP PROCEDURE
Syntax
DROP PROCEDURE <proc_name> [<drop_option>]
Syntax Elements
<proc_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
The name of the procedure to be dropped, with optional schema name.
<drop_option> ::= CASCADE | RESTRICT
When <drop_option> is not specified a non-cascaded drop will be performed. This will only drop the specified
procedure, dependent objects of the procedure will be invalidated but not dropped.
The invalidated objects can be revalidated when an object that has same schema and object name is creat ed.
CASCADE
Drops the procedure and dependent objects.
RESTRICT
Drops the procedure only when dependent objects do not exist. If this drop option is used and a dependent
object exists an error will be thrown.
Description
Drops a procedure created using CREATE PROCEDURE from the database catalog.
Examples
You drop a procedure called my_proc from the database using a non-cascaded drop.
DROP PROCEDURE my_proc;
DROP TYPE
Syntax
DROP TYPE <type_name> [<drop_option>]
Syntax Elements
<type_name> ::= [<schema_name>.]<identifier>
<schema_name> ::= <identifier>
The identifier of the table type to be droppped, with optional schema name.
<drop_option> ::= CASCADE | RESTRICT
SAP HANA Database - SQL Reference Manual
180 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 181/193
When <drop_option> is not specified a non-cascaded drop will be performed. This will drop only the specified
type, dependent objects of the type will be invalidated but not dropped.
The invalidated objects can be revalidated when an object that has same schema and object name is creat ed.
Description
The DROP TYPE statement removes a user-defined table type.
Example
You create a table type called my_type.
CREATE TYPE my_type AS TABLE ( column_a DOUBLE );
You drop the my_type table type.
DROP TYPE my_type;
SAP HANA Database - SQL Reference Manual
181 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 182/193
Restrictions for SQL Statements
The table below shows the maximum allowable limit for each entry.
SAP HANA Database - SQL Reference Manual
182 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 183/193
Database
Database size limit Limited by storage size RS: 1TB
Number of locks Unlimited for record locks,16384 for table locks
Number of sessions 8192
Schemas
Number of tables in a schema 131072
Identifier length 127 characters
Length of an alias name 128 characters
Table name length Please see "Identifier length" above
Column name length Please see "Identifier length" above
Length of a constant string literal 32767 bytes
Number of hex characters in a binary literal 8192
Tables and Views
Number of columns in a table 1000
Number of columns in a view 1000
Number of partitions of a column table 1000
Number of rows in each table
Limited by storage size RS:
1TB/sizeof(row),
CS: 2^31 * number of partitions
Length of a row Limited by RS storage size ( 1TB )
Size of a non-partitioned table Limited by RS storage size ( 1TB )
Indexes and Constraints
Number of indexes for each table 1023
Number of primary key columns in each table 16
Number of columns in an index 16
Number of columns in a UNIQUE constraint 16
Size of sum of primary key, index, UNIQUE
constraint16384
SQL
SAP HANA Database - SQL Reference Manual
183 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 184/193
Length of an SQL statement 2GB
Depth of SQL view nesting 128
Depth of SQL parse tree 255
Number of joined tables in an SQL statement or view 255
Number of columns in an ORDER BY, GR OUP BY or SELECT
clause65535
Number of elements in predicates 65535
Number of elements in SELECT clause 65535
SQLScript
Size of all stored proceduresLimited by RS storage size ( 1TB )
Note:
You can obtain the current system limits from your SAP HANA Database instance by using
select * from m_system_limits
See Also
M_SYSTEM_LIMITS in the System Tables and Monitor Views Reference
SAP HANA Database - SQL Reference Manual
184 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 185/193
SQL Error Codes
The following table lists error codes displayed by SAP HANA database and their descriptions.
SAP HANA Database - SQL Reference Manual
185 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 186/193
Error
Code Description
1 General wa rning
2 General error
3 Fa tal error
4 Ca nnot a l locate enough memory
5 Initia l ization error
6 Inval id data
7 Feature not supported
8 Inval id a rgument
9 Index out of bounds
10 Inval id username or pass word
11 Inval id s tate
12 Ca nnot open fi le
13 Ca nnot crea te/write fi le
14 Ca nnot a llocate enough disk space
15 Ca nnot find fi le
16 Statement retry
17 Me ta da ta s ch ema v ers i on i nco mp ati bl e b etw ee n da ta ba s e a nd e xe cu ta bl e f il e
18 Servi ce s hutting down
19 Inval id l icense
128 Trans action error
129 Tra ns a cti on rol l ed ba ck by a n in te rna l error
130 Tra n s act io n ro l l ed ba ck by i n te gri ty co ns tra i n t vi o l a ti o n
131 Tra ns a cti on rol l ed ba ck by l ock wa i t ti me out
132 Tra ns a cti on ro ll e d b ack du e to un ava i l ab le re s ou rce
133 Tra ns a cti on ro ll e d b ack b y d ete cte d d ea dl ock
134 Fa il ure in acce ss ing che ckpoi nt fi le
135 Fa il ure in a cce ss ing a nchor fi le
136 Fa ilure in a ccess ing l og fi le
137 Fa il ure i n a cce ss ing a rchi ve fi le
138 Tra ns acti on s eri al iza ti on fa il ure
139 Cu rre n t o pe ra ti o n ca n ce l l e d b y re q ue s t a n d t ra n s acti o n ro l l ed b a ck
140 I nva l id wri te -tra ns a cti on i de nti fi er
141 Fa il ure in a cce ss ing i nvi si bl e l og fi le
142 Exce e d m ax n um o f co ncu rre nt tra ns a cti on s
143 Tra ns a cti on s eri a l iza ti on fa i l ure un ti l ti me ou t e xp ire s
144 Tra ns a cti on ro ll ba ck , u ni qu e co ns tra i nt vi ol a te d
145 Tra ns a cti on di s tri buti on work fa i lu re
146 R es ou rce bu sy a nd acq ui re wi th NOWAI T s pe ci fi e d
147 I ncons is te ncy be twe en da ta and l og
148 Tra n s act io n s ta rt i s bl o ck e d u nt il Ma s te r_ Re s ta rt f in i s he s
149 D is tri bu te d tra ns a cti on commi t fa i lure
150 Sta te me nt ca nce ll ed d ue to ol d s na ps hot
256 SQL process ing error
257 SQL s yntax error
258 Insuffici ent pri vi lege
259 Inval id tabl e name
260 Inval id column na me
261 Inval id i ndex name
262 Inval id query name
263 Inval id a l ia s na me
264 Inval id data type
265 Express i on mis s ing
266 Inconsis tent da tatype
267 Sp eci fi ed le ngth to o l ong for i ts da ta type
268 Col umn a mbi guous ly defi ne d
SAP HANA Database - SQL Reference Manual
186 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 187/193
269 Too many va lues
270 Not enough val ues
271 Dupl icate a l ias
272 Dupl icate column name
273 Not a si ngl e cha ra cter s tri ng274 I ns erte d va lue too la rge for col umn
275 Aggre ga te functi on not a ll owe d
276 Mi ss ing a ggre ga ti on or groupi ng
277 Not a GROUP BY express i on
278 Ne ste d grou p functi on wi tho ut GROUP BY
279 Group function is nes ted
280 OR DER BY i te m mu st b e th e n um be r o f a SELECT-l i s t
281 Oute r jo in not a l lo we d i n op era nd of OR or I N
282 Tw o ta bl e s ca nn ot b e o ute r- jo in ed to e a ch oth er
283 A ta bl e ma y b e o ute r jo in ed to at m os t o ne oth er ta bl e
284 Join fiel d does not ma tch
285 Inval id join condition
286 Identi fier i s too long
287 Ca nn ot i ns ert NULL or upd ate to NULL
288 Ca nnot us e dupl ica te ta bl e na me
289 Ca nnot us e dupl ica te index na me
290 Ca nnot us e dupl ica te que ry na me
291 Argume nt i de nti fi er mus t be po si ti ve
292 wrong number of a rgume nts
293 Argument type mis ma tch
294 Ca nn ot h ave more tha n o ne pri ma ry ke y
295 Too l ong multi key length
296 R epl i ca te d ta bl e mus t ha ve a p ri ma ry ke y
297 Ca nn ot u pd ate pri ma ry k ey f ie l d i n re pl i ca te d ta bl e
298 Ca nnot s tore DDL
299 Ca n no t d ro p i n de x u s ed fo r e n fo rce me n t o f u ni q ue /p ri m ary k e y
300 Argument i nde x i s out of ra nge
301 Uni que cons tra int vi ol ate d
302 I nva li d CHAR or VARCHAR va lue
303 I nva l id DATE, TI ME or TI MESTAMP va l ue
304 Divis ion by zero undefined
305 S in gl e -ro w q ue ry re tu rn s mo re th an o ne ro w
306 Inval id curs or
307 Numeric val ue out of range
308 Column name already exists
309 Co rre l ate d s ub qu ery ca nn ot ha ve TOP o r OR DER BY
310 SQL error in procedure
311 Ca nnot drop al l col umns in a ta bl e
312 Sequence is exhausted
313 Inval id s equence
314 Numeric overflow
315 Inval id s ynonym
316 w ro ng nu mb er of a rgu me nts i n fu ncti on i nvo ca ti on
317 P_QU ER YPLANS n ot e xi s ts no r va l i d fo rm at
318 D eci ma l pre ci s ion spe ci fi er i s o ut o f ra nge
319 De ci ma l sca le spe ci fi er i s out of ra nge
320 Ca nn ot cre a te i nd ex o n e xp re s s io n wi th da ta typ e LOB
321 Inval id view na me
322 Ca nnot us e dupl ica te vi ew na me
323 Dupl icate repl i cation ID
324 Ca nnot us e dupl ica te se que nce na me
325 Inval id esca pe sequence
SAP HANA Database - SQL Reference Manual
187 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 188/193
326 CU RR VAL of gi ve n se qu en ce i s no t ye t d efi ne d in th is s e ss i on
327 Ca nnot e xpl ai n pl an of gi ve n s ta te me nt
328 I nva l id n ame of fu ncti on or p roce dure
329 Ca nn ot us e du pl i ca te n am e of fu ncti on or pro ce du re
330 Ca nnot us e dupl ica te synonym na me331 User name already exists
332 Inval id user na me
333 Column not a l l owed
334 Inval id user pri vi lege
335 Fi el d a li as na me a lre ady exi sts
336 Inval id defa ult val ue
337 I NTO cl a us e no t a l l ow ed fo r th is SELECT s ta te me nt
338 Ze ro-l ength col lumns a re not a ll owe d
339 Inval id number
340 Not a l l varia bles bound
341 Numeric underflow
342 Col la tion confl ict
343 Inval id col la te name
344 Pa rse error in data loa der
345 Not a repl ication tabl e
346 Inval id repl ication ID
347 Inval id opti on in monitor
348 Inval id datetime format
349 Ca nnot CREATE UNIQUE INDEX
350 Ca nn ot dro p co lu mn s in th e pri ma ry-k ey co lu mn l is t
351 Co lu mn is re fe re nce d i n a mu lti -co lu mn co ns tra i nt
352 Ca nn ot cre ate uni que ind ex on CDX ta bl e
353 Upda te log group na me al re ady e xi sts
354 Inva li d upda te l og group na me
355 Th e ba s e ta bl e of th e up da te l og ta bl e mu st ha ve a p ri ma ry k ey
356 Exce ed ma xi mu m n umbe r of upd ate l og group
357 Th e b as e ta bl e a lre ad y h as a up da te l og ta bl e
358 Upda te l og ta bl e ca n not ha ve a up da te lo g ta bl e
359 Conca te na te d s tri ng is too long
360 Vi e w WI TH CH ECK OPTI ON wh ere -cl a us e vi ol a ti on
361 D ata ma ni pul a ti on op era ti on not le ga l on th is vi ew
362 Inval id s chema na me
363 Numbe r of inde x col umns e xce eds i ts ma xi mu m
364 Inval id partia l key s ize
365 N o m atch in g u ni qu e or p ri ma ry k ey fo r th is co lu mn l is t
366 R efe re nce d ta bl e d oe s not h ave a pri ma ry ke y
367 N um be r o f re fe re n ci n g co l um ns m us t m a tch re fe re n ce d co l um ns
368 U ni qu e co ns tra i nt n ot a l l ow ed on te mp ora ry ta bl e
369 Exce ed ma xi mum vi ew de pth l imi t
370 Ca n no t p e rf orm DI R ECT IN SER T o pe ra ti o n o n ta b l e wi th u ni q ue i n de xe s
371 Inval id XML document
372 Inval id XPATH
373 Inva li d XML dura ti on va lue
374 Inva li d XML functi on us age
375 Inva li d XML i ndex ope ra ti on
376 Python s tore d proce dure error
377 JIT opera tion error
378 Inval id column view
379 Ta ble schema mis ma tch
380 Fa i l to change run level
381 Fa i l to resta rt
382 Fa il to col le ct a ll ve rs ion ga rba ge
SAP HANA Database - SQL Reference Manual
188 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 189/193
383 Inval id i denti fi er
384 Cons tant string is too long
385 Could not restore s es sion
386 Ca nnot us e dupl ica te schema na me
387 Ta ble ambi guousl y defined388 Role already exists
389 Inval id role na me
390 Inval id user type
391 Inval ida ted view
392 Ca n't as sign cycl ic role
393 R ol e s mu st no t re ce i ve a pri vi l ege wi th gra nt op ti on
394 Error revoking role
395 Inva li d us er-de fi ned type na me
396 Ca nn ot u se dup li ca te us er-d efi ne d typ e n ame
397 Inval id object name
398 Ca nnot ha ve more tha n one orde r by
399 Role tree too deep
400 Pri ma ry k ey n ot a l l ow ed o n i ns e rt-o nl y ta bl e
401 U ni qu e co ns tra i nt n ot a l l ow ed on in se rt-o nl y ta bl e
402 Th e u se r wa s a l re a dy d ro pp ed be fo re qu ery e xe cu ti on
403 Internal error
404 I nva l i d ( no n-e xi s te nt) s tru ctu re d pri vi l ege n ame
405 Ca nn ot u se du pl i ca te s tru ctu re d p ri vi l ege na me
406 I NS ER T, UPD ATE an d U PS ER T a re d is a l l ow ed on th e ge n era te d fi e l d
407 Inval id date forma t
408 Pa s sword o r pa ra me te r re qu ire d fo r us er
409 Mul ti pl e va l ue s fo r a p ara me te r no t s upp orte d
410 Inval id privi lege namespace
411 Inval id tabl e type
412 Inval id pass word l ayout
413 La st n pa ss words ca n not be reus ed
414 Us er i s force d to cha nge pa ss word
415 User is dea ctivated
416 User is l ocked
417 Ca n't d ro p w ith ou t CAS CAD E s pe ci fi ca ti on
418 I nva li d vi ew que ry for cre ati on
419 Ca n't dro p wi th RESTR ICT spe ci fi ca ti on .
420 Pa s sword ch an ge curre ntl y n ot a l lo we d
421 Ca nnot crea te ful ltext i ndex
422 Pri vi l ege s mu st be e i th er al l SQL or al l fro m o ne n am es pa ce
423 Li veCache error
424 Inval id name of pa cka ge
425 Dupl icate package na me
426 Number of col umns mi sma tch
427 Ca nnot re se rve inde x I D a ny more
428 Inval id query plan ID
429 Integri ty check fa i l ed
430 Inval ida ted procedure
431 Us er's pa ss word wi ll exp ire wi thi n fe w da ys
432 Th i s s yn ta x h a s b e en de p re ca te d a n d w i ll be re mo ve d i n n e xt re l e a s e
433 Nul l value found
434 Inval id object ID
435 Inval id express ion
436 Coul d not s et s ys te m l ice ns e
437 O nl y co mm a nd s f or l i ce n se ha n dl i n g a re a l lo we d i n cu rre n t s ta te
438 Inva li d us er pa ra mete r va lue
439 Compos ite error
SAP HANA Database - SQL Reference Manual
189 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 190/193
440 Ta bl e type convers ion error
441 Th i s f ea tu re ha s be e n d e pre ca te d a n d w i ll be re mo ve d i n n ext re l e a s e
442 Numbe r of col umns e xce eds i ts ma xi mum
443 I nva li d ca lcul ati on s ce na ri o na me
444 Pa cka ge ma nager error512 Repl ication error
513 Ca n no t e xe cu te D DL s ta te me n t o n re pl i ca ti o n ta b l e w hi l e re p li ca ti n g
514 Fa il ure in a cce ss ing a nchor fi le
515 Fa ilure in a ccess ing l og fi le
516 R ep li ca ti on ta bl e h as no t co nfl i ct re po rt ta bl e
517 Co nfl i ct re port ta bl e a l re ady e na bl ed
518 Co nfl i ct re port ta bl e a l re ady di s abl ed
576 API error
577 Cu rs or type of forwa rd i s not a ll owe d
578 Inval id s tatement
579 Exceed maximum batch s ize
580 S e rve r re je cte d th e co nn e cti o n( pro to co l ve rs i o n m i s ma tch )
581 Th is f un cti on ca n be ca l le d on ly i n th e ca s e of si ngl e s ta te me nt
582 Thi s que ry doe s not ha ve re sul t s et
583 Connection does not exis t
584 No more lob da ta
585 Operation is not permitted
586 I nva l id pa ra me te r i s re ce ive d from se rve r
587 Res ul t s et i s curre ntl y i nva li d
588 Ne xt() is not ca ll ed for thi s re sul t s et
589 Too many para meters are set
590 Some pa ramters a re miss ing
591 Internal error
592 Not s upporte d type conve rs ion
593 Remote-onl y function
594 No more res ul t row i n res ul t s et
595 Sp eci fi ed pa ra me te r i s not outp ut pa ra me te r
596 LOB s tre a mi ng is n ot p erm itte d i n a uto -co mm it m od e
597 Sess ion context error
598 Fa i le d to e xe cu te the exte rn al sta te me nt
599 Se ss ion l aye r i s not i ni ti al ize d ye t
600 Fa iled routed executi on
601 Too ma ny s es si on va ri abl es are se t
602 Ca nnot s et re adonl y s es si on va ri abl e
603 Inval id LOB
604 Remote temp ta bl e a cces s fa il ure
605 Inval id XA join reques t
606 Exceed maximum LOB s ize
607 Fa iled to cleanup res ources
608 Exce e d m axi mu m n um be r o f p re pa re d s ta te me nts
1024 Sess ion error
1025 Communi ca ti on error
1026 Ca nn ot b ind a commu ni ca ti on port
1027 Co mmun ica ti on i ni ti a li za ti on e rror
1028 I/O control error
1029 Connection fa i l ure
1030 Send error
1031 Receive error
1032 Ca nnot crea te a threa d
1033 Error wh il e pa rs ing proto col
1034 Exce ed ma xi mu m n umbe r of s es s io ns
1035 Not s upported vers ion
SAP HANA Database - SQL Reference Manual
190 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 191/193
1036 Inval id s ess ion ID
1037 Unknown hostname
1280 SqlScript error
1281 W ro ng nu mb er or typ es o f p ara me te rs i n ca l l
1282 Outp ut p ara me te r not a va ri a bl e1283 O UT a nd I N OU T p a ra m et ers m a y n ot ha ve d e fa u l t e xp re s s i on s
1284 D up li ca te p ara me te rs are no t p erm itte d
1285 A t m os t on e de cl a ra ti o n is p e rm i tte d i n th e de cl a ra ti o n s e cti o n
1286 Cu rs o r m us t b e d e cl a re d b y S ELE CT s ta te me nt
1287 I de nti fi er mus t be de cl are d
1288 Exp re s si on ca nn ot be u se d as a n a ss i gn me nt ta rge t
1289 Express ion cannot be used as an INTO-target of SELECT/FETCH statement
1290 Exp re s s i on i s i n ap pro pri a te a s t he l e ft ha n d si d e of a n a s si gn me n t s ta te me nt
1291 Expre ss ion is of wrong type
1292 I l le ga l EXI T s ta te me nt, it mu st ap pe a r i ns i de a l oo p
1293 I de nti fi e r n ame mu st b e a n e xce pti on n am e
1294 An I NTO cl a us e i s e xp ecte d i n S ELECT s ta te me nt
1295 EXPLA IN PLA N a n d CAL L s ta te me n t a re n ot al l o we d
1296 Identi fi er i s not a curs or
1297 W ro ng nu mb er of va l u es i n th e IN TO li s t o f a F ET CH s ta te me nt
1298 Unha nd le d us er-d efi ne d e xce pti on
1299 No data found
1300 F e tch re tu rn s mo re th a n re qu e s te d nu mb e r o f ro ws
1301 Numeri c or va lue e rror
1302 Pa ra l l e l i za b l e fu ncti o n ca n no t h a ve O UT or IN OU T p a ra m ete r
1303 Us er-de fi ne d e xce pti on
1304 Curs or i s a lrea dy opened
1305 Return type is inva lid
1306 Return type mi sma tch
1307 Uns upporte d da ta type is us ed
1308 Il legal s ingle a ss i gnment
1309 I nva li d us e of ta bl e va ri abl e
1310 Sca la r type is not a ll owe d
1311 Out pa ra me te r i s not s pe ci fi ed
1312 At mo st one ou tpu t pa ra me te r i s a ll owe d
1313 O utp ut p a ra m ete r s h ou l d b e a ta b l e o r a ta b l e va ri a b le
1314 Inappropriate variab le name: do not a l low "" for the name of var iable or parameter
1315 R e tu rn re s ul t s et fro m se l e ct s tm t e xi s t wh e n re s ul t vi e w i s de fi n ed
1316 Some out ta bl e va r i s not as si gne d
1317 Fu ncti on na me exce ed es ma x. l i mi t
1318 Bui lt-i n functi on not de fi ne d
1319 Pa ra me te r mus t be a ta bl e na me
1320 Pa ra m et er mu s t b e a n at tri b ute n a me w i th ou t a t a bl e n a me u pf ro nt
1321 Pa ra m et er m us t b e a n a ttri b ute na m e w it ho ut a n a l i a s
1322 CE_CALC not a ll owe d
1323 Pa ra m et er m us t be a ve ct or o f co l um ns o r a gg re ga ti o ns
1324 Jo in a ttri bu te m us t be a va i la bl e i n pro je cti on l i st
1325 Pa ra m et er m us t b e a ve ct or o f S QL i d en ti fi e rs
1326 Dupl ica te a ttri bute na me
1327 Pa ra me te r h as a non sup porte d typ e
1328 Attri bute no t fo und i n col umn ta bl e
1329 Dupl icate column name
1330 S yn ta x Erro r fo r ca l cu la te d Attri bu te
1331 Synta x Error in fi lte r e xpre ss i on
1332 Pa ra me te r m us t b e a va l i d co lu mn ta bl e n am e
1333 Jo in a ttri bu te s n ot fo un d i n va ri a bl e
1334 I np ut pa ra me te rs d o n ot ha ve th e sa me ta bl e typ e
SAP HANA Database - SQL Reference Manual
191 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 192/193
1335 Cycl i c d e pe n de n cy f ou nd i n a ru nti m e p ro ce d ure
1336 Unexpected internal exception caught in a runtime procedure
1337 Va ri a bl e de pe nds o n a n una s si gne d va ri a bl e
1338 CE_CONVER SI ON : cu sto mi zi ng ta bl e m is s i ng
1339 Too many para meters1340 Th e d ep th of th e n es te d ca ll i s too de ep
1536 Swapx error
1537 Thi s ta bl e ha s no s wa p s pa ce
1538 Swa p a lrea dy a cti va te d
1539 Swa p not ye t a cti va ted
1540 Swa p s pa ce is not cre ate d
1541 Fa il ure in unpi nni ng a swa p pa ge
1542 Fa i lure i n s wap fi l e
1543 Fa il ure i n a cce ss ing swa p da ta fi le
1544 Fa il ure in acce ss ing s wa p l og fi le
1545 Swa p buffer overfl ow
1546 Swa p bu ffe r re se rva ti on fa il ure
1792 Shared memory error
1793 Inva li d key or i nva li d s ize
1794 The s egme nt a lre ady e xi sts
1795 Exce e d th e s ys te m-wi de l i mi t o n s ha re d me mo ry
1796 No segment exists for the g iven key, and IPC_CREAT was not speci f ied
1797 Th e u se r do e s no t h a ve p e rm i ss i o n to a cce s s th e s ha re d me mo ry s eg me n t
1798 N o m em ory co ul d b e a l l o ca te d f or s e gm en t o ve rh e a d
1799 Inval id s hmid
1800 Al low re ad a cce ss for s hmi d
1801 Sh mi d p oi nts to a re move d i de nti fi er
1802 Th e e ff ecti ve u s er ID o f th e ca l l i ng pro ce s s i s n ot th e cre a to r
1803 Th e GI D or UI D va l u e i s to o l arg e to b e s to re d i n th e s tru ct ure
1804 Th e u se r do e s no t h a ve p e rm i ss i o n to a cce s s th e s ha re d me mo ry s eg me n t
1805 Inval id s hmid
1806 No memory cou ld be al located for the descriptor or for the page tab les
1807 Unknown sha re d me mory e rror
2048 Column store error
2049 Pri ma ry k ey i s no t s pe ci fi e d fo r co lu mn ta bl e
2050 N ot s up po rte d d dl typ e fo r co lu mn ta bl e
2051 N ot s up po rte d d ata typ e fo r co lu mn ta bl e
2052 N ot s up po rte d d ml typ e f or co lu mn ta bl e
2053 I nva l i d re tu rn ed va l ue f ro m attri bu te e ngi ne
2304 Python DBAPI error
2305 Interface fa i lure
2306 Programming mistake
2307 Inva li d que ry pa ra me ter
2308 Not supp orte d e ncodi ng for stri ng
2560 Di stri bute d me ta da ta error
2561 DDL redi rect error
2562 DDL noti fi ca ti on e rror
2563 DDL i nva li d conta iner ID
2564 DDL i nva l id index ID
2565 D is tri bu te d e nvi ro nme nt e rror
2566 Network error
2567 Me ta da ta u pda te n ot sup po rte d in s la ve
2568 Me ta da ta u pd ate o f m as te r i nd exs e rve r i s fa i l ed
2816 SqlScript Error
2817 Sql Scri pt Bui lti n Functi on
2818 -
2889SqlScript
3584 Di stri buted SQL error
SAP HANA Database - SQL Reference Manual
192 2012-12-19
8/11/2019 hana_sql_ref_en.pdf
http://slidepdf.com/reader/full/hanasqlrefenpdf 193/193
3585 Expre ss ion s hi ppi ng fa il ure
3586 Ope ra tor s hi ppi ng fa il ure
3587 Invalid protocol or indexserver (statisticsserver) shutdown during distributed query execution
3588 Se quence shi ppi ng fa il ure
3589 R emo te que ry e xe ctui on fa il ure
3840 ge ne ra l a udi ti ng e rror
3841 Inval id privi lege
3842 Audi t tra il wri te r i s bl ocke d
3843 A ud i t p ol i cy w i th cu rre n t n a me a lre a dy e xi s ts
3844 I nva l id combi na ti on of audi t a cti on s
3845 I nva l id a cti on s ta tus for a ud iti ng
3846 Inval id auditing level
3847 Inval id pol i cy name
4096 G en era l erro r i n th e p ro ce s s o f s to re d p la n
4097 I nva l id ope ra ti on in ge ne ra ti ng pl a ns
4098 I nva l i d o pe ra ti on i n e xe cu ti on th e ch os e n p la n
4099 I nva l i d o pe ra ti on in s to ri ng th e p in ne d p la n
4100 I nva l i d o pe ra ti on in l oa di ng th e s to re d p la n
4101 I nva l i d o pe ra ti on in d el e ti ng th e ch os e n p la n
4103 F ai l ed to pre pa re f or ru nti me re org an iza ti on
4104 Tra n s act io n bl o ck e d s in ce r un ti m e re o rg a ni za ti o n i s i n p ro gre s s
SAP HANA Database - SQL Reference Manual