SQLScript HANA PDF
SQLScript HANA PDF
Dietmar-Hopp-Allee 16
69190 Walldorf
Germany
T +49/18 05/34 34 34
F +49/18 05/34 34 20
www.sap.com
form or for any purpose without the express permission of SAP AG.
The information contained herein may be changed without prior notice.
Institute of Technology.
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
of IBM Corporation.
Disclaimer
Linux is the registered trademark of Linus Torvalds in the U.S. and
other countries.
Adobe, the Adobe logo, Acrobat, PostScript, and Reader are either
Any Java Source Code delivered with this product is only to be used
by SAPs Support Services and may not be modified or altered in any
way.
Documentation in the SAP Service Marketplace
UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open
Group.
service.sap.com/hana
Table of Contents
SAP HANA Guides.................................................................................................................................... 9
Notation .............................................................................................................................................. 9
Introduction .......................................................................................................................................... 10
SQL .................................................................................................................................................... 10
Supported Languages and Code Pages ............................................................................................. 10
Comment .......................................................................................................................................... 10
Identifiers .......................................................................................................................................... 10
Single Quotation Mark ...................................................................................................................... 11
Double Quotation Mark .................................................................................................................... 12
SQL Reserved Words ......................................................................................................................... 12
Data Types............................................................................................................................................. 13
Classification of Data Types .............................................................................................................. 13
Datetime Types ................................................................................................................................. 13
Numeric Types .................................................................................................................................. 13
Character String Types ...................................................................................................................... 15
Binary Types ...................................................................................................................................... 15
Large Object (LOB) Types .................................................................................................................. 15
Supported Formats for Date, Time and Timestamp ......................................................................... 17
Data Type Conversion ....................................................................................................................... 19
Predicates.............................................................................................................................................. 22
Comparison Predicates ..................................................................................................................... 22
Range Predicate ................................................................................................................................ 22
In Predicate ....................................................................................................................................... 22
Exists Predicate ................................................................................................................................. 22
LIKE Predicate ................................................................................................................................... 22
NULL Predicate .................................................................................................................................. 23
Operators .............................................................................................................................................. 24
Unary and Binary Operators ............................................................................................................. 24
Operator Precedence ........................................................................................................................ 24
Arithmetic Operators ........................................................................................................................ 25
Guide/Tool
Quick Link
SAP HANA
Landscape,
Deployment &
Installation
https://service.sap.com/hana
SAP HANA
Administration &
Security
Notation
This reference use BNF (Backus Naur Form) which is the notation technique used to define
programming languages, to describe SQL. BNF describes the syntax of a grammar using a set of
production rules using a set of symbols.
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 alternative operator indicates that the portion of the formula following
the bar is an alternative to the portion preceding the bar.
...
The ellipsis indicates that the element may be repeated any number of times.
If ellipsis appears after grouped elements specifying that the grouped
elements enclosed with braces are repeated. If ellipsis appears after a single
element, only that element is repeated.
!!
Introduces normal English text. This is used when the definition of a syntactic
element is not expressed in BNF.
Introduction
This chapter describes the SAP HANA Database implementation of Structured Query Language
(SQL). It explains the characteristics of SQL, also how to manage comments and reserve words.
SQL
SQL stands for Structured Query Language. It is a standardized language for communicating with
a relational database. It is used to retrieve, store or manipulate information in the database.
SAP HANA Database manages tables using SQL statements to create or modify a table and to add
or manipulate data within a table.
SQL statements can perform the following tasks:
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:
Undelimited table and column names must start with a letter and cannot contain any
symbols other than digits or an underscore "_".
Delimited identifiers are enclosed in the delimiter, double quotes, then the identifier can
contain any character including special characters. For example, AB$%CD is a valid
identifier name.
Limitations
10
"_SYS_" is reserved exclusively for database engine, hence not allowed at the
beginning of schema object names.
Role name and user name must be specified as undelimited identifiers.
Maximum length for the identifiers is 127 characters.
11
ALTER
AS
BEFORE
BEGIN
BOTH
CASE
CHAR
CONDITION
CONNECT
CROSS
CUBE
CURRENT_CONNECTION
CURRENT_TIMESTAMP
CURRENT_UTCTIMESTAMP
DISTINCT
END
FOR
HAVING
INOUT
JOIN
LOOP
NULL
PRIOR
RIGHT
SET
SYSTIME
TRAILING
UTCTIME
WHERE
CURRENT_DATE
CURRENT_USER
CURRVAL
ELSE
EXCEPT
FROM
IF
INTERSECT
LEADING
MINUS
ON
RETURN
ROLLUP
SQL
SYSTIMESTAMP
UNION
UTCTIMESTAMP
WHILE
CURRENT_SCHEMA
CURRENT_UTCDATE
CURSOR
ELSEIF
EXCEPTION
FULL
IN
INTO
LEFT
NATURAL
ORDER
RETURNS
ROWID
START
SYSUUID
USING
VALUES
WITH
CURRENT_TIME
CURRENT_UTCTIME
DECLARE
ELSIF
EXEC
GROUP
INNER
IS
LIMIT
NEXTVAL
OUT
REVERSE
SELECT
SYSDATE
TOP
UTCDATE
WHEN
Undelimited table and column names must start with a letter and cannot contain any symbols
other than digits or an underscore "_". If the identifier is 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. However, "_SYS_" is reserved exclusively for database engine, hence not
allowed at the beginning of schema object names.
12
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 in
SAP HANA Database.
Data Type
Datetime types
Numeric types
Binary types
VARBINARY
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 'YYYYMM-DD HH24:MI:SS.FF7'. FFn represents the fractional seconds where n indicates the number
of digits in fractional part. . The range of the timestamp value is 0001-01-01
00:00:00.0000000 through 9999-12-31 23:59:59.9999999.
For details on supported formats for datetime types, refer to Table 4, Table 5, Table 6 and
Table 7.
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.
13
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 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.
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 keeping their precisions.
DECIMAL(p, s) is the SQL standard notation for fixed-point decimal. For instance, 3.14, 3.1415,
3.141592 are stored in a decimal(5, 4) column as 3.1400, 3.1415, 3.1416, respectively
keeping the specified precision(5) and scale(4).
REAL
The REAL data type specifies a single-precision 32-bit floating-point number.
DOUBLE
The DOUBLE data type specifies a single-precision 64-bit floating-point number. The minimum
value is -1.79769 x 10308 and the maximum value is 1.79769x10308 . The smallest positive
DOUBLE value is 2.2207x10-308 and the largest negative DOUBLE value is -2.2207x10-308.
FLOAT(n)
The FLOAT(n) data type specifies a 32-bit or 64-bit real number, where n specifies the
number of significant bits and can range between 1 and 53.
14
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.
Binary Types
Binary types are used to store bytes of binary data.
VARBINARY
The VARBINARY(n) data type is used to store binary data of a specified maximum length in
bytes, where n indicates the maximum length and is an integer between 1 and 5000.
BLOB
The BLOB data type is used to store large binary data.
CLOB
The CLOB data type is used to store large ASCII character data.
NCLOB
The NCLOB data type is used to store a large Unicode character object.
LOB types are provided for storing and retrieving such large data. LOB types support the following
operations.
LOB columns cannot appear in WHERE clauses as a predicate except LIKE, CONTAINS, =, or
<>.
LOB columns cannot be used in set operations such as EXCEPT. UNION ALL is an exception.
15
Table 3: Mapping between SQL Data Type and Column Store Data Type
Integer Types
Approximate Types
Decimal Types
Character Types
Binary Types
Date/Time Types
SQL Type
CS_INT
BIGINT
CS_FIXED(18,0)
REAL
CS_FLOAT
DOUBLE
CS_DOUBLE
FLOAT
CS_DOUBLE
FLOAT(p)
CS_FLOAT, CS_DOUBLE
DECIMAL
CS_DECIMAL_FLOAT
DECIMAL(p,s)
CS_FIXED(p-s,s)
SMALLDECIMAL
CS_SDFLOAT
VARCHAR
CS_STRING,CS_ALPHANUM,CS_UNITDECFLOAT,
CS_DATE,CS_TIME
NVARCHAR
CS_STRING,CS_ALPHANUM,CS_UNITDECFLOAT
CLOB, NCLOB
CS_STRING
ALPHANUM
CS_ALPHANUM
BLOB
CS_RAW
VARBINARY
CS_RAW
DATE
CS_DAYDATE, CS_DATE
TIME
CS_SECONDTIME, CS_TIME
TIMESTAMP
SECONDDATE
CS_SECONDDATE
16
Description
Examples
YYYY-MM-DD
Default format
YYYY/MM/DD
YYYY/MM-DD
YYYY-MM/DD
YYYYMMDD
MON
MONTH
RM
DDD
17
Description
HH24:MI:SS
Default format
HH:MI[:SS][AM|PM]
HH12:MI[:SS][AM|PM
]
HH24:MI[:SS]
Examples
Description
YYYY-MM-DD
HH24:MI:SS.FF7
Default format
FF [1..7]
Examples
The following date/time formats can additionally be used when converting a date/time type value
into a string value. The following functions can be used when selecting a date/time values with a
specific format.
Table 7: Additional date/time formats
Format
Description
Example
TO_CHAR(CURRENT_TIMESTAMP,D)
DAY
TO_CHAR(CURRENT_TIMESTAMP,DAY)
DY
TO_CHAR(CURRENT_TIMESTAMP,DY)
18
Description
Example
MON
TO_CHAR(CURRENT_TIMESTAMP,MON)
MONTH
TO_CHAR(CURRENT_TIMESTAMP,MONTH)
RM
TO_CHAR(CURRENT_TIMESTAMP,RM)
TO_CHAR(CURRENT_TIMESTAMP,Q)
TO_CHAR(CURRENT_TIMESTAMP,W)
WW
TO_CHAR(CURRENT_TIMESTAMP,WW)
Sample examples
Table 8. Implicit Type conversion Examples
Input Expression Transformed Expression with Implicit Conversion
BIGINT > VARCHAR BIGINT > BIGINT(VARCHAR)
BIGINT > DECIMAL
Boxes with OK mean data type conversions are allowed without any checks.
19
Boxes with CK mean the data type can be converted if the data is valid for the target
type.
Boxes with - indicate that data type conversion is not allowed.
The rule is applicable to both implicit and explicit conversion except for Time to Timestamp
conversion. Only explicit conversion is allowed for converting the Time data type to Timestamp
using the TO_TIMESTAMP or CAST function.
integer
bigint
decimal
decimal(p,s)
smalldecimal
real
double
varchar
nvarchar
tinyint
Target
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
CK
CK
CK
OK
OK
OK
CK
CK
CK
OK
OK
OK
CK
CK
CK
OK
OK
CK
CK
OK
OK
OK
OK
OK
OK
OK
Source
tinyint
smallint
CK
integer
CK
CK
bigint
CK
CK
CK
decimal
CK
CK
CK
CK
decimal(p,s)
CK
CK
CK
CK
CK
Ck
smalldecimal
CK
CK
CK
CK
OK
CK
real
CK
CK
CK
CK
OK
CK
CK
double
CK
CK
CK
CK
CK
CK
CK
CK
varchar
CK
CK
CK
CK
CK
CK
CK
CK
CK
nvarchar
CK
CK
CK
CK
CK
CK
CK
CK
CK
OK
CK
Target
Source
time
time
date
seconddate
timestamp
varchar
nvarchar
OK
OK
OK
OK
OK
OK
timestamp
OK
OK
OK
OK
date
seconddate
time
date
timestamp
time
date
seconddate
varchar
CK
CK
CK
CK
nvarchar
CK
CK
CK
CK
OK
CK
Target
Source
varbinary
varbinary
alphanum
varchar
nvarchar
OK
OK
alphanum
varchar
OK
OK
nvarchar
OK
OK
OK
CK
20
Highest
TIMESTAMP
SECONDDATE
DATE
TIME
DOUBLE
REAL
DECIMAL
SMALLDECIMAL
BIGINT
INTEGER
SMALLINT
TINYINT
NCLOB
NVARCHAR
CLOB
VARCHAR
BLOB
Lowest
VARBINARY
21
Predicates
A predicate is specified by combining one or more expressions or logical operators and returns one
of the following logical or truth values: TRUE, FALSE, or UNKNOWN.
Comparison Predicates
Two values can be compared using comparison predicates and returns true, false, or unknown.
Syntax:
<comparison_predicate> ::=
<expression> { = | != | <> | > | < | >= | <= } [ ANY | SOME| ALL ] { <expression_list> |
<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 is specified, a comparison returns true if at least one value
returned by subquery or expression_list is true.
ALL - When ALL is specified, a comparison returns true if the comparison for all values returned by
subquery or expression_list is true.
Range Predicate
A value can be compared with the 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. A true will only be returned if expression2 has a
lesser value than expression3.
In Predicate
A value can be 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. A value, expression1, is tested for a pattern,
expression2. Wildcard characters ( % ) and ( _ ) may be used in the comparison string
expression2. LIKE returns true if the pattern specified by expression2 is found.
22
NULL Predicate
When IS NULL predicate is specified, a value can be compared with NULL and returns true if a
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
23
Operators
You can perform arithmetic operations in expressions by using operators. Operators can be used
for calculation, value comparison or to assign values.
Operation
Format
Description
Unary
A unary operator
applies to one
operand or a single
value expression.
operator operand
A binary operator
applies to two
operands or two
value expressions.
operand1 operator
operand2
Binary
Operator Precedence
An expression can use several operators, if the number of operators is greater than one, then the
SAP HANA Database will evaluate them in order of operator precedence. You can change this
ordering by using parentheses. The SAP HANA Database will always evaluate expressions
contained within parentheses first.
If parentheses are not used, the operators have the precedence indicated by the table below.
Please note, the SAP HANA Database will evaluate operators with equal precedence from left to
right within an expression.
Table 11. SQL operator precedence
Precedence
Operator
Operation
Highest
()
parentheses
+, -
*, /
multiplication, division
+, -
addition, subtraction
||
concatenation
comparison
NOT
logical negation
AND
conjunction
24
Operator
Operation
Lowest
OR
disjunction
Arithmetic Operators
You use arithmetic operators to perform mathematical operations such as adding, subtracting,
multiplying, dividing and negation of numeric values.
Table 12. Arithmetic operators
Operator
Description
-<expression>
<expression> + <expression>
<expression> - <expression>
<expression> * <expression>
String Operator
A concatenation operator combines two items such as strings, expressions, or constants into one.
Table 13. Concatenation operators
Operator
Description
<expression> || <expression>
Two string concatenation results in another string. For VARCHAR or NVARCHAR type strings,
leading or trailing spaces are kept. If either string is of data type NVARCHAR, the result has data
type NVARCHAR and is limited to 5000 characters. The maximum length for VARCHAR
concatenation is also limited to 5000 characters.
Comparison Operators
Syntax:
<comparison_operation> ::= <expression1> <comparison_operator> <expression2>
Table 14. Comparison operators
Operator
Description
Example
Equal to
>
Greater than
<
Less than
25
Description
Example
>=
<=
!=, <>
Not equal
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
Notes
AND
OR
NOT
Set Operators
The operators described in this section perform set operations on the results of two or more
queries.
Table 16. Set operators
Operator
Returned Value
UNION
UNION ALL
INTERSECT
Combines the results of two or more select statements or query expressions, and
returns all common rows.
EXCEPT
Takes output from the first query and then removes rows selected by the second
query.
26
Expressions
An expression is a clause that can be evaluated to return values.
Syntax:
expression ::=
<case_expression>
| <function_expression>
| <aggregate_expression>
| (<expression> )
| ( <subquery> )
| - <expression>
| <expression> <operator> <expression>
| <variable_name>
| <constant>
| [<correlation_name>.]<column_name>
Case Expressions
A case expression allows the user to use IF ... THEN ... ELSE logic without using procedures in SQL
statements.
Syntax:
case_expression ::=
CASE <expression>
WHEN <expression>
THEN <expression>, ...
[ ELSE <expression>]
{ END | END CASE }
If the expression following the CASE statement is equal to the expression following the WHEN
statement, then the expression following the THEN statement is returned. Otherwise the
expression following the ELSE statement is returned, if it exists.
27
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
MIN
MAX
SUM
AVG
STDDEV
VAR
28
Subqueries in expressions
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;
29
Functions
Functions are used to return information from the database. They are allowed anywhere an
expression is allowed. Functions use the same syntax conventions used by SQL statements.
cast
7
TO_ALPHANUM Function
Syntax:
TO_ALPHANUM (expression)
Description:
Converts the expression of a data type into a value of alphanum data type.
Example:
SELECT TO_ALPHANUM ('10') "to alphanum" FROM DUMMY;
Retrieves:
to alphanum
10
TO_BIGINT Function
Syntax:
TO_BIGINT (expression)
Description:
Converts the expression of a data type into a value of bigint data type.
Example:
SELECT TO_BIGINT ('10') "to bigint" FROM DUMMY;
Retrieves:
to bigint
10
30
to blob
abcde
TO_CLOB Function
Syntax:
TO_CLOB (expression)
Description:
Converts the expression of a data type into a value of CLOB data type.
Example:
SELECT TO_CLOB ('TO_CLOB converts an expression into a value of CLOB data type') "to clob"
FROM DUMMY;
Retrieves:
to clob
TO_CLOB converts an expression into a value of CLOB data type
TO_DATE Function
Syntax:
TO_DATE (expression [, format])
Description:
Converts the expression of a data type into a value of DATE data type.
Example:
SELECT TO_DATE('2010-01-12', 'YYYY-MM-DD') "to date" FROM DUMMY;
Retrieves:
to date
2010-01-12
TO_DATS Function
Syntax:
TO_DATS (expression)
Description:
Converts the expression of a data type into a value of ABAP DATE string with format YYYYMMDD.
Example:
SELECT TO_DATS ('2010-01-12') "abap date" FROM DUMMY;
Retrieves:
abap date
20100112
TO_DECIMAL Function
31
Syntax:
TO_DECIMAL (expression [, precision, scale])
Description:
Converts the expression of a data type into a value of DECIMAL (precision, scale) data type.
Example:
SELECT TO_DECIMAL(7654321.89, 9, 2) "to decimal" FROM DUMMY;
Retrieves:
to decimal
7654321.89
TO_DOUBLE Function
Syntax:
TO_DOUBLE (expression)
Description:
Converts the expression of a data type into a value of DOUBLE (double precision) data type.
Example:
SELECT 3*TO_DOUBLE ('15.12') "to double" FROM DUMMY;
Retrieves:
to double
45.36
TO_INT Function
Syntax:
TO_INT (expression)
Description:
Converts the expression of a data type into a value of INTEGER data type.
Example:
SELECT TO_INT('10') "to int" FROM DUMMY;
Retrieves:
to int
10
TO_INTEGER Function
Syntax:
TO_INTEGER (expression)
Description:
Converts the expression of a data type into a value of INTEGER data type.
Example:
SELECT TO_INTEGER ('10') "to int" FROM DUMMY;
Retrieves:
to int
10
TO_NCLOB Function
Syntax:
32
to nclob
TO_NCLOB converts an expression into a value of NCLOB data type
TO_NVARCHAR Function
Syntax:
TO_NVARCHAR (expression [,format])
Description:
Converts the expression of a data type into a value of unicode character data type.
If format is omitted, it converts to the corresponding format using the date format model.
Example:
SELECT TO_NVARCHAR(TO_DATE('2009/12/31'), 'YY-MM-DD') "to nchar" FROM DUMMY;
Retrieves:
to nchar
09-12-31
TO_REAL Function
Syntax:
TO_REAL (expression)
Description:
Converts the expression of a data type into the value of REAL (single precision) data type.
Example:
SELECT 3*TO_REAL ('15.12') "to real" FROM DUMMY;
Retrieves:
to real
45.36
TO_SMALLINT Function
Syntax:
TO_SMALLINT (expression)
Description:
Converts the expression of a data type into a value of SMALLINT data type.
Example:
SELECT TO_SMALLINT ('10') "to smallint" FROM DUMMY;
Retrieves:
to smallint
10
33
to tinyint
10
TO_TIME Function
Syntax:
TO_TIME (expression [, format])
Description:
Converts the expression of a data type into a value of TIME data type.
If format is omitted, it converts expression into the corresponding format using the date format
model as explained in Table 5.
Example:
SELECT TO_TIME ('08:30 AM', HH:MI AM) "to time" FROM DUMMY;
Retrieves:
to time
08:30:00
TO_TIMESTAMP Function
Syntax:
TO_TIMESTAMP (expression [, format])
Description:
Converts the expression of a data type into the TIMESTAMP data type.
If format is omitted, it converts expression into the corresponding format using the date format
model as explained in Table 5.
Example:
SELECT TO_TIMESTAMP ('2010-01-11 13:30:00', 'YYYY-MM-DD HH24:MI:SS') "to timestamp"
FROM DUMMY;
Retrieves:
to timestamp
2010-01-11 13:30:00.0000000
TO_VARCHAR Function
Syntax:
TO_VARCHAR (expression [, format])
Description:
Converts the expression of a data type into a value of character data type.
Example:
SELECT TO_VARCHAR (TO_DATE('2009-12-31'), 'YYYY/MM/DD') "to char" FROM DUMMY;
34
Retrieves:
to char
2009/12/31
35
DateTime Functions
ADD_DAYS Function
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;
Retrieves:
add days
2010-01-04
ADD_MONTHS Function
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;
Retrieves:
add months
2010-01-05
ADD_YEARS Function
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;
Retrieves:
add years
2010-12-05
ADD_SECONDS Function
Syntax:
ADD_SECONDS (t, n)
Description:
Computes the time t plus n seconds.
Example:
SELECT ADD_SECONDS (TO_TIME ('23:30:45'), 60*30) "add seconds" FROM DUMMY;
Retrieves:
add seconds
00:00:45.000
36
days between
31
DAYNAME Function
Syntax:
DAYNAME (expression)
Description:
Returns the name of the weekday in English.
Example:
SELECT DAYNAME ('2011-05-30') "dayname" FROM DUMMY;
Retrieves:
dayname
MONDAY
DAYOFMONTH Function
Syntax:
DAYOFMONTH (expression)
Description:
Returns the day of the month in integer.
Example:
SELECT DAYOFMONTH ('2011-05-30') "dayofmonth" FROM DUMMY;
Retrieves:
dayofmonth
30
DAYOFYEAR Function
Syntax:
DAYOFYEAR (expression)
Description:
Returns the day of the year in integer.
Example:
SELECT DAYOFYEAR ('2011-05-30') "dayofyear" FROM DUMMY;
Retrieves:
dayofyear
150
37
extract
2010
HOUR Function
Syntax:
HOUR (expression)
Description:
Extract hour from expression.
Example:
SELECT HOUR ('12:34:56) "hour" FROM DUMMY;
Retrieves:
hour
12
LAST_DAY Function
Syntax:
LAST_DAY (d)
Description:
Returns the date of the last day of the month that contains d.
Example:
SELECT LAST_DAY (TO_DATE('2010-01-04', 'YYYY-MM-DD')) "last day" FROM DUMMY;
Retrieves:
last day
2010-01-31
MINUTE Function
Syntax:
MINUTE (expression)
Description:
Extract minute from expression.
Example:
SELECT MINUTE ('12:34:56) "minute" FROM DUMMY;
Retrieves:
minute
34
MONTH Function
38
Syntax:
MONTH(expression)
Description:
Returns the number of the month from a given date.
Example:
SELECT MONTH ('2011-05-30) "month" FROM DUMMY;
Retrieves:
month
5
MONTHNAME Function
Syntax:
MONTHNAME(expression)
Description:
Returns the name of the month in English.
Example:
SELECT MONTHNAME ('2011-05-30) "monthname" FROM DUMMY;
Retrieves:
monthname
MAY
NEXT_DAY Function
Syntax:
NEXT_DAY (d)
Description:
Returns the date of the next day of d.
Example:
SELECT NEXT_DAY (TO_DATE ('2009-12-31', 'YYYY-MM-DD')) "next day" FROM DUMMY;
Retrieves:
next day
2010-01-01
NOW Function
Syntax:
NOW ()
Description:
Returns the current timestamp.
Example:
SELECT NOW () "now" FROM DUMMY;
Retrieves:
now
2010-01-01 16:34:19
39
second
56
SECONDS_BETWEEN Function
Syntax:
SECONDS_BETWEEN (d1, d2)
Description:
Computes the number of seconds between d1 and d2, which is semantically equal to d2 d1.
Example:
SELECT SECONDS_BETWEEN ('2009-12-05', '2010-01-05') "seconds between" FROM DUMMY;
Retrieves:
Seconds between
2678400
CURRENT_DATE Function
Syntax:
CURRENT_DATE
Description:
Returns the current local system date.
Example:
SELECT CURRENT_DATE "current date" FROM DUMMY;
Retrieves:
current date
2010-01-11
CURRENT_TIME Function
Syntax:
CURRENT_TIME
Description:
Returns the current local system time.
Example:
SELECT CURRENT_TIME "current time" FROM DUMMY;
Retrieves:
current time
17:37:37.279
40
2010-01-11 17:38:48.802
CURRENT_UTCDATE Function
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;
Retrieves:
CURRENT_UTCTIME Function
Syntax:
CURRENT_UTCTIME
Description:
Returns the current UTC time.
Example:
SELECT CURRENT_UTCTIME "Coordinated Universal Time" FROM DUMMY;
Retrieves:
CURRENT_UTCTIMESTAMP Function
Syntax:
CURRENT_UTCTIMESTAMP
Description:
Returns the current UTC timestamp.
Example:
SELECT CURRENT_UTCTIMESTAMP "Coordinated Universal Timestamp" FROM DUMMY;
Retrieves:
41
week
22
WEEKDAY Function
Syntax:
WEEKDAY (d)
Description:
Returns the day of week of a given date d. The return value ranges from 0 to 6, each of which
represents Monday to Sunday.
Example:
SELECT WEEKDAY (TO_DATE ('2010-12-31', 'YYYY-MM-DD')) "week day" FROM DUMMY;
Retrieves:
week day
4
YEAR Function
Syntax:
YEAR (d)
Description:
Returns the year number of a given date d.
Example:
SELECT YEAR (TO_DATE ('2011-05-30', 'YYYY-MM-DD')) "year" FROM DUMMY;
Retrieves:
year
2011
42
Number Functions
Number functions take numeric values or strings with numeric characters as inputs and returns
numeric values. When strings with numeric characters are given as inputs, implicit conversion from
string to number is performed automatically before computing the result values.
ABS Function
Syntax :
ABS (n)
Description:
Returns the absolute value of a numeric expression n.
Example:
SELECT ABS (-1) "absolute" FROM DUMMY;
Retrieves:
absolute
1
ACOS Function
Syntax:
ACOS (n)
Description:
Returns the arc-cosine, in radians, of a numeric expression n between -1 and 1.
Example:
SELECT ACOS (0.5) "acos" FROM DUMMY;
Retrieves:
acos
1.0471975511965979
ASIN Function
Syntax:
ASIN (n)
Description:
Returns the arc-sine, in radians, of a number n between -1 and 1.
Example:
SELECT ASIN (0.5) "asin" FROM DUMMY;
Retrieves:
asin
0.5235987755982989
ATAN Function
Syntax :
ATAN (n)
Description:
Returns the arc-tangent, in radians, of a number n. The argument is a number and the range of n
is unlimited.
Example:
43
atan
0.4636476090008061
ATAN2 Function
Syntax :
ATAN2 (n, m)
Description:
Returns the arc-tangent, in radians, of the ratio of two numbers n and m. This is the same result
as ATAN(n/m).
Example:
SELECT ATAN2 (1.0, 2.0) "atan2" FROM DUMMY;
Retrieves:
atan2
0.4636476090008061
BITAND Function
Syntax:
BITAND (expression1, expression2)
Description:
Calculates an AND operation on the bits of expression1 and expression2. Both expression1 and
expression2 must be non-negative integers. The BITAND function returns a result with BIGINT type.
Example:
SELECT BITAND (255, 123) "bitand" FROM DUMMY;
Retrieves:
bitand
123
ceiling
15
COS Function
Syntax:
COS (n)
Description:
44
cos
1.0
COSH Function
Syntax:
COSH (n)
Description:
Computes the hyperbolic cosine of n.
Example:
SELECT COSH (0.5) "cosh" FROM DUMMY;
Retrieves:
cosh
1.1276259652063807
COT Function
Syntax:
COT (n)
Description:
Computes the cotangent of n.
Example:
SELECT COT (40) "cot" FROM DUMMY;
Retrieves:
Cot
1.5423510453569202
EXP Function
Syntax:
EXP (n)
Description:
Returns the result of the base of natural logarithms e raised to the power of the given argument n.
Example:
SELECT EXP (1.0) "exp" FROM DUMMY;
Retrieves:
exp
2.718281828459045
FLOOR Function
Syntax:
FLOOR (n)
Description:
Returns the largest integer not greater than the given number n.
Example:
45
floor
14
GREATEST Function
Syntax:
GREATEST (n1 [, n2]...)
Description:
Returns the greatest value among the arguments: n1, n2, ...
Example:
SELECT GREATEST ('aa', 'ab', 'ba', 'bb') "greatest" FROM DUMMY;
Retrieves:
greatest
bb
LEAST Function
Syntax:
LEAST (n1 [, n2]...)
Description:
Returns the least value among the arguments: n1, n2...
Example:
SELECT LEAST('aa', 'ab', 'ba', 'bb') "least" FROM DUMMY;
Retrieves:
least
aa
LN Function
Syntax:
LN (n)
Description:
Returns the natural logarithm of the specified number.
Example:
SELECT LN (9) "ln" FROM DUMMY;
Retrieves:
ln
2.1972245773362196
LOG Function
Syntax :
LOG (m, n)
Description:
Returns the natural logarithm of n base m. The base m must be a positive value other than 1 and n
must be any positive value.
Example:
SELECT LOG (10, 2) "log" FROM DUMMY;
46
log
0.30102999566398114
MOD Function
Syntax:
MOD (n, d)
Description:
Returns the remainder of a number n divided by a divisor d.
When n is negative this function acts differently dto the standard computational modulo operation.
The following explains example of what MOD functions returns as the result.
Otherwise, this function calculates the remainder of the absolute value of n divided by the
absolute value of d to calculate the absolute value of the remainder. If m is less than 0, then
the returned remainder from MOD is a negative number, and if m is greater than 0, then the
returned remainder from MOD is a positive number.
Example:
SELECT MOD (15, 4) "modulus" FROM DUMMY;
Retrieves:
modulus
3
POWER Function
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;
Retrieves:
power
1024.0
ROUND Function
Syntax:
ROUND (n [, pos])
Description:
Rounds n to the specified pos amount of places after the decimal point.
Example:
SELECT ROUND (16.16, 1) "round" FROM DUMMY;
Retrieves:
round
16.2
SELECT ROUND (16.16, -1) "round" FROM DUMMY;
47
Retrieves:
round
20
SIGN Function
Syntax:
SIGN (n)
Description:
Returns the sign (positive or negative) of the given number.n. Returns 1 if n is a positive value, -1
if n is a negative value, and 0 if n is equal to zero.
Example:
SELECT SIGN (-15) "sign" FROM DUMMY;
Retrieves:
sign
-1
SIN Function
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;
Retrieves:
sine
1.0
SINH Function
Syntax:
SINH (n)
Description:
Returns the hyperbolic sine of n, where the argument is an angle expressed in radians.
Example:
SELECT SINH (0.0) "sinh" FROM DUMMY;
Retrieves:
sinh
0.0
SQRT Function
Syntax:
SQRT (n)
Description:
Returns the square root of a number n.
48
sqrt
1.4142135623730951
TAN Function
Syntax:
TAN (n)
Description:
Returns the tangent of an angle in radians.
Example:
SELECT TAN (0.0) "tan" FROM DUMMY;
Retrieves:
tan
0.0
TANH Function
Syntax:
TANH (n)
Description:
Returns the hyperbolic tangent of a number n.
Example:
SELECT TANH (1.0) "tanh" FROM DUMMY;
Retrieves:
tanh
0.7615941559557649
49
String Functions
ASCII Function
Syntax:
ASCII(c)
Description:
Returns the integer ASCII value of the first byte in a string c.
Example:
SELECT ASCII('Ant') "ascii" FROM DUMMY;
Retrieves:
ascii
65
CHAR Function
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;
Retrieves:
character
Ant
CONCAT Function
Syntax:
CONCAT (str1, str2)
Description:
Returns a combined string which consists of str1 followed by str2. The concatenation operator (||)
is identical to this function.
Example:
SELECT CONCAT ('C', 'at') "concat" FROM DUMMY;
Retrieves:
concat
Cat
LEFT Function
Syntax:
LEFT (str, n)
Description:
Returns n characters from the beginning of a string str.
Example:
SELECT LEFT ('Hello', 3) "left" FROM DUMMY;
Retrieves:
left
50
LCASE Function
Syntax:
LCASE(s)
Description:
Converts all characters in a string s to lowercase. The LCASE function is identical to the LOWER
function.
Example:
SELECT LCASE ('Test') "lcase FROM DUMMY;
Retrieves:
lcase
test
LENGTH Function
Syntax:
LENGTH(s)
Description:
Returns the number of characters in the specified string.s. For LOB types, it returns the length in
bytes.
Example:
SELECT LENGTH ('length in char') "length" FROM DUMMY;
Retrieves:
length
14
LOCATE Function
Syntax:
LOCATE (haystack, needle)
Description:
Returns the position of sub-string needle within string haystack. Returns 0 if needle is not found
from haystack.
Example:
SELECT LOCATE ('length in char', char) "locate" FROM DUMMY;
Retrieves:
Locate
11
LOWER Function
Syntax
LOWER(s)
Description
Converts all characters in a string s to lowercase. The LOWER function is identical to the LCASE
function.
51
lower
ant
LPAD Function
Syntax:
LPAD (target, n [, pattern])
Description:
Pad the left side of a target string with spaces or pattern to make the target n characters in length..
Example:
SELECT LPAD ('end', 15, '12345') "lpad" FROM DUMMY;
Retrieves:
lpad
123451234512end
LTRIM Function
Syntax:
LTRIM (target [, remove_set])
Description:
Removes from the leftmost of target all of the characters that appear in remove_set until reaching a
character not in remove_set and then returns the result. If remove_set is not specified, a single
blank space is used. Please note that remove_set is treated as a set of characters and not a search string.
Example:
SELECT LTRIM ('babababAabend','ab') "ltrim" FROM DUMMY;
Retrieves:
ltrim
Aabend
NCHAR Function
Syntax:
NCHAR (n)
Description:
This function returns the Unicode character with the specified integer code number n.
Example:
SELECT NCHAR (65) "nchar" FROM DUMMY;
Retrieves:
nchar
A
REPLACE Function
Syntax:
REPLACE (original_string, search_string, replace_string)
Description:
52
If original_string is an empty string, then the result will also be an empty string.
If two overlapping substrings match the search_string in the original_string, then only the first
occurrence will be replaced with the replace_string.
If original_string does not contain any occurrence of search_string, then the function returns
the original_string unchanged. If original_string, search_string, or replace_string is NULL, then
the function returns NULL.
Example:
SELECT REPLACE ('DOWNGRADE DOWNWARD','DOWN', 'UP') "replace" FROM DUMMY;
Retrieves:
replace
UPGRADE UPWARD
RIGHT Function
Syntax:
RIGHT(target, n)
Description:
Returns the rightmost n characters of a string target.
Example:
SELECT RIGHT('HI0123456789', 3) "right" FROM DUMMY;
Retrieves:
right
789
RPAD Function
Syntax:
RPAD (target, n [, pattern])
Description:
Pad the right side of a target string with spaces or pattern to make the target n characters in length.
Example:
SELECT RPAD ('end', 15, '12345') "right padded" FROM DUMMY;
Retrieves:
right padded
end123451234512
RTRIM Function
Syntax:
RTRIM (target [,remove_set ])
Description:
Removes from the rightmost of target all of the characters that appear in remove_set until reaching
a character not in remove_set and then returns the result. If remove_set is not specified, a single
blank space is used. Please note that remove_set is treated as a set of characters and not a search string.
Example:
SELECT RTRIM ('endabAabbabab','ab') "rtrim" FROM DUMMY;
Retrieves:
rtrim
53
SUBSTRING Function
Syntax:
SUBSTRING (target, start_position [, string_length])
Description:
Returns a substring of a string target starting from the start_position of the string. SUBSTRING
can either return the remaining part of a string from the start_position or, optionally, a number of
characters set by the string_length parameter.
Example:
SELECT SUBSTRING ('1234567890',4,2) "substring" FROM DUMMY;
Retrieves:
substring
45
SUBSTR_AFTER Function
Syntax:
SUBSTR_AFTER (target, pattern)
Description:
Returns a substring of the target string that follows the first occurrence of the pattern argument in
the target string.
If target does not contain a substring which is the same as pattern, then an empty string is
returned.
If pattern is an empty string, then target is returned.
If target or pattern is NULL, then NULL is returned.
Example:
SELECT SUBSTR_AFTER ('Hello My Friend','My ') "substr after" FROM DUMMY;
Retrieves:
substr after
Friend
SUBSTR_BEFORE Function
Syntax:
SUBSTR_BEFORE (target, pattern)
Description:
Returns a substring of the target string before the first occurrence of the pattern argument in the
target string.
If target does not contain a substring which is the same as pattern, then an empty string is
returned.
substr before
Hello
54
If no option is specified, it removes both the leading and trailing substring trim_char from
target_string string.
trim both
123456789
SELECT TRIM (LEADING a FROM aaa123456789aa) "trim leading" FROM DUMMY;
Retrieves:
trim leading
123456789aa
UCASE Function
Syntax:
UCASE (target)
Description:
Converts all characters in the target string to uppercase.
Example:
SELECT UCASE ('Ant') "ucase" FROM DUMMY;
Retrieves:
ucase
ANT
UNICODE Function
Syntax :
UNICODE(c)
Description:
Returns an integer containing the Unicode code point of the first character in the string, or NULL if
the first character is not a valid encoding.
Example:
SELECT UNICODE ('#') "unicode" FROM DUMMY;
Retrieves:
unicode
54620
UPPER Function
Syntax:
UPPER (target)
55
Description:
Converts all characters in the target string to uppercase.
Example:
SELECT UPPER ('Ant') "uppercase" FROM DUMMY;
Retrieves:
uppercase
ANT
56
Miscellaneous Functions
BINTOHEX Function
Syntax:
BINTOHEX (expression)
Description:
Returns the hexidecimal string of expression.
Example:
SELECT BINTOHEX('AB') "bintohex" FROM DUMMY;
Retrieves:
bintohex
4142
COALESCE Function
Syntax :
COALESCE (expression_list)
Description:
Returns the first non-NULL expression from a list. At least two expressions must be passed into
the function, and all expressions must be comparable. The result will be NULL if all the arguments
are NULL.
Example:
SELECT * FROM tab;
Retrieves:
ID
1
2
3
A
100.0
NULL
NULL
B
80.0
63.0
NULL
ID
1
2
3
A
100.0
NULL
NULL
B
80.0
63.0
NULL
coalesce
100
69.3
50
HASANYPRIVILEGES Function
Syntax:
HASANYPRIVILEGES (<user_name>, <object_oid>, <schema_name>, <object_type> [,
<subobjecttype>])
Description:
Returns 1 in case the given user has any privilege on the specified object.
<object_type> is for example: TABLE, VIEW, PROCEDURE
Users having system privilege DATA ADMIN or CATALOG READ are allowed to use this function
with any user given as first parameter. Other users are only allowed to use their own user_name
as first parameter.
57
HAS_PRIV
1
HASSYSTEMPRIVILEGE Function
Syntax:
HASSYSTEMPRIVILEGE (<user_name>, <systemprivilege>)
Description:
Returns 1 if the given user has the specified systemprivilege.
<systemprivilege> is CATALOG READ for example
DATA ADMIN or CATALOG READ With DATA ADMIN or CATALOG READ privilege, users are
allowed to check for all users. Normal users are only allowed to check for themselves, if they do
have any privilege on that object.
Example:
SELECT HASSYSTEMPRIVILEGE (CURRENT_USER, 'INIFILE ADMIN') HAS_INI_ADMIN FROM
DUMMY;
Retrieves:
HAS_INI_ADMIN
0
HEXTOBIN Function
Syntax:
HEXTBIN (expression)
Description:
Returns the binary value of expression where expression is a hexadecimal value.
Example:
SELECT HEXTOBIN ('1a') "hextobin" FROM DUMMY;
Retrieves:
hextobin
1A
ISAUTHORIZED Function
Syntax:
ISAUTHORIZED (<user_name>, <SQL-privilege>, <schema_name>, <object_name>,
<object_type> [, <subobjecttype>])
Description:
Returns 1 if the given user has the specified SQL-privilege on the specified object.
<SQL-privilege> is SELECT or EXECUTE for example.
<object_type> is for example: TABLE, VIEW, PROCEDURE
Example:
SELECT ISAUTHORIZED (CURRENT_USER, SELECT, MY_SCHEMA, MY_TABLE, TABLE)
HAS_PRIV FROM DUMMY;
58
HAS_PRIV
1
IFNULL Function
Syntax:
IFNULL (expression1, expression2)
Description:
Returns expression1 if expression1 is not NULL and expression2 if expression1 is NULL.
Example:
SELECT IFNULL ('diff', 'same') "ifnull" FROM DUMMY;
Retrieves:
ifnull
diff
NULLIF Function
Syntax:
NULLIF (expression1, expression2)
Description:
NULLIF compares the values of the two expressions. If the first expression equals the second
expression, NULLIF returns NULL.
If the first expression does not equal the second expression, or if the second expression is NULL,
NULLIF returns the first expression.
The NULLIF function provides a short way to write some CASE expressions.
Example:
SELECT NULLIF ('diff', 'same') "nullif" FROM DUMMY;
Retrieves:
nullif
Diff
SELECT NULLIF('same', 'same') "nullif" FROM DUMMY;
Retrieves:
nullif
NULL
CURRENT_CONNECTION Function
Syntax:
CURRENT_CONNECTION
Description:
Returns the current connection id.
Example:
SELECT CURRENT_CONNECTION "current connection" FROM DUMMY;
Retrieves:
current connection
2
59
current schema
SYSTEM
CURRENT_USER Function
Syntax:
CURRENT_USER
Description:
Returns the current user name in the string.
Example:
SELECT CURRENT_USER "current user" FROM DUMMY;
Retrieves:
current user
SYSTEM
GROUPING_ID Function
Syntax:
GROUPING_ID(column_name_list)
Description:
GROUPING_ID function can be used with GROUPING SETS to return multiple levels of aggregations
in a single result set. GROUPING_ID returns an integer value to identify which grouping set each
row belongs to. Each column in GROUPING_ID must be an element of the GROUPING SETS.
GROUPING_ID is assigned by converting the bit vector generated from GROUPING SETS to a
decimal number by treating the bit vector as a binary number. When a bit vector is composed, 0 is
assigned to each column specified in the GROUPING SETS and 1 otherwise in the order it appears
in the GROUPING SETS. By treating the bit vector as a binary number, this function returns an
integer value as the output.
Example:
SELECT customer, year, product, SUM(sales),
GROUPING_ID(customer, year, product)
FROM guided_navi_tab
GROUP BY GROUPING SETS (
(customer, year, product),
(customer, year),
(customer, product),
(year, product),
(customer),
(year),
(product));
60
CUSTOMER YEAR
PRODUCT SUM(SALES)
GROUPING_ID(CUSTOMER,YEAR,PRODUCT)
C1
2009 P1
100
C1
2010 P1
50
C2
2009 P1
200
C2
2010 P1
100
C1
2009 P2
200
C1
2010 P2
150
C2
2009 P2
300
C2
2010 P2
150
C1
2009 ?
300
10
C1
2010 ?
200
11
C2
2009 ?
500
12
C2
2010 ?
250
13
C1
P1
150
14
C2
P1
300
15
C1
P2
350
16
C2
P2
450
17
2009 P1
300
18
2010 P1
150
19
2009 P2
500
20
2010 P2
300
21
C1
500
22
C2
750
23
2009 ?
800
24
2010 ?
450
25
P1
450
26
P2
800
SESSION_CONTEXT Function
Syntax:
SESSION_CONTEXT(session_parameter)
Description:
Returns the value of session_parameter assigned to the current user or the value of a personal
setting. The parameter can be set when the session is created. Currently available read only
session variables are locale, locale_sap, client, conn_id, applicationname, clientuser,
clienthostname.
Example:
SELECT SESSION_CONTEXT(conn_Id) session context FROM DUMMY;
Retrieves:
session context
4
61
SYSUUID
4DE3CD576C79511BE10000000A3C2220
62
SQL Statements
This chapter describes the SQL statements that are supported by the SAP HANA Database.
63
64
65
Files
ALERT
<service>alert...trc
CLIENT
localclient_....trc
CRASHDUMP
*.crashdump....trc
INDEXSERVER,NAMESERVER,...,DAEMON
REMOVE TRACES deletes the trace files on specified hosts. When a service has a trace file
open, then it cannot be deleted, so CLEAR command should be used in that case.
The trace files can be monitored using M_TRACEFILES and trace file contents can be
monitored using M_TRACEFILE_CONTENTS.
DELETE ALL HANDLED EVENTS
Delete all events with status HANDLED.
DELETE HANDLED EVENT
Delete the event with given ID.
<host_port> ::= (<host_name>:<port_number>) | (<host_name>, <port_number>)
<host_name> ::= <string_literal>
<port_number> ::= Port Number
<event_id> ::= event ID number
DISCONNECT SESSION
Disconnects the specified session from the database. The specified session will be
disconnected but the current operation will be continued until it is completed.
LOGGING <on_off>
Logging is enabled or disabled.
<on_off>::= ON | OFF
RECLAIM DATA VOLUME
Reduces data volume size to a N% of payload size; it works like defragmenting a hard disk,
pages scattered around the data volume will be moved to the front of the data volume and
the free space at the end of the data volume will be truncated.
<host_port>::= host:port
<payload_size>::= % of payload size (should be > 110%)
<opt_shrink_mode>::= either defragment or sparsify, default value is defragment
RECLAIM LOG
Reclaim disk space of unused log segments.
<log_part>::= Log part number
66
Host
port
n.a.
not empty
not 0
not empty
not empty
not empty
empty
empty
empty
67
Host
port
n.a.
not empty
not 0
not empty
not empty
not empty
empty
empty
empty
68
69
70
71
72
Move a table
T1 WITH PARAMETERS('CONCAT_ATTRIBUTE'=('A$B','A','B'));
73
74
Example:
ALTER USER my_user PASSWORD myUserPass1;
75
Example:
CONNECT my_user PASSWORD myUserPass1;
76
77
78
79
80
81
82
83
Example 2:
If the sequence s is used to create a unique key on column A in the table R, then after a database
is restarted, a UNIQUE key value can be created by automatically assigning the maximum value of
column A to the sequence value using a RESET BY statement as follows:
CREATE SEQUENCE s RESET BY SELECT IFNULL(MAX(a), 0) + 1 FROM r;
84
85
86
ROW, COLUMN
If the majority of access is through a large number of tuples but with only a few selected
attributes, COLUMN-based storage should be used. If the majority of access involves
selecting a few records with all attributes selected, ROW-based storage is preferable. The
SAP HANA Database uses a combination to enable storage and interpretation in both forms.
You can define the type of organization for each table. The default value is ROW.
HISTORY COLUMN
Creates a table with a particular transaction session type called HISTORY. Tables with
session type HISTORY support time travel; the execution of queries against historic states
of the database is possible.
Timetravel can be done in the following ways.
Session-level timetravel:
SET HISTORY SESSION TO UTCTIMESTAMP =<timestamp yyyy:mm:dd hh:mm:ss>
SET HISTORY SESSION TO COMMIT ID =<commitid>
A database session (=database connection) can be set back to a certain point-in-time. The
COMMIT ID variant of the statement takes a commitid as a parameter. The value of the
commitid parameter must occur in COMMIT_ID column of the system table
SYS.TRANSACTION_HISTORY, otherwise an exception will be thrown. The COMMIT ID is
useful when using user defined snapshots. A user defined snapshot can be taken by simply
storing the commitid which is assigned to a transaction during the commit phase. The
commitid can be retrieved by executing the following query directly after a transaction
commit:
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 systemtable SYS.TRANSACTION_HISTORY where the commit_time is close to the given
timestamp (to be more precisely: choose pair where maximal COMMIT_TIME is smaller or
equal to the given timestamp; if no such pair is found an exception will be raised). The
session then will be restored with the determined commit-id as in the COMMIT ID variant.
To terminate a restored session to switch back to the current session, an explicit
COMMIT or ROLLBACK has to be executed on the DB connection.
Statement-level timetravel:
<subquery> AS OF UTCTIMESTAMP <timestamp yyyy:mm:dd hh:mm:ss>
<subquery> AS OF COMMIT ID <commitid>
87
GLOBAL TEMPORARY
Table definition is globally available while data is visible only to the current session. The
table is truncated at the end of the session.
Metadata in a global temporary table is persistent meaning the metadata exists until the
table is dropped and the metadata is shared across sessions. Data in a global temporary
table is session-specific meaning only the owner session of the global temporary table is
allowed to insert/read/truncate the data, exists for the duration of the session and data
from the global temporary table is automatically dropped when the session is terminated.
Global temporary table can be dropped only when the table does not have any record in it.
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
LOCAL TEMPORARY
The table definition and data is visible only to the current session. The table is truncated at
the end of the session.
Metadata exists for the duration of the session and is session-specific meaning only the
owner session of the local temporary table is allowed to see. Data in a local temporary
table is session-specific meaning only the owner session of the local temporary table is
allowed to insert/read/truncate the data, exists for the duration of the session and data
from the local temporary table is automatically dropped when the session is terminated.
Supported operations on Global 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_contents_source>:
88
89
90
91
It is possible to determine the index servers on which the partitions are created. If you
specify the LOCATION, the partitions will be created on these instances using round robin.
Duplicates in the list will be removed. If you specify exactly the same number of instances
as partitions in the partition specification, then each partition will be assigned to the
respective instance in the list. All index servers in the list have to belong to the same
instance.
If no locations are specified, the partitions will be created randomly. If the number of
partitions matches the number of servers for example by using GET_NUM_SERVERS()
it is ensured that multiple CREATE TABLE calls distribute the partitions in the same way. In
case of a multi-level partitioning, this applies for the number of partitions of the first level.
This mechanism is useful if several tables are to be created which have a semantic relation
to each other.
<location_clause> ::= AT [LOCATION] <host:port> | ( <host:port>, )
AT LOCATION
A column store table can be created in the specified location with host:port. Location list
can be specified when creating partitioned tables that are distributed on multiple instances.
When location list is provided without partition_clause, the table is created on the first
location specified.
If location information is not provided, the table will be automatically assigned to one node.
This option can be used for both row store and column store tables in a distributed
environment.
<parameter_key_value_list>::= <parameter_key_value>,
<parameter_key_value>::=
<string_literal> = <string_literal> |
<identifier> = <string_literal> |
<string_literal> = (<string_literal>, ... )
Options that can be used only for column store tables can be passed in using "WITH PARAMETERS"
clause. Parameter keys and string values can be any string literal. Duplicate keys are allowed.
Keys are automatically mapped into their upper-case form.
parameter_key_value
'TREX_FLAGS' = ('column_name','flags'),
Flags are the implementation flags, integer value is currently between 0 and 67108864.
Description:
The CREATE TABLE statement creates a table. Tables are created without data except when
as_table_subquery or like_table_clause is used with the WITH DATA option.
Example:
CREATE TABLE A (A INT PRIMARY KEY, B INT);
92
93
94
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:
CREATE VIEW v_name AS SELECT * FROM a;
95
Example:
DELETE FROM table_a WHERE a = 1;
96
97
98
99
100
101
102
103
104
105
106
Example:
DROP USER my_user;
107
108
OPERATOR_NAME
OPERATOR_DETAILS
Description
The string specified as STATEMENT_NAME on executing the EXPLAIN PLAN command.
This is used to distinguish plans from each other when there are multiple plans in the
EXPLAIN_PLAN_TABLE view.
Name of an operator. Details are described in the following section.
SCHEMA_NAME
Details of an operator. Predicates and expressions used by the operator are shown
here.
Name of the schema of the accessed table.
TABLE_NAME
TABLE_TYPE
Type of the accessed table. One of the following options: COLUMN TABLE, ROW
TABLE, MONITORING VIEW, JOIN VIEW, OLAP VIEW, CALCULATION VIEW and
HIERARCHY VIEW.
TABLE_SIZE
OUTPUT_SIZE
109
Description
SUBTREE_COST
Estimated cost of executing the subtree starting from an operator. This value is only
for relative comparison.
OPERATOR_ID
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 using OPERATOR_ID and
PARENT_OPERATOR_ID. PARENT_OPERATOR_ID of the root operator is shown as
NULL.
Level from the root operator. Level of the root operator is 1, level of a child of the
root operator is 2 and so on. This can be utilized for output indentation.
LEVEL
POSITION
Position in the parent operator. Position of the first child is 1, position of the second
child is 2 and so on.
HOST
PORT
TIMESTAMP
Date and time when the EXPLAIN PLAN command was executed.
CONNECTION_ID
EXECUTION_ENGINE
Description
LIMIT
ORDER BY
HAVING
GROUP BY
DISTINCT
FILTER
JOIN
COLUMN TABLE
MULTIPROVIDER
Operator for producing union-all of multiple results having the same grouping and
aggregation
Table 21. List of row engine operators shown in the OPERATOR_NAME column.
Operator Name
Description
ROW SEARCH
LIMIT
ORDER BY
HAVING
GROUP BY
MERGE AGGREGATION
Operator for merging the results of multiple parallel grouping and aggregations
DISTINCT
FILTER
110
Description
Operator for producing union-all of input relations
MATERIALIZED UNION ALL Operator for producing union-all of input relations with intermediate result
materialization
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.
Operator for joining input relations through CPB-tree index searches. Join type
suffix can be added.
HASH JOIN
Operator for joining input relations through probing hash table built on the fly. Join
type suffix can be added.
Operator for joining input relations through nested looping. Join type suffix can be
added.
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.
Table access through B-tree index search
TABLE SCAN
AGGR TABLE
MONITOR SEARCH
MONITOR SCAN
COLUMN SEARCH is a mark for the starting position of column engine operators and ROW SEARCH
is a mark for the starting position of row engine operators.
In the example below, the intermediate result produced by a COLUMN SEARCH (ID 10) is
consumed by a ROW SEARCH (ID 7), and the intermediate result produced by the ROW SEARCH
(ID 7) is consumed by another COLUMN SEARCH (ID 1).
The operators below the lowest COLUMN SEARCH (ID 10) explain how the COLUMN SEARCH (ID
10) is executed. The operators between the ROW SEARCH (ID 7) and the COLUMN SEARCH (ID 10)
explain how the ROW SEARCH (ID 7) processes the intermediate result produced by the COLUMN
SEARCH (ID 10). The operators between the top COLUMN SEARCH (ID 1) and the ROW SEARCH
(ID 7) explain how the top COLUMN SEARCH (ID 1) processes the intermediate result produced by
the ROW SEARCH (ID 7).
Table 22. Operators
OPERATOR_NAME
COLUMN SEARCH
LIMIT
ORDER BY
GROUP BY
JOIN
COLUMN TABLE
ROW SEARCH
BTREE INDEX JOIN
BTREE INDEX JOIN
COLUMN SEARCH
FILTER
OPERATOR_ID
PARENT_OPERATOR_ID
LEVEL
POSITION
NULL
10
11
10
10
111
OPERATOR_ID
PARENT_OPERATOR_ID
12
LEVEL
11
POSITION
11
OPERATOR_NAME
ROW SEARCH
OPERATOR_DETAILS
CUSTOMER.C_CUSTKEY, CUSTOMER.C_NAME,
SUM(LINEITEM.L_EXTENDEDPRICE * (1 - LINEITEM.L_DISCOUNT)),
CUSTOMER.C_ACCTBAL, NATION.N_NAME, CUSTOMER.C_ADDRESS,
CUSTOMER.C_PHONE, CUSTOMER.C_COMMENT
LIMIT
ORDER BY
MERGE AGGREGATION
GROUP BY
CPBTREE INDEX JOIN
NUM RECORDS: 20
SUM(LINEITEM.L_EXTENDEDPRICE * (1 - LINEITEM.L_DISCOUNT))
DESC
NUM PARTITIONS: 4
GROUPING: NATION.N_NAME, R_CUSTOMER.C_CUSTKEY, AGGREGATION:
SUM(LINEITEM.L_EXTENDEDPRICE * (1 - LINEITEM.L_DISCOUNT))
INDEX NAME: _SYS_TREE_RS_279_#0_#P0,
INDEX CONDITION: ORDERS.O_ORDERKEY = LINEITEM.L_ORDERKEY,
INDEX FILTER: 'R' = LINEITEM.L_RETURNFLAG
TABLE_NAM
E
None
None
None
None
LINEITEM
112
OPERATOR_DETAILS
INDEX NAME: _SYS_TREE_RS_285_#0_#P0,
INDEX CONDITION: CUSTOMER.C_NATIONKEY = NATION.N_NATIONKEY
TABLE_NAM
E
NATION
CUSTOMER
ORDERS
113
114
115
Description
they can be granted to users and roles.
Used to restrict the access to and the use of packages in
the repository of the SAP HANA database.
Packages contain design-time versions of various objects,
such as Analytic, Attribute, and Calculation Views, Analytic
Privileges, and functions. To be able to work with
packages, the respective Package Privileges must be
granted.
SQL Privileges
In the SAP HANA database, a number of privileges are available to control the authorization of SQL
commands. Following the principle of least privilege, users should be given only the smallest set of
privileges they require for their role. Thus, this chapter gives a complete overview of the privileges
supported at the SQL level, so that they can be assigned appropriately to the respective database
users.
The SQL Privileges can be divided as follows:
System Privileges
These are system-wide privileges that control some general system activities mainly for
administrative purposes, such as creating schema, creating and changing users and roles.
Object Privileges
These privileges are bound to an object, for example, to a table, and control activities that are
possible on this particular object, such as SELECT, UPDATE, or DELETE on database tables.
The following sections describe all supported privileges in these two groups, together with the list
of SQL commands they authorize.
System Privileges
Users and Roles
USER ADMIN
This privilege authorizes the creation and changing of users using the CREATE USER, ALTER USER,
and DROP USER SQL commands.
ROLE ADMIN
This privilege authorizes the creation and deletion of roles using the CREATE ROLE and DROP ROLE
SQL commands. It also authorizes the granting and revocation of roles using the GRANT and
REVOKE SQL commands.
Catalog and Schema Management
CREATE SCHEMA
This privilege authorizes the creation of database schemas using the CREATE SCHEMA SQL
command.
DATA ADMIN
This powerful privilege authorizes to read all data in the system and monitoring views as well as
execute all DDL (Data Definition Language) and only DDL commands in the SAP HANA
database.
CATALOG READ
This privilege authorizes all users to have unfiltered read-only access to all system and monitoring
views. Normally, the content of those views is filtered based on the privileges of the accessing user.
The CATALOG READ privilege enables users to have read-only access to the full content of all
system and monitoring views.
Analytics
116
117
Table
View
Sequence
Synonym
OK
-
OK
OK
Function/
Procedure
-
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
-
OK
OK
OK
OK
OK
-
OK
OK
-
?
?
?
?
?
?
?
?
OK
OK
OK
CREATE ANY
This privilege allows the creation of all kinds of objects, in particular, tables, views, sequences,
synonyms, SQL Script functions, or database procedures in a schema. This privilege can only be
granted on a schema.
ALL PRIVILEGES
This is a collection of all DDL and DML (Data Manipulation Language) privileges that on the one
hand, the grantor currently has and is allowed to grant further and on the other hand, can be
granted on this particular object. This collection is dynamically evaluated for the given grantor and
object. ALL PRIVILEGES is not applicable to a schema, but only a table, view, or table type.
DROP and ALTER are DDL privileges and authorize the DROP and ALTER SQL commands. While the
DROP privilege is valid for all kinds of objects, the ALTER privilege is not valid for sequences and
synonyms as their definitions cannot be changed after creation.
118
INDEX
This special DDL privilege authorizes the creation, changing, or dropping of indexes for an object
using the CREATE INDEX, DROP INDEX, and ALTER INDEX commands. This privilege can only be
applied to a schema, table, and table type.
SELECT, INSERT, UPDATE, and DELETE
These are DML privileges and authorize respective SQL commands. While SELECT is valid for all
kinds of objects, except for functions and procedures, INSERT, UPDATE, and DELETE are valid for
schemas, tables, table types, and updatable views only.
EXECUTE
This special DML privilege authorizes the execution of an SQL Script function or a database
procedure using the CALLS or CALL command, respectively.
All DDL and DML privileges are valid for schemas in the sense that they authorize applicable
activities on the objects created in this schema.
Synonyms can be created for tables, views, sequences, database procedures, but not for schemas
and SQL Script functions. The privileges that can be granted and revoked on a synonym are
determined by the actual object the synonym stands for.
119
120
[] means optional.
field specs: a comma separated list of column specifications. When not specified, the
whole fields are assumed.
eor: end of row. When not specified, the new-line character is used.
eoc: end of column. When not specified, the comma character is used.
moq: mark of quotation. When not specified, the double-quotation mark is used.
[IMPORT DATA]
INTO TABLE <tablename> [(<field specs>)]
FROM <os_data_filename> [RECORD DELIMITED BY '<eor>'] [FIELDS [DELIMITED BY
'<eoc>'] [OPTIONALLY ENCLOSED BY '<moq>']]
[ERROR LOG <os_bad_filename>]
Upon an error, either a parsing error or a SQL error, the erroneous rows are written to the error
log file. In the case of a parsing error, the error position is marked with the carrot character.
The following is how a column is parsed from CSV files.
//
// Note on the Current Implementation
//
// Common
//
- The null value cannot be enclosed.
//
- Leading whilte spaces are not ignored.
//
- Most of the limitations are tradeoff for the performance.
121
The sample control file below shows how to give column specifications, which are a commaseparated list of name-type pairs. The "reposrc.csv" file should have two columns per line. The
first column in the file is stored into the PROGNAME field of the REPOSRC table and the second
column in the file is stored into the DATA field of the table.
IMPORT DATA
INTO TABLE "SYSTEM"."TEST"
FROM 'data_file_name.csv'
RECORD DELIMITED BY '\n'
FIELD DELIMITED BY ','
OPTIONALLY ENCLOSED BY '"'
ERROR LOG 'error_file_name.err'
Example:
IMPORT FROM home/myself/reposrc.ctl WITH THREADS 10 BATCH 50000;
122
123
Description:
The LOAD statement loads the column store table data to memory.
DELTA - DELTA part of the column store table is loaded into memory. Since the column store is
read optimized and compressed, deltas are introduced to optimize insert or updates. All insertions
are passed to a delta.
ALL ALL data of the column store table in main and delta is loaded into memory.
column_name, Columns specified in the column list are loaded into memory.
Example:
LOAD a_table all;
124
Description
The MERGE DELTA statement merges deltas to main column store table. Since the column store is
read optimized and compressed, deltas are introduced to optimize insert or updates in the
optimized way. All insertions are passed to a delta. At a certain point in time, deltas can be
merged into the main column table. Deltas will be merged into main column table.
HISTORY Can be specified to merge history deltas into the history main on column store history
tables.
PART Can be specified to merge a delta of a partition to main column table.
Example:
MERGE DELTA OF A;
MERGE DELTA OF A PART 1;
MERGE HISTORY DELTA OF A;
MERGE HISTORY DELTA OF A PART 1;
125
126
127
128
129
130
Description:
<select_clause> ::= SELECT [TOP n] [ ALL | DISTINCT ] <select_list>
<select_list> ::= { <select_item>, }
<select_item> ::=
[ [<schema_name>.] <table_name>.] <asterisk>
| <expression> [ AS ] <column_alias>
<asterisk> ::= *
131
132
133
134
Return Format
135
column table t1 (
varchar(5), sales
into t1 values(1,
into t1 values(2,
into t1 values(3,
into t1 values(4,
into t1 values(5,
into t1 values(6,
into t1 values(7,
into t1 values(8,
The following GROUPING SETS query is equivalent to the second below group-by query. Note that
two groups inside grouping sets in the first query are specified at each group by in the second
query.
select customer, year, product, sum(sales)
from t1
group by GROUPING SETS
(
(customer, year),
(customer, product)
);
select customer, year,
from t1
group by customer,
union all
select customer, NULL,
from t1
group by customer,
NULL, sum(sales)
year
product, sum(sales)
product;
ROLLUP and CUBE are concise representations of grouping sets that are used frequently. The
following ROLLUP query is equivalent to the second below grouping-set query.
136
137
138
139
140
141
NOW Session will restore the snapshot to the current time from the history search.
COMMIT ID Session will restore the snapshot corresponding to the specified commit ID
(COMMIT ID).
UTCTIMESTAMP Session will restore the snapshot of the specified timestamp.
The COMMIT ID-variant of the statement takes a commit-id as parameter. The value of the
commit-id parameter must occur inside the COMMIT_ID column of the system-table
SYS.TRANSACTION_HISTORY, otherwise an exception will be thrown.
The COMMIT ID-variant is mainly useful when using user defined snapshots. A user defined
snapshot can be taken by simply storing the commit-id which is assigned to a transaction during
the commit-phase (of course this does only make sense when history tables are updated by the
transaction).
The commit-id may be retrieved by executing the following query directly after a transaction
commit:
SELECT LAST_COMMIT_ID
FROM M_HISTORY_INDEX_LAST_COMMIT_ID
WHERE SESSION_ID = CURRENT_CONNECTION
The UTCTIMESTAMP-variant of the statement takes a timestamp as parameter. Internally, the
timestamp is used to look up a (commit_time,commit_id)-pair inside the system-table
SYS.TRANSACTION_HISTORY where the commit_time is close to the given timestamp. To be more
precisely: choose pair where maximal COMMIT_TIME is smaller or equal to the given timestamp; if
no such pair is found an exception will be raised. The session then will be restored with the
determined commit-id as in the COMMIT ID-variant.
NOTE:
Execution of data manipulation statements and data definition statements are not allowed
inside restored sessions. Only select statements are allowed.
Besides SET HISTORY SESSION TO NOW, a history session can als obe terminated by an
explicit COMMIT or ROLLBACK on the DB connection.
142
143
Normal row and column table: DDLs except for truncate and table conversion can be
rollbacked, and rollbacks on DMLs are supported.
Global temporary table: DDLs can be rollbacked, but rollbacks on DMLs are not supported.
Local temporary table: rollbacks on DDLs and DMLs are not supported.
No logging column table: DDLs are not supported when ddl autocommit is off, whereas
rollbacks on DMLs are supported.
144
145
146
Description:
Deletes all rows from a table. TRUNCATE is faster than DELETE FROM when deleting all records
from a table, but TRUNCATE cannot be rollbacked. To rollback from deleting records, DELETE
FROM <table_name> should be used.
HISTORY tables can also be truncated just like normal tables by executing this command. All parts
of the history table (main, delta, history main and history delta) will be deleted and the content
will be lost.
147
148
Description:
You can unset session variables by providing key. With this command, session variables of the
current session can be unset. If you have session administration privileges, you can change
session variables of other sessions by specifying the session ID using ALTER SYSTEM ALTER
SESSION [session_id] UNSET command.
There are several available read-only session variables and they are LOCALE, LOCALE_SAP,
CLIENT, CONN_ID, APPLICATIONNAME, CLIENTUSER, CLIENTHOSTNAME.
Session variables can be retrieved using SESSION_CONTEXT() function.
Example:
SET my_var = dummy;
SELECT session_context(my_var) FROM dummy;
Unset my_var;
149
150
151
Appendix
Restrictions for SQL Statements
Database
Maximum number of locks
8192
Limited by storage size RS: 1TB
Schemas
Maximum number of tables in a schema
Length of an identifier
Length of an alias name
Maximum length of a constant string literal
maximum number of hex characters in a binary
literal
131072
127 characters
128 characters
32767 bytes
8192
1000
1000
1000
Limited by storage size RS: 1TB/sizeof(row),
1023
16
16
16
16384
constraint
SQL
Maximum length of an SQL statement
Maximum depth of SQL view nesting
Maximum depth of SQL parse tree
Maximum number of joined tables in an SQL
statement or view
Maximum number of columns in an ORDER BY,
GROUP BY or SELECT clause
SQLScript
Maximum size of all stored procedures
2GB
128
255
255
65536
152
Description
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
general warning
general error
fatal error
cannot allocate enough memory
initialization error
invalid data
feature not supported
invalid argument
index out of bounds
invalid username or password
invalid state
cannot open file
cannot create/write file
cannot allocate enough disk space
cannot find file
statement retry
metadata schema version incompatible between database and executable file
service shutting down
invalid license
transaction error
transaction rolled back by an internal error
transaction rolled back by integrity constraint violation
transaction rolled back by lock wait timeout
transaction rolled back due to unavailable resource
transaction rolled back by detected deadlock
failure in accessing checkpoint file
failure in accessing anchor file
failure in accessing log file
failure in accessing archive file
transaction serialization failure
current operation cancelled by request and transaction rolled back
invalid write-transaction identifier
failure in accessing invisible log file
exceed max num of concurrent transactions
transaction serialization failure until timeout expires
transaction rollback, unique constraint violated
transaction distribution work failure
resource busy and acquire with NOWAIT specified
inconsistency between data and log
transaction start is blocked until Master_Restart finishes
distributed transaction commit failure
statement cancelled due to old snapshot
153
154
155
156
157
this syntax has been deprecated and will be removed in next release
null value found
invalid object ID
invalid expression
could not set system license
only commands for license handling are allowed in current state
invalid user parameter value
composite error
table type conversion error
this feature has been deprecated and will be removed in next release
number of columns exceeds its maximum
invalid calculation scenario name
package manager error
replication error
cannot execute ddl statement on replication table while replicating
failure in accessing anchor file
failure in accessing log file
replication table has not conflict report table
conflict report table already enabled
conflict report table already disabled
api error
cursor type of forward is not allowed
invalid statement
exceed maximum batch size
Server rejected the connection(protocol version mismatch)
this function can be called only in the case of single statement
this query does not have result set
connection does not exist
no more lob data
operation is not permitted
invalid parameter is received from server
result set is currently invalid
next() is not called for this result set
too many parameters are set
some paramters are missing
internal error
not supported type conversion
remote-only function
no more result row in result set
Specified parameter is not output parameter
LOB streaming is not permitted in auto-commit mode
session context error
failed to execute the external statement
session layer is not initialized yet
158
159
161
162
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
SqlScript
distributed SQL error
expression shipping failure
operator shipping failure
invalid protocol or indexserver (statisticsserver) shutdown during distributed
query execution
sequence shipping failure
remote query exuectuion failure
Something went wrong ($errtxt$)
$number$, $errtxt$
No source defined which should be backed up
The file '$filename$' already exists and must not be overwritten
No destination defined for restore
Unable to read $readItem$ information from backup '$filename$'
Invalid value <$value$> for $readItem$
Expected tag <$expected$> but found <$readItem$>
Unexpected end of backup
163
165
166
167
3000067
3000068
3000070
3000071
3000072
3000073
3000074
3000075
3000076
3010001
3010002
3010004
3010005
3010006
3010008
3010009
3010013
3010014
3010015
3010016
3010017
3010018
3010019
3010020
3010021
3010022
3010023
3010024
3010025
3010026
3010027
3010028
3010029
3010030
3010031
3010032
3010033
3010034
3010035
3010036
3010037
3010038
174
175
Log replay start at position $pos$ requested, but data ends at position $epos$
Invalid part $pos$+$size$ of partial entry $id$, expected end $size$, computed
$csize$
Found duplicate start of partial log entry $id$ at $pos$
Partial entry $id$ continuation found at $pos$, but no beginning found
Invalid buffer header found at position $pos$ in segment $id$
Buffer size $size$ at position $pos$ in segment $id$ invalid, maximum
$rest$ expected
Buffer checksum at position $pos$ in segment $id$ invalid
Buffer at position $pos$ doesn't belong to segment $id$
Buffer $start$ with size $size$ at position $pos$ starts before current position
$cpos$ in segment $id$
Error in parallel worker thread prevents continuing recovery in this worker
Transaction for $sess$ already prepared for COMMIT or ROLLBACK
Invalid log partition index $idx$ found for local log segment $seg$
Invalid log segment replay sequence (trying to push $seg$, expected $exp$)
Invalid log segment replay sequence (trying to push unknown $seg$)
Invalid log partition index $idx$ found for backed up log segment $seg$
Inconsistent log segment information (already known $old$, newly-added $new$)
Segment $seg$ is already loading
Known log segments already set or a segment already pushed
All known log segments were already loaded for log partition when trying to load
$seg$
Invalid authorization mode change
Unknown authorization mode
Adding dependencies under objects that do not have any restrictions on DMLprivileges is not allowed.
Granting privilege on object that is not enabled for that kind of operation.
OUTDATED ERROR
Invalid principal id type found on current dependency.
Not authorized
Cycles in dependency graph not allowed
Change ownership can only be applied to root node of consists-of dependency
graph.
Consists-of dependencies can only be created between objects owned by the
same user.
Changing validity on objects that are either unrestricted or restricted but
impossible is not allowed.
Object found that is either unrestricted but has dependencies or that is
impossible to use with a certain privilege, but has dependencies for that privilege.
A handler is already registered for object type $type$
No handler registered for object type $type$
There can be only on type of dependencies under the same object
Dependency must be of valid type
Trying to insert a structured privilege twice
Trying to fetch a non-existing structured privilege
Trying to delete a non-existing dependency with DepObj=$depoid$
177
179
181