SAP HANA Database - SQL Reference Manual SAP HANA Appliance Software SPS 04 Target Audience Consultants Administrators SAP SAP Har dware Par tner tner Others
1
2 0 12 -0 8 -2 1
Copyright
© Copyright 2012 SAP AG. All rights reserved
SAP Library document classification: PUBLIC
No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP AG. The information contained herein may be c hanged hanged without prior notice. Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors. Microsoft, Windows, Excel, Outlook, PowerPoint, Silverlight, and Visual Studio are registered trademarks of Microsoft Corporation. IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x, System z, System z10, z10, z/VM, z/OS, OS/390, zEnterprise, PowerVM, Power Architecture, Power Systems, POWER7, POWER6+, POWER6, POWER, PowerHA, pureScale, PowerPC, BladeCenter, System Storage, Storw St orwize, ize, XIV, GPFS, HACMP, RETAIN, RETAIN, DB2 Connect, RACF, Redbooks, OS/2, AIX, Intelligent Miner, WebSphere, Tivoli, Informix, and Smarter Planet are trademarks or registered trademarks of IBM Corporation. Linux is the registered trademark of Linus Torv Torvalds alds in the United St ates and other ot her countries. Adobe, the Adobe logo, Acrobat, PostScript, and Reader are trademarks or registered trademarks of Adobe Systems Incorporated in the United States and other countries. Oracle and Java are registered trademarks of Oracle and its affiliates. UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group. Citrix, ICA, ICA, Program Program Neighborhood, Neighborhood, MetaFrame, W WinFrame, inFrame, VideoFrame, VideoFrame, and MultiWin are trademarks or registered trademarks of Citrix Systems Inc. HTML, XML, XHTML, and W3C are trademarks or registered trademarks of W3C®, World Wide Web Consortium, Massachusetts Institute of Technology. Apple, App Store, iBooks, iPad, iPhone, iPhoto, iPod, iTunes, Multi-Touch, Objective-C, Retina, Safari, Siri, and Xcode are trademarks or registered trademarks of Apple Inc. IOS is a registered trademark of Cisco Systems Inc. RIM, BlackBerry, BBM, BlackBerry Curve, BlackBerry Bold, BlackBerry Pearl, BlackBerry Torch, BlackBerry Storm, BlackBerry Storm2, BlackBerry PlayBook, and BlackBerry App World are trademarks or registered trademarks of Research
2
2 0 12 -0 8 -2 1
Copyright
© Copyright 2012 SAP AG. All rights reserved
SAP Library document classification: PUBLIC
No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP AG. The information contained herein may be c hanged hanged without prior notice. Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors. Microsoft, Windows, Excel, Outlook, PowerPoint, Silverlight, and Visual Studio are registered trademarks of Microsoft Corporation. IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x, System z, System z10, z10, z/VM, z/OS, OS/390, zEnterprise, PowerVM, Power Architecture, Power Systems, POWER7, POWER6+, POWER6, POWER, PowerHA, pureScale, PowerPC, BladeCenter, System Storage, Storw St orwize, ize, XIV, GPFS, HACMP, RETAIN, RETAIN, DB2 Connect, RACF, Redbooks, OS/2, AIX, Intelligent Miner, WebSphere, Tivoli, Informix, and Smarter Planet are trademarks or registered trademarks of IBM Corporation. Linux is the registered trademark of Linus Torv Torvalds alds in the United St ates and other ot her countries. Adobe, the Adobe logo, Acrobat, PostScript, and Reader are trademarks or registered trademarks of Adobe Systems Incorporated in the United States and other countries. Oracle and Java are registered trademarks of Oracle and its affiliates. UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group. Citrix, ICA, ICA, Program Program Neighborhood, Neighborhood, MetaFrame, W WinFrame, inFrame, VideoFrame, VideoFrame, and MultiWin are trademarks or registered trademarks of Citrix Systems Inc. HTML, XML, XHTML, and W3C are trademarks or registered trademarks of W3C®, World Wide Web Consortium, Massachusetts Institute of Technology. Apple, App Store, iBooks, iPad, iPhone, iPhoto, iPod, iTunes, Multi-Touch, Objective-C, Retina, Safari, Siri, and Xcode are trademarks or registered trademarks of Apple Inc. IOS is a registered trademark of Cisco Systems Inc. RIM, BlackBerry, BBM, BlackBerry Curve, BlackBerry Bold, BlackBerry Pearl, BlackBerry Torch, BlackBerry Storm, BlackBerry Storm2, BlackBerry PlayBook, and BlackBerry App World are trademarks or registered trademarks of Research
2
2 0 12 -0 8 -2 1
in Motion Limited. Google App Engine, Google Apps, Google Checkout, Checkout, Google Data Data AP I, Google Maps, Google Mobile Ads, Google Mobile Updater, Updater, Google Mobile, Google Store, Google Sync, Google Updater, Updater, Google Voice, Google Mail, Gmail, YouTube, 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 Computop is a registered trademark trademark of Computop Computop Wirts chaftsinformatik chaftsinformatik 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 products and services services mentioned herein herein as well as their respective logos logos are trademarks or registered trademarks of Business Objects Software Ltd. Business Objects Objects is an SAP company. company. Sybase and Adaptive Server, iAnywhere, Sybase 365, SQL Anywhere, and other Sybase products products and services services mentioned herein herein as well as t heir respective respective logos are trademarks or registered trademarks of Sybase Inc. Sybase is an SAP company. Cross Crossgate, gate, m@gic EDDY, B2B 360°, 360°, and B2B B 2B 360° Services Services are regist registered ered trademarks of Crossgate AG in Germany and other countries. Crossgate is an SAP company. All other ot her product product and service service names mentioned are the trademarks trademarks of their respective respective companies. Data contained in this document serv s erves es info i nformational rmational 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 warranties for SAP Group products products and services services are those that are set forth forth in the express warranty statements accompanying such products and services, if any. Nothing herein should be construed as constituting an additional warranty.
3
2 0 12 -0 8 -2 1
Table of Content
Table of Content Table of Content SAP HANA Database - SQL Reference Manual SQL Reference Manual Notation Introduction SQL Supported Languages and Code Pages Comment Identifiers Single Quotation Mark Double Quotation Mark SQL Reserved Words
Data Types Classification of Data Types Datetime Types Date 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 SQ L Data Type and Column Store Data Type Data Type Conversion Typed Constant
Predicates Comparison 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 Functions CAST TO_ALPHANUM TO_BIGINT TO_BINARY TO_BLOB TO_CHAR TO_CLOB TO_DATE TO_DATS
4
4 8 9 10 11 11 11 11 11 11 11 12
13 13 13 13 14 14 14 15
15 16 17 17 18 18 20
22 22 22 22 22 22 22 23
25 25 25 25 26 26 26 26
28 28 28 28 28
30 30 30 30 30 30 31 31 31 31 32 32
2012-08-21
Table of Content
TO_DECIMAL TO_DOUBLE TO_INT TO_INTEGER TO_NCHAR TO_NCLOB TO_NVARCHAR TO_REAL TO_SECONDDATE TO_SMALLDECIMAL TO_SMALLINT TO_TIME TO_TIMESTAMP TO_TINYINT TO_VARCHAR
32 33 33 33 33 34 34 34 34 35 35 35 35 36 36
DateTime Functions
36
ADD_DAYS ADD_MONTHS ADD_SECONDS ADD_YEARS CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP CURRENT_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 Functions ABS ACOS ASIN ATAN ATAN2 BINTOHEX BITAND CEIL COS COSH COT EXP FLOOR GREATEST HEXTOBIN LEAST LN LOG MOD POWER ROUND SIGN SIN SINH SQRT TAN TANH UMINUS
5
36 37 37 37 37 38 38 38 38 39 39 39 39 40 40 40 40 41 41 41 42 42 42 42 43 43 43 43 44 44 44
44 44 45 45 45 46 46 46 46 47 47 47 47 48 48 48 48 49 49 49 50 50 50 50 51 51 51 51 52
2012-08-21
Table of Content
String Functions
52
ASCII CHAR CONCAT LCASE LEFT LENGTH LOCATE LOWER LPAD LTRIM NCHAR REPLACE RIGHT RPAD RTRIM SUBSTR_AFTER SUBSTR_BEFORE SUBSTRING TRIM UCASE UNICODE UPPER
52 52 53 53 53 53 54 54 54 55 55 55 55 56 56 56 57 57 57 58 58 58
Miscellaneous Functions COALESCE CURRENT_CONNECTION CURRENT_SCHEMA CURRENT_USER GROUPING_ID IFNULL MAP NULLIF SESSION_CONTEXT SESSION_USER SYSUUID
SQL Statements Schema Definition and Manipulation Statements ALTER 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 SCHEMA DROP SEQUENCE DROP SYNONYM DROP TABLE DROP TRIGGER DROP VIEW RENAME COLUMN RENAME INDEX RENAME TABLE ALTER TABLE ALTER TYPE TRUNCATE TABLE
Data Manipulation Statements DELETE EXPLAIN PLAN INSERT LOAD MERGE DELTA REPLACE | UPSERT SELECT UNLOAD UPDATE
6
59 59 59 59 59 60 61 61 62 62 63 63
64 64 64 65 66 67 68 73 75 76 77 77 78 79 83 90 90 91 91 91 92 92 93 93 94 94 95 96 96 97
97 97 98 101 102 103 104 105 113 113
2012-08-21
Table of Content
System M anagement Statements SET SYSTEM LICENSE ALTER SYSTEM ALTER CONFIGURATION ALTER SYSTEM ALTER SESSION SET ALTER SYSTEM ALTER SESSION UNSET ALTER SYSTEM CANCEL [WORK IN] SESSION ALTER SYSTEM CLEAR SQL PLAN CACHE ALTER SYSTEM CLEAR TRACES ALTER SYSTEM DISCONNECT SESSION ALTER SYSTEM LOGGING 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 UNSET SYSTEM LICENSE ALL
Session Ma nagement Statements CONNECT SET HISTORY SESSION SET SCHEMA SET [SESSION] UNSET [SESSION]
Transaction Management Statements COMMIT LOCK TABLE ROLLBACK SET TRANSACTION
Access Control Statements ALTER SAML PROVIDER ALTER USER CREATE ROLE CREATE SAML PROVIDER CREATE USER DROP ROLE DROP SAML PROVIDER DROP USER GRANT REVOKE
Data Import Export Statements EXPORT IMPORT IMPORT FROM
Res trictions for SQL Statements See Also
SQL Error Code s
7
114 114 114 116 116 117 117 118 118 119 119 120 120 120 121 122 122 123 123 124 124 124
124 124 125 125 126 126
126 127 127 127 127
128 128 129 131 132 133 134 135 135 136 142
143 143 144 145
147 149
150
2012-08-21
SAP HANA Database - SQL Reference Manual
SAP HANA Database - SQL Reference Manual This guide describes SQL language supported by SAP HANA DB.
8
2012-08-21
SAP HANA Database - SQL Reference Manual
SQL Reference Manual
9
2012-08-21
SAP HANA Database - SQL Reference Manual
Notation This reference use BNF (Backus Naur Form) which is the notation technique used to define programming languages, t o describe SQL. B NF describes the syntax of a g rammar 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 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.
10
2012-08-21
SAP HANA Database - SQL Reference Manual
Introduction This chapter describes the SAP HANA Data base 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 r etrieve, 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:
::= | ::= [{|}, ...] ::= " ::= any character ::= 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 ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 ::= | ::= _
Identifiers are used to represent names used in SQL statement including table name, view name, synonym name, column name, index name, function name, procedure name, user name, role name, and so on. There are two kinds of identifiers; undelimited identifiers and delimited identifiers. Undelimited table and column names must start with a letter and cannot contain any symbols other than digits or an underscore "_". Delimited identifiers are enclosed in the delimiter, double quotes, then the identifier can contain any character including special characters. For example, "AB $%CD" is a valid identifier name. Limitations: "_SYS_" is reserved exclusively for database engine, hence not allowed at the beginning of schema object names. Role name and user name must be specified as undelimited identifiers. Maximum length for the identifiers is 127 characters.
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
11
2012-08-21
SAP HANA Database - SQL Reference Manual
Double quotation marks are used to delimit identifiers and double quotation mark itself can be represented using two double quotation marks.
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 ta ble lists all the current and future reserved words for the SAP HANA Database. ALL
ALTER
AS
BEFORE
BEGI N
BOTH
CASE
CHAR
CONDITI ON
CONNECT
CROSS
CUBE
CU RR EN T_ CO NN ECT IO N
CU RR EN T_ DA TE
CU RR EN T_ SCH EMA
CU RR EN T_ TI ME
CU RR EN T_ TI ME ST AMP
CU RR EN T_ US ER
CU RR EN T_ UT CD AT E
CU RR EN T_ UT CT I ME
CURRENT_UTCTIMESTAMP
CURRVAL
CURSOR
DECLARE
DISTINCT
ELSE
ELSEIF
ELSIF
END
EXCEPT
EXCEPTION
EXEC
FOR
FROM
FULL
GROUP
HAVI NG
IF
IN
INNER
INOUT
INTERSECT
INTO
IS
JOIN
LEADING
LEFT
LIMI T
LOOP
MINUS
NATURAL
NEXTVAL
NULL
ON
ORDER
OUT
PRIOR
RETURN
RETURNS
REVERSE
RIGHT
ROLLUP
ROWID
SELECT
SET
SQL
START
SYSDATE
SYSTIME
SYSTIMESTAMP
SYSUUID
TOP
TRAI LING
UNI ON
USING
UTCDATE
UTCTIME
UTCTIMESTAMP
VALUES
WHEN
WHERE
WHILE
WI TH
Table 1. Reserved Words
12
2012-08-21
SAP HANA Database - SQL Reference Manual
Data Types This section describes the data types used in the SAP HANA Database. Data type specifies the characteristics of a dat a 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 Da tabase each data type can be classified by its characteristic a s follows: C lass ificat io n
Dat a Ty pe
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
Bi na ry type s
VARBINARY
L a rg e Ob je ct typ e s
B LO B, CL OB , N CL OB , T EXT
Table 2: Classification of data types
Datetime Types DATE The DATE data t ype consists of year, month, and day information to represent a date value. The default format for the DATE data t ype is 'YYYY-MM-DD'. YYYY represents the year, MM r epresents 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 t ype 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 t ype is 'YYYY-MM-DD HH24:MI:SS'. YYYY represents the year, MM represents the month, D D represents the day, HH24 represents hour, MI represents minute, and SS represents seconds. The range of date value is 000101-01 00:00:01 t hrough 9999-12-31 24:00:00. TIMESTAMP The TIMESTAMP data t ype 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. . T he range of t he timestamp value is 0001-01-01 00:00:00.0000000 through 9999-1231 23:59:59.9999999.
For details on supported formats for datetime types, refer to Table 4, Ta ble 5, Table 6 a nd Table 7 below. Date Formats
The following date/time formats ca n be used when parsing a string into a dat e/time type and converting a date/time type value into a string value. Please note that format for Timestamp is the combination of Date and Time with the additional support for fractional seconds.
13
2012-08-21
SAP HANA Database - SQL Reference Manual
Format
Description
Examples
YYYY-MM-DD
De fa ul t forma t
INSERT INTO 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, or day 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 INSERT INSERT INSERT
YYYYMMDD
ABAP Da ta Type , DATS forma t.
INSERT INTO TBL VALUES ('19570613');
Abbre vi a ted na me of month. (JAN. ~ DEC.)
INSERT INTO TBL VALUES (TO_DATE('2040Jan-10', 'YYYY-MON-DD')); INSERT INTO TBL VALUES (TO_DATE('Jan10', 'MON-DD'));
MONTH
Na me of month. (JANUARY - DECEMBER).
INSERT INTO TBL VALUES (TO_DATE('2040January-10', 'YYYY-MONTH-DD')); INSERT INTO TBL VALUES (TO_DATE('January-10', 'MONTH-DD'));
RM
Roma n numera l month (I -XII ; JAN = I).
INSERT INTO TBL VALUES (TO_DATE('2040-I10', 'YYYY-RM-DD')); INSERT INTO TBL VALUES (TO_DATE('I-10', 'RM-DD'));
DDD
Da y of ye a r (1-366).
INSERT INTO TBL VALUES (TO_DATE('204', 'DDD')); INSERT INTO TBL VALUES (TO_DATE('2001204','YYYY-DDD'));
MON
INTO TBL INTO TBL INTO TBL INTO TBL
VALUES ('1957-06-13'); VALUES ('1957/06/13'); VALUES ('1957/06-13'); VALUES ('1957-06/13');
Table 4: Supported formats for Date
Time Formats Format
Description
Examples
HH24:MI:SS
Defa ul t 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 is specified, 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 TBL VALUES ('23:59:59'); INSERT INTO TBL VALUES ('3:47:39 AM'); INSERT INTO TBL VALUES ('9:9:9 AM'); INSERT INTO TBL VALUES (TO_TIME('11:59:59','HH12:MI:SS');
SSSSS
Seconds pa s t mi dni ght (0-86399).
INSERT INTO TBL VALUES (TO_TI ME('12345', 'SSSSS'));
Table 5: Supported formats for Time
Timestamp Formats Format
Description
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.
Examples
INSERT INTO TBL VALUES (TO_TIMESTAMP('2011-05-11 12:59.999','YYYY-MM-DD HH:SS.FF3'));
Table 6: Supported formats for Timestamp
Additional Formats
14
2012-08-21
SAP HANA Database - SQL Reference Manual
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
Abbre vi a ted na me of da y (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')
RM
Roman numeral month (I - XII; I is for January)
TO_CHAR(CURRENT_TIMESTAMP,'RM')
Q
Qua rter of yea r (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')
Table 7: Additional formats for Datetime
Supported Functions for Date/Time types ADD_DAYS ADD_MONTHS ADD_SECONDS ADD_YEARS COALESCE CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP CURRENT_UTCDATE CURRENT_UTCTIME CURRENT_UTCTIMESTAMP DAYNAME DAYOFMONTH DAYOFYEAR DAYS_BETWEEN EXTRACT GREATEST GREATEST HOUR IFNULL ISOWEEK LAST_DAY LEAST LOCALTOUTC MINUTE MONTH MONTHNAME NEXT_DAY NULLIF QUARTER SECOND SECONDS_BETWEEN TO_CHAR TO_DATE TO_DATS TO_NCHAR TO_TIME TO_TIMESTAMP UTCTOLOCAL WEEK WEEKDAY YEAR
Numeric Types TINYINT The TINYINT data type stores an 8-bit unsigned integer. The minimum value is 0 and the maximum value is 255 for TINYINT. SMALLINT The SMALLINT data type stores a 16-bit signed integer. The minimum value is -32,768 and the maximum value is 32,767 for SMALLINT.
15
2012-08-21
SAP HANA Database - SQL Reference Manual
INTEGER The INTEGER data type stores a 32-bit signed integer. The minimum value is -2,147,483,648 and t he 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) The DECIMAL(p, s) data type specifies a fixed-point decimal number with precision p and scale s. 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 ca n range from -6,111 to 6,176, which means scale specifies the range of the exponent in the decimal number from 10-6111 to 106176. If scale is not specified, it defaults to 0. Scale is positive when the number has significant digits to the rig ht of the decimal point a nd negative when the number has significant digits to the left of the decimal point. Examples: 0.0000001234 (1234 x 10-10) has the precision 4 and the scale 10. 1.0000001234 (10000001234 x 10-10) has the precision 11 and scale 10. 1234000000 (1234x106) has the precision 4 and scale -6. When precision and scale are not specified, DECIMAL becomes a floating-point decimal number. In this case, precision and scale can vary within the range described above, 1~34 for precision and 6,111~6,176 for scale depending on the stored value. SMALLDECIMAL The SMALLDECIMAL is a floating-point decimal number. The precision and scale can vary within the range, 1~16 for precision and -369~368 for scale depending on t he 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 larg est negative DOUBLE value is -2.2207x10-308. FLOAT(n) The FLOAT(n) data type specifies a 32-bit or 64-bit real number, where n specifies the number of significant bits and can range between 1 and 53.
When you use the FLOAT(n) data type, if n is smaller than 25, it becomes a 32-bit REAL data type. I f n is greater than or equal to 25, it then becomes a 64-bit DOUBLE data t ype. 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 t ype 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 t ype 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 charact er string which contains alphanumeric chara cters, where n indicates the maximum length and is an integer between 1 and 127. SHORTTEXT The SHORTTEXT(n) data type specifies veriable-length chara cter string which supports textsearch-
16
2012-08-21
SAP HANA Database - SQL Reference Manual
features and stringsearch-features. This is not a standalone sql-type. Selecting a SHORTTEXT(n)column yields a column of type NVARCHAR(n).
::= SHORTTEXT '(' int_const ')'
::= [... ',' ] ::= | SYNC[HRONOUS]
Binary Types Binary types are used to store bytes of binary data. VARBINARY The VARBINAR Y(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, a re 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 charac ter data. NCLOB The NCLOB data t ype is used to store a la rge 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 ::= [... ',' ] ::= | [SYNC[HRONOUS] | [ASYNC[HRONOUS] FLUSH [QUEUE] EVERY MINUTES [[OR] AFTER DOCUMENTS] ]
Syntax-rules common to TEXT and SHORTTEXT ::= LANGUAGE COLUMN | LANGUAGE DETECTION '(' ')' | MIME TYPE COLUMN | FUZZY SEARCH INDEX [ON|OFF] | PHRASE INDEX RATIO [ON|OFF] | CONFIGURATION | SEARCH ONLY [ON|OFF] | FAST PREPROCESS [ON|OFF]
LOB types are provided for storing and retrieving such large data. LOB types support t he 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 ORD ER 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 LI KE, CONTAINS, =, or <>. LOB columns cannot appear in SELECT clauses as an a ggrega te 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. LOB columns cannot be used in CREATE INDEX statements. LOB columns cannot be used in statistics update statements.
17
2012-08-21
SAP HANA Database - SQL Reference Manual
Mapping between SQL Data Type and Column Store Data Type SQL Type I nt nte ge ge r Typ es es
Ap p ro xi ma te Typ e s
D e ci ma l Typ e s
Ch a ra ra ct cte r Typ e s
B i n a ry Typ e s
D at ate /T /Ti me me Typ es es
Column St ore Type
TI NY NYI NT NT, S MA MALLI NT NT, I NT NT
CS _I NT NT
B I G I NT
CS _F I XED (18,0)
R EAL
CS _F LOAT
D OUB LE
CS _D OU B LE
F LOAT
CS _D OU B LE
F LOAT(p )
CS _F LOAT, CS _D OU B LE
D ECI MAL
CS _D ECI MAL_F LOAT
D ECI MAL( p ,s )
CS _F I XED (p -s ,s )
S MALLD ECI MAL
CS _S D F LOAT
VAR CH AR AR
CS_STRING,CS_ALPHANUM,CS_UNITDECFLOAT,CS_DATE,CS_TIME CS_STRING,CS_ALPHANUM,CS_UNITDECFLOAT,CS_DATE,CS_TIME
NVARCHAR
CS_STRING,CS_ALPHANUM,CS_UNITDECFLOAT CS_STRING,CS_ALPHANUM,CS_UNITDECFLOAT
CLOB , NCLOB
CS _S TR I NG
ALPH ANUM
CS _ALPH AN UM
B LOB
CS _R AW
VAR B I NAR Y
CS _R AW
D A TE
CS_DAYDATE,CS_DATE CS_DAYDATE,CS_DATE
TIME
CS_SECONDTIME,CS_TIME CS_SECONDTIME,CS_TIME
TIMESTAMP
CS_LONGDATE,CS_DATE,CS_SECONDDATE CS_LONGDATE,CS_DATE,CS_SECONDDATE
S ECON D D ATE
CS _S ECOND D ATE
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 be converted using using the following functions: functions: CAST, TO_ALPHANUM, TO_BI GINT, 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 BIGI NT and VARCHAR is performed by implicitly implicitly converting converting VARCHAR to B IGINT. The entire explicit conversions conversions can be used for implicit conversion conversion except 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 Input Express Expression ion
Transformed Tran sformed Express Expression ion with Impli Implicit cit Conversi Conversion on
BIGINT BIGINT > VARC VARCHA HAR R
BIGINT BIGINT > BIGINT( BIGINT(VA VARC RCHAR HAR))
BIGINT BIGINT > DECIMA DECIMALL
DECIMA DECIMAL( L(BIGIN BIGINT) T) > DECIM DECIMAL AL
TIMESTAMP TIMESTAMP > DATE DATE
TIMESTAMP TIMESTAMP > TIMESTAM TIMESTAMP(DAT P(DATE) E)
D AT AT E > T IM IME
E rr rr or or b e ca ca u s e th th e re re i s no no co co n ve ve rs rs i o n a va va i l a b l e be be t we we e n DA DA TE TE a n d T IM IME
Table 8: Implicit Type conversion Examples
In the tables below, Boxes with "OK" means data type conversions are allowed without any checks. Boxes with "CHK" means the data t ype can be converted if the data is valid for the tar get type. Boxes with "-" indicates that data type conversion is not allowed. The rules shown are applicable to both implicit and explicit conversion except for Time to Timestamp conversion. Only explicit conversions are allowed for converting the Time data type to Timestamp using the TO_TIMESTAMP or CAST functions.
18
2 0 12 -0 8 -2 1
SAP HANA Database - SQL Reference Manual
Target/ Source
t n i l l a m s
t n i y n i t
r e g e t n i
) s , p ( l a m i c e d
l a m i c e d
t n i g i b
l a m i c e d l l a m s
e l b u o d
l a e r
r a h c r a v
r a h c r a v n
tinyint
-
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
smallint
CH K
-
OK
OK
OK
OK
OK
OK
OK
OK
OK
integer
CH K
CH K
-
OK
OK
OK
OK
OK
OK
OK
OK
bigint
CH K
CH K
CH K
-
OK
CH K
CH K
CH K
OK
OK
OK
decimal
CH K
CH K
CH K
CH K
-
CH K
CH K
CH K
OK
OK
OK
decimal(p,s)
CH K
CH K
CH K
CH K
CH K
CH K
CH K
CH K
CH K
CH K
OK
smalldecimal
CH K
CH K
CH K
CH K
OK
CH K
-
CH K
CH K
OK
OK
real
CH K
CH K
CH K
CH K
OK
CH K
CH K
-
OK
OK
OK
double
CH K
CH K
CH K
CH K
CH K
CH K
CH K
CH K
-
OK
OK
varchar
CH K
CH K
CH K
CH K
CH K
CH K
CH K
CH K
CH K
-
OK
nvarchar
CH K
CH K
CH K
CH K
CH K
CH K
CH K
CH K
CH K
CH K
-
Table 9a: Data type conversion table
Target/ Source
time tim e
date da te
secon sec ondda ddate te
timest tim estam amp p
varc va rcha harr
nvar nv arch char ar
time
-
-
-
-
OK
OK
date
-
-
OK
OK
OK
OK
seconddate
ti m e
d a te
-
t i m e s ta m p
OK
OK
timestamp
ti m e
d a te
s e co n d d a te
-
OK
OK
varchar
CH K
CH K
CH K
CH K
-
OK
nvarchar
CH K
CH K
CH K
CH K
CH K
-
Table 9b: Data type conversion table
Target/ Source
varbin va rbinary ary
alpha al phanum num
varch va rchar ar
nvarch nva rchar ar
varbinary
-
-
-
-
alphanum
-
-
OK
OK
varchar
OK
OK
-
OK
nvarchar
OK
OK
CH K
-
Table 9c: Data type conversion table
Data Type Precedence
This section describes describes the data type precedence implemented implemented by the SAP HANA Data base. Da ta type precedence precedence specifies that the dat a t ype with lower precedence is converted converted to t he data type with higher precedence.
19
2 0 12 -0 8 -2 1
SAP HANA Database - SQL Reference Manual
Highest
TIMESTAMP SECONDDATE DATE TIME DOUBLE REAL DECIMAL SMALLDECIMAL BIGINT INTEGER SMALLINT TINYINT NCLOB NVARCHAR CLOB VARCHAR BLOB
Lowest
VARBINARY
Typed Constant A constant is a symbol symbol that represents represents a specific specific fixed data value. Character string contant A charact er string constant is enclosed enclosed in single quotation marks.
'Brian' '100' Unicode Unicode string has a similar format to charact er string but is preceded by an N identifier (N stands for National Language in the SQL-92 standard). The N prefix must must be uppercase. N'abc' SELECT 'Brian' "character string 1", 1", '100' "character string 2", 2", N'abc' 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" "integer", , 123.4 "decimal1" "decimal1", , 1.234e2 "decimal2" "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' X'00abcd' "binary string 1", 1", x'dcba00' x'dcba00' "binary string 2" FROM DUMMY; binary string 1, binary string 2
20
2 0 12 -0 8 -2 1
SAP HANA Database - SQL Reference Manual
00ABCD, DCBA00
Date/Time/Timestamp consta nt 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
21
2012-08-21
SAP HANA Database - SQL Reference Manual
Predicates A predicate is specified by combining one or more expressions, or logical operators, and returns one of the following logical/truth values: TR UE, FALSE, or UNKNOWN.
Comparison Predicates Two values are compared using comparison predicates and the comparison returns true, false, or unknown. Syntax: ::= { = | != | <> | > | < | >= | <= } [ ANY | SOME| ALL ] { | } ::= , ...
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: ::=
[NOT] BETWEEN
AND
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: ::= [NOT] IN { | }
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: ::= [NOT] EXISTS ( )
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 charac ters 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: ::= [NOT] LIKE [ESCAPE ]
NULL Predicate
22
2012-08-21
SAP HANA Database - SQL Reference Manual
When the IS NULL predicate is specified, a value can be compared with NULL. IS NULL returns true if the expression value is NULL. If t he IS NOT NULL predicate is specified, it returns true if a value is not NULL. Syntax: ::= IS [NOT] NULL
CONTAINS Predicate The CONTAINS predicate is used to search for text-matches to a search string in subqueries. Syntax: ::= CONTAINS '(' ',' ')' | CONTAINS '(' ',' ',' ')'
::= '*' | | '(' ')'
::=
::= |
::= empty | ::= | | ::= | ',' :=
|
::= EXACT ::= FUZZY | FUZZY '(' ')' | FUZZY '(' ',' ')' ::= LINGUISTIC ::= WEIGHT '(' ')' :: LANGUAGE '(' ')' ::=
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 mat ches of the searchterms are found in the searchattributes FUZZY FUZZY returns true for those records where words similar to the searchterms are found in the searchattributes (e.g. spelling errors will be ignored to a certain extent) float_const If float_const is omitted, then 0.8 is t he default. This default can be overridden by defining para meter 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 LANGUAGE
23
2012-08-21
SAP HANA Database - SQL Reference Manual
LANGUAGE is used during preprocessing of the search string and as a pre-search filter. Only documents which match the search string a nd the language specified are returned. LINGUISTIC LINGUISTIC returns true for those records where word-variants of the searchterms are found in the searchattributes (e.g. searching for 'cats' will also return records which contain 'cat') Limitations: If t here 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 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))
24
2012-08-21
SAP HANA Database - SQL Reference Manual
Operators You can perform arithmetic operations in expressions by using operators. Operators can be used for calculation, value comparison or to assign values.
Unary and Binary Operators Operator
Operation
Format
Description unary plus operator(+)
Unary
A unary operator applies to one operand or a single value expression.
operator operand
unary negation operator(-) logical negation(NOT) multiplicative operators ( *, / ) additive operators ( +,- )
Binary
Binary A binary operator applies to two operands or two value e xpress ions.
operand1 operator operand2
comparison operators ( =,!=,<,>,<=,>=) logical operators ( AND, OR )
Table 10. Unary and binary operators
Operator Precedence An expression can use several operators. If the number of operators is greater than one then the SAP HANA Database will evaluate t hem in order of operator precedence. You can change the order of evaluation by using parentheses, as expressions contained within parentheses are always evaluated first. If parentheses are not used, the operators have the precedence indicated by the table below. Please note, the SAP HANA Data base will evaluate operators with equal precedence from left to right within an expression. Precedence Hi ghes t
Lowe s t
Operator
Operation
()
pa renthe s e s
+, -
una ry pos i ti ve a nd ne ga ti ve ope ra ti on
*, /
mul ti pl i ca ti on, di vi s i on
+, -
a ddi ti on, s ubtra cti on
||
conca tena ti on
=, !=, <, >, <=, >=, IS NULL, LIKE, BETWEEN
comparsion
NOT
l ogi ca l nega ti on
AND
conjuncti on
OR
di s juncti on
Table 11. SQL operator precedence
Arithmetic Operators You use arithmetic operators to perform mathematical operations such as adding, subtracting, multiplying, dividing and negation of numeric values.
25
2012-08-21
SAP HANA Database - SQL Reference Manual
Operator
Description
-
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.
+
Addition. If either express ion i s the NULL value, the result i s NULL.
Subtraction. If either expression is the NULL value, the result is NULL.
*
Multipli cation. If either express ion i s NULL, the resul t is NULL.
/
Division. If ei ther expression i s NULL, or if the se cond expression i s 0, an error is returned.
Table 12. Arithmetic operators
String Operators A concatenation operator combines two items such as strings, expressions or constants into one. Operator
Description
||
String concatenation (two vertical bars). If ei ther string is NULL, it returns NULL.
Table 13. Concatenation operators
For VARCHAR or NVARCHAR type strings, leading or tra iling spaces are kept. If either string is of data t ype NVARCHAR, the result has data type NVARCHAR and is limited to 5000 characters. The maximum length for VARCHAR concatenation is also limited to 5000 chara cters.
Comparsion Operators Syntax: ::=
Operator
Description
Example
=
Equa l to
SELECT * FROM s tudents WHERE i d = 25;
>
Grea ter tha n
SELECT * FROM s tudents WHERE i d > 25;
<
Le s s tha n
SELECT * FROM s tudents WHERE i d < 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 e qua l
SELECT * FROM students WHERE id != 25; SELECT * FROM students WHERE id <> 25;
!=, <>
Table 14. Comparison operators
Logical Operators Search conditions can be combined using AND or OR operators. You can also negate them using the NOT operator. O pe rat or
Sy nt ax
De scr ip tio n
AND
WHERE condition1 AND 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.
NOT
WHERE 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.
Table 15. Logical operators
Set Operators The operators described in this section perform set operations on the results of two or more queries.
26
2012-08-21
SAP HANA Database - SQL Reference Manual
Operator
Returned Value
U NI O N
Co mb i n e s th e r es u l ts o f t wo o r mo re s e l e c t s t a te m e nt s o r q ue ry e xp re s s i o n s
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 all common rows.
EXCEPT
Takes output from the first query and then removes rows sele cted by the second query.
Table 16. Set operators
27
2012-08-21
SAP HANA Database - SQL Reference Manual
Expressions An expression is a clause t hat ca n be evaluated to r eturn values. Syntax: ::= | | | ( ) | ( ) | - | | | | [.]
Case Expressions A case expression allows the user to use IF ... THEN .. . ELSE logic without using procedures in SQL statements. Syntax: ::= CASE WHEN THEN , ... [ ELSE ] { END | END CASE }
If the expression following the CASE statement is equal to the expression following the WHEN statement, then the expression following the THEN statement is returned. Otherwise the expression following the ELSE statement is returned if it exists.
Function Expressions SQL built-in functions can be used as an expression. Syntax: ::= ( , ... )
Aggregate Expressions An aggrega te expression uses an aggrega te function to calculate a single value from the values of multiple rows in a column. Syntax: ::= COUNT(*) | ( [ ALL | DISTINCT ] ) ::= 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() 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
28
2012-08-21
SAP HANA Database - SQL Reference Manual
A subquery is a SELECT statement enclosed in parentheses. The SELECT statement can contain one and only one select list item. When used as an expression a scalar subquery is allowed to return only zero or one value. Syntax: ::= ()
Within the SELECT list of the top level SELECT, or in the SET clause of an UPDATE statement, you can use a scalar subquery anywhere that you can use a column name. However, scalar_subquery cannot be used inside GROUP BY clause. Example: For example, the following statement returns the number of employees in each department, grouped by department name: 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
2012-08-21
SAP HANA Database - SQL Reference Manual
SQL Functions Introduction This chapter describes SQL Functions that are provided by SAP HANA Database. Data Type Conversion Functions DateTime Functions Number Functions String Functions Miscellaneous Functions
Data Type Conversion Functions Data type conversion functions are used to convert arguments from one data t ype 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 t ype. TINYINT | SMALLINT | INTEGER | BIGI NT | 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 BI GINT data type.
30
2012-08-21
SAP HANA Database - SQL Reference Manual
Example
SELECT TO_BIGINT ('10') "to bigint" FROM DUMMY; to bigint 10
TO_BINARY Syntax
TO_BINARY (value) Description
Converts a value to a BI NARY 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_CHAR Syntax
TO_CHAR (value [, format]) Description
Converts a given value to a CHAR character data t ype. If t he format specifier is omitted, the conversion is performed using the date format model as explained in Date Formats Example
SELECT
TO_CHAR (TO_DATE('2009-12-31'), 'YYYY/MM/DD') "to char" FROM DUMMY;
to char 2009/12/31
TO_CLOB Syntax
TO_CLOB (value) Description
31
2012-08-21
SAP HANA Database - SQL Reference Manual
Converts a value to a CLOB data t ype. Example
SELECT TO_CLOB ('TO_CLOB converts the value to a CLOB data type') "to clob" FROM DU MMY; to clob TO_CLOB converts the value to a CLOB data type
TO_DATE Syntax
TO_DATE (d [, format]) Description
Converts a date string d into a D ATE data type. If t he 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 'YYYYMMD D'. 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 ca n range from 6,111 to 6,176. This means that the scale specifies the range of t he exponent in the decimal number from 106111 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 t he decimal point, and negative when the number has significant digits to the left of the decimal point. When precision and scale are not specified, DECIMAL becomes a floating-point decimal number. In this case, precision and scale can vary within the range described above, 1~34 for precision and -6,111~6,176 for scale depending on the stored value.
32
2012-08-21
SAP HANA Database - SQL Reference Manual
Example
SELECT
TO_DECIMAL(7654 321.888888, 10, 3) "to decimal" FROM DUMMY
to decimal 7654321.889
TO_DOUBLE Syntax
TO_DOUBLE (value) Description
Converts a value t o a DOUBLE (double precision) data type. 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 I NTEGER dat a 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 I NTEGER dat a type. Example
SELECT
TO_INTEGER ('10') "to int" FROM DUMMY;
to int 10
TO_NCHAR Syntax
TO_NCHAR (value [, format]) Description
Converts the value to a NCHAR unicode character dat a type. If the format specifier is omitted, the conversion
33
2012-08-21
SAP HANA Database - SQL Reference Manual
is performed using the date format model as explained in Date Formats. Example
SELECT
TO_NCHAR (TO_DATE('2009-12-31'), 'YYYY/MM/DD') "to nchar" FROM DUMMY;
to nchar 2009/12/31
TO_NCLOB Syntax
TO_NCLOB (value) Description
Converts a value to a NCLOB data t ype. 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
Converts the value to a NVARCHAR unicode character data t ype. 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 t o 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])
34
2012-08-21
SAP HANA Database - SQL Reference Manual
Description
Converts a date string d into a SECONDDATE data type. If the format specifier is omitted, t he 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 t ype. Example
SELECT
TO_SMALLDECIMAL(7654321.89) "to smalldecimal" FROM DUMMY;
to smalldecimal 7654321.89
TO_SMALLINT Syntax
TO_SMALLINT (value) Description
Converts the value to a SMALLINT data t ype. 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 t ype. If the format specifier is omitted, the conversion is performed using the time format model as explained in Time Formats. Example
SELECT TO_TIME ('08:30 AM', 'HH:MI AM') "to time" FROM DUMMY; to time 08:30:00
TO_TIMESTAMP
35
2012-08-21
SAP HANA Database - SQL Reference Manual
Syntax
TO_TIMESTAMP (d [, format]) Description
Converts a date string d into the TIMESTAMP data type. If t he 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
TO_VARCHAR Syntax
TO_VARCHAR (value [, format]) Description
Converts a given value to a VARCHAR character data t ype. 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
36
2012-08-21
SAP HANA Database - SQL Reference Manual
SELECT ADD_DAYS (TO_DATE ('2009-12-05', 'YYYY-MM-DD'), 30) "add days" FROM DUMMY; add days 2010-01-04
ADD_MONTHS Syntax
ADD_MONTHS (d, n) Description
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
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.
37
2012-08-21
SAP HANA Database - SQL Reference Manual
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. 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
38
2012-08-21
SAP HANA Database - SQL Reference Manual
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
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)
39
2012-08-21
SAP HANA Database - SQL Reference Manual
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) Description
Finds and returns the value of a specified datetime field from date d. Example
SELECT MY;
EXTRACT (YEAR FROM TO_DATE ('2010-01-04', 'YYYY-MM-DD')) "extract" FROM DUM
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
40
2012-08-21
SAP HANA Database - SQL Reference Manual
ISOWEEK (d) Description
Returns the ISO year and week numbers of date d. The week number is prefixed by the letter W. 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 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
41
2012-08-21
SAP HANA Database - SQL Reference Manual
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
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
42
2012-08-21
SAP HANA Database - SQL Reference Manual
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 sta rts 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 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 t o the local time in a timezone Example
43
2012-08-21
SAP HANA Database - SQL Reference Manual
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 r eturn value ranges from 0 to 6, representing Monday(0) through to Sunday(6). 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
44
2012-08-21
SAP HANA Database - SQL Reference Manual
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
ASIN (n) Description
Returns the arc-sine, in ra dians, of the numeric argument n between -1 a nd 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. unlimited. Example
SELECT ATAN (0.5) "atan" FROM DUMMY; atan 0.4636476090008061
45
2 0 12 -0 8 -2 1
SAP HANA Database - SQL Reference Manual
ATAN2 Syntax
ATAN2 (n, m) Description
Returns the arc-tangent, in radians, of the ratio of t wo numbers numbers n and m. This produces the same result 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('AB') ) "bintohex" FROM DUMMY; bintohex 4142
BITAND Syntax
BITAND (n, m) Description
Performs an AND operation on the bits of the arguments n and m. Both n and m must be non-negative integers. The BITAND function returns a result with BIGINT 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;
46
2 0 12 -0 8 -2 1
SAP HANA Database - SQL Reference Manual
ceiling 15
COS Syntax
COS (n) Description
Returns the cosine of the angle, in radians, of the a rgument 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
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 ument n. Example
47
2 0 12 -0 8 -2 1
SAP HANA Database - SQL Reference Manual
SELECT EXP (1.0) "exp" FROM DUMMY; exp 2.718281828459045
FLOOR Syntax
FLOOR (n) Description
Returns the largest integer not greater t han 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; 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 arg uments: n1, n2.. . Example
48
2012-08-21
SAP HANA Database - SQL Reference Manual
SELECT LEAST('aa', 'ab', 'ba', 'bb') "least" FROM DUMMY; least aa
LN Syntax
LN (n) Description
Returns the natural logarithm of the a rgument 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
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 grea ter than 0 and n is less than d, then n is returned. If n is less than 0 a nd n is greater t han 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 grea ter than 0, then the returned remainder from MOD is a positive number. Example
SELECT MOD (15, 4) "modulus" FROM DUMMY; modulus
49
2012-08-21
SAP HANA Database - SQL Reference Manual
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
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 z ero. Example
SELECT SIGN (-15) "sign" FROM DUMMY; sign -1
SIN Syntax
50
2012-08-21
SAP HANA Database - SQL Reference Manual
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) 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
51
2012-08-21
SAP HANA Database - SQL Reference Manual
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) 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
52
2012-08-21
SAP HANA Database - SQL Reference Manual
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
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. For Larg e Object (LOB) types, this function returns the length of the object in bytes. Example
53
2012-08-21
SAP HANA Database - SQL Reference Manual
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 haystack. 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 patt ern 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;
54
2012-08-21
SAP HANA Database - SQL Reference Manual
lpad 123451234512end
LTRIM Syntax
LTRIM (str [, remove_set]) Description
Returns string str, t rimmed of all leading spaces. I f remove_set is specified, LTR IM removes all the charact ers contained in this set from the start of string str. This process continues until a character not the in remove_set is reached. Note:
remove_set is treated as a set of characters a nd 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 t wo 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, t hen 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
55
2012-08-21
SAP HANA Database - SQL Reference Manual
Syntax
RIGHT(str, n) Description
Returns the rightmost n chara cters/bytes of string str. Example
SELECT
RIGHT('HI0123456789', 3) "right" FROM DUMMY;
right 789
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 a rgument 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 a nd 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 arg ument. If str does not contain the patt ern substring, t hen an empty string is returned.
56
2012-08-21
SAP HANA Database - SQL Reference Manual
If patt ern is an empty string, then str is returned. If str or patt ern 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) Description
Returns a substring of string str before the first occurrence of the pattern argument in the ta rget string. If str does not contain the patt ern substring, t hen an empty string is returned. If patt ern is an empty string, then str is returned. If str or patt ern 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 t rimming 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 a nd trailing substring trim_char from string str. If trim_char is not specified, then a single blank space is used.
57
2012-08-21
SAP HANA Database - SQL Reference Manual
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) Description
Converts all charac ters 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 charac ters in string str to uppercase. Note:
The UPPER function is identical to the UCASE function. Example
SELECT UPPER ('Ant') "uppercase" FROM DUMMY; uppercase ANT
58
2012-08-21
SAP HANA Database - SQL Reference Manual
Miscellaneous Functions COALESCE Syntax
COALESCE (expression_list) Description
Returns the first non-NULL expression from a list. At least two expressions must be contained in expression_list, and all expressions must be comparable. The result will be NULL if all the arguments are NULL. Example
CREATE INSERT INSERT INSERT
TABLE coalesce_example (ID INT PRIMARY KEY, A REAL, B REAL); INTO coalesce_example VALUES(1, 100, 80); INTO coalesce_example VALUES(2, NULL, 63); 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
59
2012-08-21
SAP HANA Database - SQL Reference Manual
Syntax
CURRENT_USER Description
Returns the current user name at t he 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; 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 ret urn 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 GR OUPING SETS. By t reating the bit vector a s a binary number, this function returns an integer value a s 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
2012-08-21
SAP HANA Database - SQL Reference Manual
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 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.
61
2012-08-21
SAP HANA Database - SQL Reference Manual
Note:
Search values and corresponding results are always provided in search-result pairs. Example
SELECT MAP(2, 0, 'Zero', 1, 'One', 2, 'Two', 3, 'Three', 'Default') "map" FROM DUMM Y; map Two
SELECT MAP(99, 0, 'Zero', 1, 'One', 2, 'Two', 3, 'Three', 'Default') "map" FROM DUM MY; map Default
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 'TR ACEPROFILE'. Session variables can be defined or modified using SET [SESSION] = command, and unset using UNSET [SESSION] . SESSION_CONTEXT returns an NVARCHAR with a maximum length of 512 chara cters. Example
To read session variables use:
62
2012-08-21
SAP HANA Database - SQL Reference Manual
SELECT SESSION_CONTEXT('APPLICATION') "session context" FROM DUMMY; session context HDBStudio
SESSION_USER Syntax
SESSION_USER Description
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 the SYSUUID of the connected SAP HANA instance. Example
SELECT SYSUUID FROM DUMMY; SYSUUID 4DE3CD576C79511BE10000000A3C2220
63
2012-08-21
SAP HANA Database - SQL Reference Manual
SQL Statements This chapter describes the SQL statements that a re supported by the SAP HANA Data base. Schema Definition and Manipulation Statements Data Manipulation Statements System Management Statements Session Management Statements Transaction Management Statements Access Control Statements Data Import Export Statements
Schema Definition and Manipulation Statements ALTER AUDIT POLICY Syntax
ALTER AUDIT POLICY Syntax Elements
::=
The name of the audit policy to be altered. ::= 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. must specify an existing audit policy. Only database users having the system privilege AUDIT ADMIN a re allowed to alter a n audit policy. Each database user that has t his privilege can alter any audit policy, regardless of if they are the creator of t he policy. A newly created audit policy is disabled by default and does not cause any auditing to occur. Therefore the audit policy has to be enabled to make its audit actions take effect. An audit policy can be disabled and enabled as often as required.
Configuration Parameters
The following configuration parameters for auditing ar e stored in global.ini, in t he section on 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. default_audit_trail_path Specifies the file path where the CSVTEXTFILE should be stored. These parameters can be selected in monitoring view M_INIFILE_CONTENTS if the c urrent user has the
64
2012-08-21
SAP HANA Database - SQL Reference Manual
required system privileges. These parameters will only be seen in the case that they have been explicitly set. System Tables and Monitoring Views
AUDIT_POLICY: shows all audit policies and their states M_INIFILE_CONTENTS: shows the data base system configuration parameters Only database users with system privilege CATALOG READ, D ATA ADMIN or I NIFILE ADMI N can view the content of the M_INI FILE_CONTENTS view. For all other data base users this view will be empty. Example
For this example you need to first create an audit policy called priv_audit using the following statement: CREATE AUDIT POLICY priv_audit AUDITING SUCCESSFUL GRANT PRIVILEGE, REVOKE PRIVILEG E, GRANT ROLE, REVOKE ROLE LEVEL CRITICAL;
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 Syntax Elements
::=
The identifier of the fulltext index to be altered. ::= | 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. ::= [, ...]
A list of fulltext index parameters that are to be changed. ::= FUZZY SEARCH INDEX | PHRASE INDEX RATIO |
::= ON | OFF
FUZZY SEARCH INDEX Use a fuzzy search index. PHRASE INDEX RATIO Specifies the phrase index ratio. ::=
Specifies the percentage of the phrase index ratio, the value used must be between 0.0 and 1.0 ::= SYNC[HRONOUS] | ASYNC[HRONOUS] [FLUSH [QUEUE] ]
SYNC[HRONOUS] Changes the fulltext index to synchronous mode. ASYNC[HRONOUS]
65
2012-08-21
SAP HANA Database - SQL Reference Manual
Changes the fulltext index to asynchronous mode. ::= EVERY MINUTES | AFTER DOCUMENTS | EVERY MINUTES OR AFTER DOCUMENTS
When using an asynchronous index you use the flush_queue_elem to specify when to update the fulltext index. ::= FLUSH | SUSPEND | ACTIVATE
FLUSH Update the fulltext index with the documents in the queue which have already been processed. SUSPEND Suspends the fulltext index processing queue. ACTIVATE Activates the fulltext index processing queue. Description
With this command you can 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 are not blocked until a document is processed. The ALTER FULLTEXT INDEX stat ement changes the parameters of a fulltext index. The ALTER FULLTEXT IND EX stat ement changes the processing queue state for an asynchronous fulltext index. Example
ALTER FULLTEXT INDEX i1 PHRASE INDEX RATIO 0.3 FUZZY SEARCH INDEX ON
In the example above for fulltext index 'i1' the phrase index is set to 30 percent and the fuzzy search index is turned on. ALTER FULLTEXT INDEX i2 SUSPEND QUEUE
Suspends the queue for fulltext index 'i2'. ALTER FULLTEXT INDEX i2 FLUSH QUEUE
Updates fulltext index 'i2' with all processed documents in the queue. ALTER INDEX Syntax
ALTER INDEX REBUILD Syntax Elements
::=
Specifies the name of the index to be rebuilt. Description
The ALTER I NDEX statement rebuilds an index. Example
The following example rebuilds the idx index. ALTER INDEX idx REBUILD;
66
2012-08-21
SAP HANA Database - SQL Reference Manual
ALTER SEQUENCE Syntax
ALTER SEQUENCE [] [RESET BY ] Syntax Elements
::=
The name of the sequence to be altered. ::= , ... ::= | ::= RESTART WITH ::= | | | | | |
INCREMENT BY MAXVALUE NO MAXVALUE MINVALUE NO MINVALUE CYCLE NO CYCLE
RESTART WITH 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. ::=
An integer value between 0 and 4611686018427387903 which will be the first value provided by the sequence generator. INCREMENT BY The sequence increment. ::=
An integer value which will be used to increment or decrement the sequence value. MAXVALUE Defines the maximum value that can be generated by the sequence. ::=
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 Defines the minimum value that can be generated by the sequence. ::=
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.
67
2012-08-21
SAP HANA Database - SQL Reference Manual
NO CYCLE When the NO CYCLE directive is used the sequence number will not be restarted after it reaches its maximum or minimum value. ::=
During a restart of the database, the system automatically executes the RESET BY sta tement 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 para meters of a sequence generator. Example
In the example below you change the starting sequence value of sequence seq to 2. ALTER SEQUENCE seq RESTART WITH 2;
In the example below you change the maximum value of sequence seq to 100 along with no minimum value. ALTER SEQUENCE seq MAXVALUE 100 NO MINVALUE;
In the example below you change the increment of sequence seq to 2 along with a "no cycle" restriction. ALTER SEQUENCE seq INCREMENT BY 2 NO CYCLE;
In the example below you first create a ta ble r, with a column a. You then change the reset-by subquery of sequence seq to the maximum value contained in column a. CREATE TABLE r (a INT); ALTER SEQUENCE seq RESET BY SELECT MAX(a) FROM r;
ALTER TABLE Syntax
ALTER TABLE { | | | | | | | | | | | | | | | | | } Syntax Elements
::= [ .] ::= ADD ( [], ... ) ::= DROP ( , ... ) ::= ALTER ( [], .. . ) ::= [] [] [DEFAULT