hana_sql_en
-
Upload
rahul-gupta -
Category
Documents
-
view
549 -
download
5
Transcript of hana_sql_en
SAP HANA Database - SQL Reference ManualSAP HANA Appliance Software SPS 04
Target Audience
ConsultantsAdministratorsSAP Hardware PartnerOthers
1 2012-08-21
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 forany purpose without the express permission of SAP AG. The informationcontained herein may be changed without prior notice.
Some software products marketed by SAP AG and its distributors containproprietary software components of other software vendors.
Microsoft, Windows, Excel, Outlook, PowerPoint, Silverlight, and Visual Studioare registered trademarks of Microsoft Corporation.
IBM, DB2, DB2 Universal Database, System i, System i5, System p, Systemp5, 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, SystemStorage, Storwize, XIV, GPFS, HACMP, RETAIN, DB2 Connect, RACF,Redbooks, OS/2, AIX, Intelligent Miner, WebSphere, Tivoli, Informix, and SmarterPlanet are trademarks or registered trademarks of IBM Corporation.
Linux is the registered trademark of Linus Torvalds in the United States and othercountries.
Adobe, the Adobe logo, Acrobat, PostScript, and Reader are trademarks orregistered trademarks of Adobe Systems Incorporated in the United States andother 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, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, andMultiWin are trademarks or registered trademarks of Citrix Systems Inc.
HTML, XML, XHTML, and W3C are trademarks or registered trademarks ofW3C®, 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 registeredtrademarks 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 2012-08-21
in Motion Limited.
Google App Engine, Google Apps, Google Checkout, Google Data API, GoogleMaps, Google Mobile Ads, Google Mobile Updater, Google Mobile, Google Store,Google Sync, Google Updater, Google Voice, Google Mail, Gmail, YouTube,Dalvik and Android are trademarks or registered trademarks of Google Inc.
INTERMEC is a registered trademark of Intermec Technologies Corporation.
Wi-Fi is a registered trademark of Wi-Fi Alliance.
Bluetooth is a registered trademark of Bluetooth SIG Inc.
Motorola is a registered trademark of Motorola Trademark Holdings LLC.
Computop is a registered trademark of Computop Wirtschaftsinformatik GmbH.
SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAPBusinessObjects Explorer, StreamWork, SAP HANA, and other SAP productsand services mentioned herein as well as their respective logos are trademarks orregistered trademarks of SAP AG in Germany and other countries.
Business Objects and the Business Objects logo, BusinessObjects, CrystalReports, Crystal Decisions, Web Intelligence, Xcelsius, and other BusinessObjects products and services mentioned herein as well as their respective logosare trademarks or registered trademarks of Business Objects Software Ltd.Business Objects is an SAP company.
Sybase and Adaptive Server, iAnywhere, Sybase 365, SQL Anywhere, and otherSybase products and services mentioned herein as well as their respective logosare trademarks or registered trademarks of Sybase Inc. Sybase is an SAPcompany.
Crossgate, m@gic EDDY, B2B 360°, and B2B 360° Services are registeredtrademarks of Crossgate AG in Germany and other countries. Crossgate is anSAP company.
All other product and service names mentioned are the trademarks of theirrespective companies. Data contained in this document serves informationalpurposes only. National product specifications may vary.
These materials are subject to change without notice. These materials areprovided by SAP AG and its affiliated companies ("SAP Group") for informationalpurposes only, without representation or warranty of any kind, and SAP Groupshall not be liable for errors or omissions with respect to the materials. The onlywarranties for SAP Group products and services are those that are set forth inthe express warranty statements accompanying such products and services, ifany. Nothing herein should be construed as constituting an additional warranty.
3 2012-08-21
489
101111111111111112
1313131314141415
15161717181820
2222222222222223
2525252526262626
2828282828
303030303030313131313232
Table of Content
Table of ContentSAP HANA Database - SQL Reference Manual
SQL Reference ManualNotationIntroduction
SQLSupported Languages and Code PagesCommentIdentifiersSingle Quotation MarkDouble Quotation MarkSQL Reserved Words
Data TypesClassification of Data TypesDatetime Types
Date FormatsTime FormatsTimestamp FormatsAdditional FormatsSupported Functions for Date/Time types
Numeric TypesCharacter String TypesBinary TypesLarge Object (LOB) TypesMapping between SQL Data Type and Column Store Data TypeData Type ConversionTyped Constant
PredicatesComparison PredicatesRange PredicateIn PredicateExists PredicateLIKE PredicateNULL PredicateCONTAINS Predicate
OperatorsUnary and Binary OperatorsOperator PrecedenceArithmetic OperatorsString OperatorsComparsion OperatorsLogical OperatorsSet Operators
Express ionsCase ExpressionsFunction ExpressionsAggregate ExpressionsSubqueries in Expressions
SQL FunctionsIntroductionData Type Conversion Functions
CASTTO_ALPHANUMTO_BIGINTTO_BINARYTO_BLOBTO_CHARTO_CLOBTO_DATETO_DATS
Table of Content
4 2012-08-21
323333333334343434353535353636
3636373737373838383839393939404040404141414242424243434343444444
4444454545464646464747474748484848494949505050505151515152
TO_DECIMALTO_DOUBLETO_INTTO_INTEGERTO_NCHARTO_NCLOBTO_NVARCHARTO_REALTO_SECONDDATETO_SMALLDECIMALTO_SMALLINTTO_TIMETO_TIMESTAMPTO_TINYINTTO_VARCHAR
DateTime FunctionsADD_DAYSADD_MONTHSADD_SECONDSADD_YEARSCURRENT_DATECURRENT_TIMECURRENT_TIMESTAMPCURRENT_UTCDATECURRENT_UTCTIMECURRENT_UTCTIMESTAMPDAYNAMEDAYOFMONTHDAYOFYEARDAYS_BETWEENEXTRACTHOURISOWEEKLAST_DAYLOCALTOUTCMINUTEMONTHMONTHNAMENEXT_DAYNOWQUARTERSECONDSECONDS_BETWEENUTCTOLOCALWEEKWEEKDAYYEAR
Number FunctionsABSACOSASINATANATAN2BINTOHEXBITANDCEILCOSCOSHCOTEXPFLOORGREATESTHEXTOBINLEASTLNLOGMODPOWERROUNDSIGNSINSINHSQRTTANTANHUMINUS
Table of Content
5 2012-08-21
5252525353535354545455555555565656575757585858
595959595960616162626363
646464656667687375767777787983909091919192929393949495969697
979798
101102103104105113113
String FunctionsASCIICHARCONCATLCASELEFTLENGTHLOCATELOWERLPADLTRIMNCHARREPLACERIGHTRPADRTRIMSUBSTR_AFTERSUBSTR_BEFORESUBSTRINGTRIMUCASEUNICODEUPPER
Miscellaneous FunctionsCOALESCECURRENT_CONNECTIONCURRENT_SCHEMACURRENT_USERGROUPING_IDIFNULLMAPNULLIFSESSION_CONTEXTSESSION_USERSYSUUID
SQL StatementsSchema Definition and Manipulation Statements
ALTER AUDIT POLICYALTER FULLTEXT INDEXALTER INDEXALTER SEQUENCEALTER TABLECREATE AUDIT POLICYCREATE FULLTEXT INDEXCREATE INDEXCREATE SCHEMACREATE SEQUENCECREATE SYNONYMCREATE TABLECREATE TRIGGERCREATE VIEWDROP AUDIT POLICYDROP FULLTEXT INDEXDROP INDEXDROP SCHEMADROP SEQUENCEDROP SYNONYMDROP TABLEDROP TRIGGERDROP VIEWRENAME COLUMNRENAME INDEXRENAME TABLEALTER TABLE ALTER TYPETRUNCATE TABLE
Data Manipulation StatementsDELETEEXPLAIN PLANINSERTLOADMERGE DELTAREPLACE | UPSERTSELECTUNLOADUPDATE
Table of Content
6 2012-08-21
114114114116116117117118118119119120120120121122122123123124124124
124124125125126126
126127127127127
128128129131132133134135135136142
143143144145
147149
150
System Management StatementsSET SYSTEM LICENSEALTER SYSTEM ALTER CONFIGURATIONALTER SYSTEM ALTER SESSION SETALTER SYSTEM ALTER SESSION UNSETALTER SYSTEM CANCEL [WORK IN] SESSIONALTER SYSTEM CLEAR SQL PLAN CACHEALTER SYSTEM CLEAR TRACESALTER SYSTEM DISCONNECT SESSIONALTER SYSTEM LOGGINGALTER SYSTEM RECLAIM DATAVOLUMEALTER SYSTEM RECLAIM LOGALTER SYSTEM RECLAIM VERSION SPACEALTER SYSTEM RECONFIGURE SERVICEALTER SYSTEM REMOVE TRACESALTER SYSTEM RESET MONITORING VIEWALTER SYSTEM SAVE PERFTRACEALTER SYSTEM SAVEPOINTALTER SYSTEM START PERFTRACEALTER SYSTEM STOP PERFTRACEALTER SYSTEM STOP SERVICEUNSET SYSTEM LICENSE ALL
Session Management StatementsCONNECTSET HISTORY SESSIONSET SCHEMASET [SESSION]UNSET [SESSION]
Transaction Management StatementsCOMMITLOCK TABLEROLLBACKSET TRANSACTION
Access Control StatementsALTER SAML PROVIDERALTER USERCREATE ROLECREATE SAML PROVIDERCREATE USERDROP ROLEDROP SAML PROVIDERDROP USERGRANTREVOKE
Data Import Export StatementsEXPORTIMPORTIMPORT FROM
Restrictions for SQL StatementsSee Also
SQL Error Codes
Table of Content
7 2012-08-21
SAP HANA Database - SQL Reference Manual
This guide describes SQL language supported by SAP HANA DB.
SAP HANA Database - SQL Reference Manual
8 2012-08-21
SQL Reference Manual
SAP HANA Database - SQL Reference Manual
9 2012-08-21
Notation
This reference use BNF (Backus Naur Form) which is the notation technique used to define programminglanguages, to describe SQL. BNF describes the syntax of a grammar using a set of production rules using a setof symbols.
Symbols used in BNF
Symbol Description
< >Angle brackets are used to surround the name of a syntactic element (BNF nontermina l ) of the SQLlanguage.
::=The defini tion operator i s used to provide defini tions of the element appeared on the left s ide ofthe operator in a production rule.
[ ]Square brackets are used to indicate optiona l elements in a formula . Optiona l elements may bespeci fied or omitted.
{ }Braces group elements in a formula . Repeti tive elements (zero or more elements ) can be speci fiedwithin brace symbols .
|The a l ternative operator indicates that the portion of the formula fol lowing the bar i s ana l ternative to the portion preceding the bar.
...The el l ips i s indicates that the element may be repeated any number of times . If el l ips i s appearsafter grouped elements speci fying that the grouped elements enclosed with braces are repeated.If el l ips i s appears a fter a s ingle element, only that element i s repeated.
!!Introduces normal Engl i sh text. This i s used when the defini tion of a syntactic element i s notexpressed in BNF.
SAP HANA Database - SQL Reference Manual
10 2012-08-21
Introduction
This chapter describes the SAP HANA Database implementation of Structured Query Language (SQL). Itexplains the characteristics of SQL, also how to manage comments and reserve words.
SQL
SQL stands for Structured Query Language. It is a standardized language for communicating with a relationaldatabase. SQL is used to retrieve, store or manipulate information in the database.
SQL statements perform the following tasks:
Schema definition and manipulationData manipulationSystem managementSession managementTransaction management
Supported Languages and Code Pages
The SAP HANA Database supports Unicode to allow the use of all languages in the Unicode Standard and 7 BitASCII code page without restriction.
Comment
You can add comments to improve readability and maintainability of your SQL statements. Comments aredelimited in SQL statements as follows:
Double hyphens "--". Everything after the double hyphen until the end of a line is considered by theSQL parser to be a comment"/*" and "*\/". This style of commenting is used to place comments on multiple lines. All text betweenthe opening "/*" and closing "*\/" is ignored by the SQL parser.
Identifiers
Syntax:
<identifier> ::= <simple_identifier> | <double_quotes><special_identifier><double_quotes> <simple_identifier> ::= <letter> [{<letter_or_digit>|<underscore>}, ...] <double_quotes> ::= " <special_identifier> ::= any character <letter> ::= A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | v | w | x | y | z <digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 <letter_or_digit> ::= <letter> | <digit> <underscore> ::= _
Identifiers are used to represent names used in SQL statement including table name, view name, synonymname, column name, index name, function name, procedure name, user name, role name, and so on. Thereare two kinds of identifiers; undelimited identifiers and delimited identifiers.
Undelimited table and column names must start with a letter and cannot contain any symbols otherthan digits or an underscore "_".Delimited identifiers are enclosed in the delimiter, double quotes, then the identifier can contain anycharacter 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 ofschema 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 representedusing two single quotation marks.
Double Quotation Mark
SAP HANA Database - SQL Reference Manual
11 2012-08-21
Double quotation marks are used to delimit identifiers and double quotation mark itself can be representedusing two double quotation marks.
SQL Reserved Words
Reserved words are words which have a special meaning to the SQL parser in the SAP HANA Database thatcannot be used as a user-defined name. Reserved words should not be used in SQL statements for schemaobject names. If necessary, you can work around this limitation by delimiting a table or column name withdouble quotation marks.
The following table lists all the current and future reserved words for the SAP HANA Database.
Table 1. Reserved Words
ALL ALTER AS BEFORE
BEGIN BOTH CASE CHAR
CONDITION CONNECT CROSS CUBE
CURRENT_CONNECTION CURRENT_DATE CURRENT_SCHEMA CURRENT_TIME
CURRENT_TIMESTAMP CURRENT_USER CURRENT_UTCDATE CURRENT_UTCTIME
CURRENT_UTCTIMESTAMP CURRVAL CURSOR DECLARE
DISTINCT ELSE ELSEIF ELSIF
END EXCEPT EXCEPTION EXEC
FOR FROM FULL GROUP
HAVING IF IN INNER
INOUT INTERSECT INTO IS
JOIN LEADING LEFT LIMIT
LOOP MINUS NATURAL NEXTVAL
NULL ON ORDER OUT
PRIOR RETURN RETURNS REVERSE
RIGHT ROLLUP ROWID SELECT
SET SQL START SYSDATE
SYSTIME SYSTIMESTAMP SYSUUID TOP
TRAILING UNION USING UTCDATE
UTCTIME UTCTIMESTAMP VALUES WHEN
WHERE WHILE WITH
SAP HANA Database - SQL Reference Manual
12 2012-08-21
Data Types
This section describes the data types used in the SAP HANA Database.
Data type specifies the characteristics of a data value. A special value of NULL is included in every data typeto indicate the absence of a value. The following table shows the built-in data types available in the SAPHANA Database.
Classification of Data Types
In the SAP HANA Database each data type can be classified by its characteristic as follows:
Table 2: Classification of data types
Classification Data Type
Datetime types DATE, TIME, SECONDDATE, TIMESTAMP
Numeric types TINYINT, SMALLINT, INTEGER, BIGINT, SMALLDECIMAL, DECIMAL, REAL, DOUBLE
Character s tring types VARCHAR, NVARCHAR, ALPHANUM, SHORTTEXT
Binary types VARBINARY
Large Object types BLOB, CLOB, NCLOB, TEXT
Datetime Types
DATE The DATE data type consists of year, month, and day information to represent a date value. Thedefault format for the DATE data type is 'YYYY-MM-DD'. YYYY represents the year, MM representsthe 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 defaultformat for the TIME data type is 'HH24:MI:SS'. HH24 represents the hour from 0 to 24, MI representsthe 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 torepresent a date with time value. The default format for the SECONDDATE data type is 'YYYY-MM-DDHH24:MI:SS'. YYYY represents the year, MM represents the month, DD represents the day, HH24represents hour, MI represents minute, and SS represents seconds. The range of date value is 0001-01-01 00:00:01 through 9999-12-31 24:00:00.
TIMESTAMP The TIMESTAMP data type consists of date and time information. Its default format is 'YYYY-MM-DDHH24:MI:SS.FF7'. FFn represents the fractional seconds where n indicates the number of digits infractional part. . The range of the timestamp value is 0001-01-01 00:00:00.0000000 through 9999-12-31 23:59:59.9999999.
For details on supported formats for datetime types, refer to Table 4, Table 5, Table 6 and Table 7 below.
Date Formats
The following date/time formats can be used when parsing a string into a date/time type and converting adate/time type value into a string value. Please note that format for Timestamp is the combination of Dateand Time with the additional support for fractional seconds.
SAP HANA Database - SQL Reference Manual
13 2012-08-21
Table 4: Supported formats for Date
Format Description Examples
YYYY-MM-DD Defaul t format 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 fourdigi ts , month has less than two digi ts , orday has less than two digi ts , then va lueswi l l be padded by one or more zeros . Forexample, a two digi t year 45 wi l l be savedas year 0045, a one digi t month 9 wi l l besaved as 09, and a one digi t day 2 wi l l besaved as 02.
INSERT INTO TBL VALUES ('1957-06-13'); INSERT INTO TBL VALUES ('1957/06/13'); INSERT INTO TBL VALUES ('1957/06-13'); INSERT INTO TBL VALUES ('1957-06/13');
YYYYMMDD ABAP Data Type, DATS format. INSERT INTO TBL VALUES ('19570613');
MON Abbreviated name of month. (JAN. ~ DEC.)
INSERT INTO TBL VALUES (TO_DATE('2040-Jan-10', 'YYYY-MON-DD')); INSERT INTO TBL VALUES (TO_DATE('Jan-10', 'MON-DD'));
MONTH Name of month. (JANUARY - DECEMBER).
INSERT INTO TBL VALUES (TO_DATE('2040-January-10', 'YYYY-MONTH-DD')); INSERT INTO TBL VALUES(TO_DATE('January-10', 'MONTH-DD'));
RM Roman numera l month (I-XII ; JAN = I).
INSERT INTO TBL VALUES (TO_DATE('2040-I-10', 'YYYY-RM-DD')); INSERT INTO TBL VALUES (TO_DATE('I-10','RM-DD'));
DDD Day of year (1-366).
INSERT INTO TBL VALUES (TO_DATE('204','DDD')); INSERT INTO TBL VALUES (TO_DATE('2001-204','YYYY-DDD'));
Time Formats
Table 5: Supported formats for Time
Format Description Examples
HH24:MI:SS Defaul t format
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 0to 59. FFF from 0 to 999. If one digi t hour, minute, second i sspeci fied, then 0 wi l l be inserted intothe va lue. For example, 9:9:9 wi l l besaved as 09:09:09. HH12 indicates 12 hour clock and HH24indicates 24 hour clock.AM or PM can be speci fied as a suffix toindicate the time va lue i s before or a fternoon.
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 past midnight (0-86399).INSERT INTO TBL VALUES (TO_TIME('12345','SSSSS'));
Timestamp Formats
Table 6: Supported formats for Timestamp
Format Description Examples
YYYY-MM-DDHH24:MI:SS.FF7
Defaul t format
FF [1..7]
Fractiona l seconds has the range 1 to 7after the FF parameter to speci fy thenumber of digi ts in the fractiona l secondportion of the date time va lue returned. Ifa digi t i s not speci fied, the defaul t va lueis used.
INSERT INTO TBL VALUES(TO_TIMESTAMP('2011-05-1112:59.999','YYYY-MM-DD HH:SS.FF3'));
Additional Formats
SAP HANA Database - SQL Reference Manual
14 2012-08-21
Table 7: Additional formats for Datetime
Format Description Example
D Day of week (1-7). TO_CHAR(CURRENT_TIMESTAMP,'D')
DAY Name of day (MONDAY - SUNDAY). TO_CHAR(CURRENT_TIMESTAMP,'DAY')
DY Abbreviated name of day (MON - SUN). TO_CHAR(CURRENT_TIMESTAMP,'DY')
MON Abbreviated month name (JAN - DEC) TO_CHAR(CURRENT_TIMESTAMP,'MON')
MONTH Ful l month name (JANUARY - DECEMBER) TO_CHAR(CURRENT_TIMESTAMP,'MONTH')
RMRoman numera l month (I - XII ; I i s forJanuary)
TO_CHAR(CURRENT_TIMESTAMP,'RM')
Q Quarter of year (1, 2, 3, 4) TO_CHAR(CURRENT_TIMESTAMP,'Q')
W Week of month (1-5). TO_CHAR(CURRENT_TIMESTAMP,'W')
WW Week of year (1-53). TO_CHAR(CURRENT_TIMESTAMP,'WW')
Supported Functions for Date/Time types
ADD_DAYSADD_MONTHSADD_SECONDSADD_YEARSCOALESCECURRENT_DATECURRENT_TIMECURRENT_TIMESTAMPCURRENT_UTCDATECURRENT_UTCTIMECURRENT_UTCTIMESTAMPDAYNAMEDAYOFMONTHDAYOFYEARDAYS_BETWEENEXTRACTGREATESTGREATESTHOURIFNULLISOWEEKLAST_DAYLEASTLOCALTOUTCMINUTEMONTHMONTHNAMENEXT_DAYNULLIFQUARTERSECONDSECONDS_BETWEENTO_CHARTO_DATETO_DATSTO_NCHARTO_TIMETO_TIMESTAMPUTCTOLOCALWEEKWEEKDAYYEAR
Numeric Types
TINYINT The TINYINT data type stores an 8-bit unsigned integer. The minimum value is 0 and the maximumvalue is 255 for TINYINT.
SMALLINT The SMALLINT data type stores a 16-bit signed integer. The minimum value is -32,768 and themaximum value is 32,767 for SMALLINT.
SAP HANA Database - SQL Reference Manual
15 2012-08-21
INTEGER The INTEGER data type stores a 32-bit signed integer. The minimum value is -2,147,483,648 and themaximum 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. Theprecision is the total number of significant digits and can range from 1 to 34.
The scale is the number of digits from the decimal point to the least significant digit and can rangefrom -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 hassignificant digits to the right of the decimal point and negative when the number has significant digitsto 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 4and scale -6.
When precision and scale are not specified, DECIMAL becomes a floating-point decimal number. Inthis 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 therange, 1~16 for precision and -369~368 for scale depending on the stored value. SMALLDECIMAL issupported only on column store.
DECIMAL and SMALLDECIMAL are floating-point types. For instance, a decimal column can store anyof 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 thespecified 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 is2.2207x10-308 and the largest negative DOUBLE value is -2.2207x10-308.
FLOAT(n) The FLOAT(n) data type specifies a 32-bit or 64-bit real number, where n specifies the number ofsignificant bits and can range between 1 and 53.
When you use the FLOAT(n) data type, if n is smaller than 25, it becomes a 32-bit REAL data type. If nis greater than or equal to 25, it then becomes a 64-bit DOUBLE data type. If n is not declared, itbecomes 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 datatypes contain ASCII character strings, NVARCHAR are used for storing Unicode character strings.
VARCHAR The VARCHAR(n) data type specifies a variable-length ASCII character string, where n indicates themaximum length and is an integer between 1 and 5000.
NVARCHAR The NVARCHAR(n) data type specifies a variable-length Unicode character set string, where nindicates the maximum length and is an integer between 1 and 5000.
ALPHANUM The ALPHANUM(n) data type specifies a variable-length character string which contains alpha-numeric characters, where n indicates the maximum length and is an integer between 1 and 127.
SHORTTEXT The SHORTTEXT(n) data type specifies veriable-length character string which supports textsearch-
SAP HANA Database - SQL Reference Manual
16 2012-08-21
features and stringsearch-features. This is not a standalone sql-type. Selecting a SHORTTEXT(n)-column yields a column of type NVARCHAR(n).
<shorttext_type> ::= SHORTTEXT '(' int_const ')' <elem_list_shorttext>
<elem_list_shorttext> ::= <elem_shorttext> [... ',' <elem_shorttext>]
<elem_shorttext> ::= <fulltext_elem> | SYNC[HRONOUS]
Binary Types
Binary types are used to store bytes of binary data.
VARBINARY The VARBINARY(n) data type is used to store binary data of a specified maximum length in bytes,where n indicates the maximum length and is an integer between 1 and 5000.
Large Object (LOB) Types
LOB (large objects) data types, CLOB, NCLOB and BLOB, are used to store a large amount of data such as textdocuments and images. The maximum size of an LOB is 2 GB.
BLOB The BLOB data type is used to store large binary data.
CLOB The CLOB data type is used to store large ASCII character data.
NCLOB The NCLOB data type is used to store a large Unicode character object.
TEXT The TEXT data type specifies which supports textsearch-features. This is not a standalone sql-type.Selecting a TEXT-column yields a column of type NCLOB.
<text_type> ::= TEXT <opt_fulltext_elem_list_text>
<opt_fulltext_elem_list_text> ::= <fulltext_elem_text> [... ',' <fulltext_elem_text>]
<fulltext_elem_text> ::= <fulltext_elem> | [SYNC[HRONOUS] | [ASYNC[HRONOUS] FLUSH [QUEUE] EVERY <n> MINUTES [[OR] AFTER <m> DOCUMENTS] ]
Syntax-rules common to TEXT and SHORTTEXT
<fulltext_elem> ::= LANGUAGE COLUMN <column_name> | LANGUAGE DETECTION '(' <str_const_list> ')' | MIME TYPE COLUMN <column_name> | FUZZY SEARCH INDEX [ON|OFF] | PHRASE INDEX RATIO [ON|OFF] | CONFIGURATION <str_const> | SEARCH ONLY [ON|OFF] | FAST PREPROCESS [ON|OFF]
LOB types are provided for storing and retrieving such large data. LOB types support the followingoperations.
The length() function returns the LOB length in bytes.LIKE can be used to search LOB columns.
The LOB types have the following restrictions:
LOB columns cannot appear in ORDER BY or GROUP BY clauses.LOB columns cannot appear in FROM clauses as a join predicate.LOB columns cannot appear in WHERE clauses as a predicate except LIKE, CONTAINS, =, or <>.LOB columns cannot appear in SELECT clauses as an aggregate function argument.LOB columns cannot appear in SELECT DISTINCT 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.
SAP HANA Database - SQL Reference Manual
17 2012-08-21
Mapping between SQL Data Type and Column Store Data Type
SQL Type Column Store Type
Integer Types TINYINT, SMALLINT, INT CS_INT
BIGINT CS_FIXED(18,0)
Approximate Types REAL CS_FLOAT
DOUBLE CS_DOUBLE
FLOAT CS_DOUBLE
FLOAT(p) CS_FLOAT, CS_DOUBLE
Decimal Types DECIMAL CS_DECIMAL_FLOAT
DECIMAL(p,s ) CS_FIXED(p-s ,s )
SMALLDECIMAL CS_SDFLOAT
Character Types VARCHAR CS_STRING,CS_ALPHANUM,CS_UNITDECFLOAT,CS_DATE,CS_TIME
NVARCHAR CS_STRING,CS_ALPHANUM,CS_UNITDECFLOAT
CLOB, NCLOB CS_STRING
ALPHANUM CS_ALPHANUM
Binary Types BLOB CS_RAW
VARBINARY CS_RAW
Date/Time Types DATE CS_DAYDATE,CS_DATE
TIME CS_SECONDTIME,CS_TIME
TIMESTAMP CS_LONGDATE,CS_DATE,CS_SECONDDATE
SECONDDATE CS_SECONDDATE
Data Type Conversion
This section describes the data type conversion allowed in SAP HANA Database.
Explicit type conversion
The type of an expression result, for example a field reference, a function on fields, or literals can beconverted using the following functions: CAST, TO_ALPHANUM, TO_BIGINT, TO_VARBINARY,TO_BLOB, TO_CLOB, TO_DATE, TO_DATS, TO_DECIMAL, TO_DOUBLE, TO_INTEGER, TO_INT,TO_NCLOB, TO_NVARCHAR, TO_REAL, TO_SECONDDATE, TO_SMALLINT, TO_TINYINT, TO_TIME,TO_TIMESTAMP, TO_VARCHAR.
Implicit type conversion
When a given set of operand/argument types does not match what an operator/function expects, atype conversion is carried out by the SAP HANA Database. This conversion only occurs if a relevantconversion is available and if it makes the operation/function executable. For instance, a comparisonof BIGINT and VARCHAR is performed by implicitly converting VARCHAR to BIGINT. The entire explicitconversions can be used for implicit conversion except for the TIME and TIMESTAMP data types. TIMEand TIMESTAMP can be converted to each other using TO_TIME(TIMESTAMP) andTO_TIMESTAMP(TIME).
Examples
Table 8: Implicit Type conversion Examples
Input Expression Transformed Expression with Implicit Conversion
BIGINT > VARCHAR BIGINT > BIGINT(VARCHAR)
BIGINT > DECIMAL DECIMAL(BIGINT) > DECIMAL
TIMESTAMP > DATE TIMESTAMP > TIMESTAMP(DATE)
DATE > TIME Error because there i s no convers ion ava i lable between DATE and TIME
In the tables below,
Boxes with "OK" means data type conversions are allowed without any checks.Boxes with "CHK" means the data type can be converted if the data is valid for the target type.Boxes with "-" indicates that data type conversion is not allowed.
The rules shown are applicable to both implicit and explicit conversion except for Time to Timestampconversion. Only explicit conversions are allowed for converting the Time data type to Timestamp using theTO_TIMESTAMP or CAST functions.
SAP HANA Database - SQL Reference Manual
18 2012-08-21
Table 9a: Data type conversion table
Target/Source
tinyint - OK OK OK OK OK OK OK OK OK OK
smallint CHK - OK OK OK OK OK OK OK OK OK
integer CHK CHK - OK OK OK OK OK OK OK OK
bigint CHK CHK CHK - OK CHK CHK CHK OK OK OK
decimal CHK CHK CHK CHK - CHK CHK CHK OK OK OK
decimal(p,s) CHK CHK CHK CHK CHK CHK CHK CHK CHK CHK OK
smalldecimal CHK CHK CHK CHK OK CHK - CHK CHK OK OK
real CHK CHK CHK CHK OK CHK CHK - OK OK OK
double CHK CHK CHK CHK CHK CHK CHK CHK - OK OK
varchar CHK CHK CHK CHK CHK CHK CHK CHK CHK - OK
nvarchar CHK CHK CHK CHK CHK CHK CHK CHK CHK CHK -
Table 9b: Data type conversion table
Target/Source
time date seconddate timestamp varchar nvarchar
time - - - - OK OK
date - - OK OK OK OK
seconddate time date - timestamp OK OK
timestamp time date seconddate - OK OK
varchar CHK CHK CHK CHK - OK
nvarchar CHK CHK CHK CHK CHK -
Table 9c: Data type conversion table
Target/Source
varbinary alphanum varchar nvarchar
varbinary - - - -
alphanum - - OK OK
varchar OK OK - OK
nvarchar OK OK CHK -
Data Type Precedence
This section describes the data type precedence implemented by the SAP HANA Database. Data typeprecedence specifies that the data type with lower precedence is converted to the data type with higherprecedence.
tinyi
nt
smal
lint
inte
ger
bigi
nt
deci
mal
deci
mal
(p,s
)
smal
ldec
imal
real
doub
le
varc
har
nvar
char
SAP HANA Database - SQL Reference Manual
19 2012-08-21
Highest TIMESTAMP
SECONDDATE
DATE
TIME
DOUBLE
REAL
DECIMAL
SMALLDECIMAL
BIGINT
INTEGER
SMALLINT
TINYINT
NCLOB
NVARCHAR
CLOB
VARCHAR
BLOB
Lowest VARBINARY
Typed Constant
A constant is a symbol that represents a specific fixed data value.
Character string contant A character string constant is enclosed in single quotation marks.
'Brian''100'
Unicode string has a similar format to character string but is preceded by an N identifier (N stands forNational Language in the SQL-92 standard). The N prefix must be uppercase.
N'abc'
SELECT 'Brian' "character string 1", '100' "character string 2", N'abc' "unicode string" 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.
123123.41.234e2
A hexadecimal number constant is a string of hexadecimal numbers and has the prefix 0x.
0x0abc
SELECT 123 "integer", 123.4 "decimal1", 1.234e2 "decimal2", 0x0abc "hexadecimal" FROM 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 quotationmarks.
X'00abcd'x'dcba00'
SELECT X'00abcd' "binary string 1", x'dcba00' "binary string 2" FROM DUMMY;
binary string 1, binary string 2
SAP HANA Database - SQL Reference Manual
20 2012-08-21
00ABCD, DCBA00
Date/Time/Timestamp constant Date, Time and Timestamp each have the following prefixes.
date'2010-01-01'time'11:00:00.001'timestamp'2011-12-31 23:59:59'
SELECT date'2010-01-01' "date", time'11:00:00.001' "time", timestamp'2011-12-31 23:59:59' "timestamp" FROM DUMMY;
date, time, timestamp 2010-01-01, 11:00:00, 2011-12-31 23:59:59.0
SAP HANA Database - SQL Reference Manual
21 2012-08-21
Predicates
A predicate is specified by combining one or more expressions, or logical operators, and returns one of thefollowing logical/truth values: TRUE, FALSE, or UNKNOWN.
Comparison Predicates
Two values are compared using comparison predicates and the comparison returns true, false, or unknown.
Syntax:
<comparison_predicate> ::= <expression> { = | != | <> | > | < | >= | <= } [ ANY | SOME| ALL ] { <expression_list> | <subquery> } <expression_list> ::= <expression>, ...
Expressions can be a simple expression such as a character, date, or number. An expression can also be ascalar subquery.
ANY, SOME - When ANY or SOME are specified, the comparison returns true if at least one value returned bythe subquery or expression_list is true. ALL - When ALL is specified, the comparison returns true if thecomparison of all values returned by the subquery or expression_list is true.
Range Predicate
A value is compared with a list of values within the provided range.
Syntax:
<range_predicate> ::= <expression1> [NOT] BETWEEN <expression2> AND <expression3>
BETWEEN ... AND ... - When a range predicate is used, it returns true if expression1 is within the rangespecified by expression2 and expression3. True will only be returned if expression2 has a lesser value thanexpression3.
In Predicate
A value is compared with a specified set of values. True will be returned if the value of expression1 is found inthe expression_list (or subquery).
Syntax:
<in_predicate> ::= <expression> [NOT] IN { <expression_list> | <subquery> }
Exists Predicate
Returns true if the subquery returns a result set that is not empty and returns false if the subquery returns anempty result set.
Syntax:
<exists_predicate> ::= [NOT] EXISTS ( <subquery> )
LIKE Predicate
The LIKE predicate is used for string comparisons. Expression1 is tested for a pattern contained inexpression2. Wildcard characters ( % ) and ( _ ) may be used in the comparison string expression2. LIKEreturns true if the pattern specified by expression2 is found.
The percentage sign (%) matches zero or more characters and underscore (_) matches exactly onecharacter. 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 usedallowing the underscore (_) or percentage sign (%) to be matched.
Syntax:
<like_predicate> ::= <expression1> [NOT] LIKE <expression2> [ESCAPE <expression3>]
NULL Predicate
SAP HANA Database - SQL Reference Manual
22 2012-08-21
When the IS NULL predicate is specified, a value can be compared with NULL. IS NULL returns true if theexpression value is NULL. If the IS NOT NULL predicate is specified, it returns true if a value is not NULL.
Syntax:
<null_predicate> ::= <expression> IS [NOT] NULL
CONTAINS Predicate
The CONTAINS predicate is used to search for text-matches to a search string in subqueries.
Syntax:
<contains_function> ::= CONTAINS '(' <contains_columns> ',' <search_string>')' | CONTAINS '(' <contains_columns> ',' <search_string> ',' <search_specifier> ')' <contains_columns> ::= '*' | <column_name> | '(' <columnlist> ')' <search_string> ::= <string_const> <search_specifier> ::= <search_type> <opt_search_specifier2_list> | <search_specifier2_list> <opt_search_specifier2_list> ::= empty | <search_specifier2_list> <search_type> ::= <exact_search> | <fuzzy_search> | <linguistic_search> <search_specifier2_list> ::= <search_specifier2> | <search_specifier2_list> ',' <search_specifier2> <search_specifier2> := <weights> | <language> <exact_search> ::= EXACT <fuzzy_search> ::= FUZZY | FUZZY '(' <float_const> ')' | FUZZY '(' <float_const> ',' <additional_params> ')' <linguistic_search> ::= LINGUISTIC <weights> ::= WEIGHT '(' <float_const_list> ')' <language> :: LANGUAGE '(' <string_const> ')' <additional_params> ::= <string_const>
search_stringThe freestyle-search-string format is used (eg. Peter "Palo Alto" OR Berlin -"SAP LABS" )
search_specifierIf the search_specifier clause is not specified EXACT is taken as default
EXACTEXACT returns true for those records where exact matches of the searchterms are found in the search-attributes
FUZZYFUZZY returns true for those records where words similar to the searchterms are found in the search-attributes (e.g. spelling errors will be ignored to a certain extent)
float_constIf float_const is omitted, then 0.8 is the default. This default can be overridden by defining parameterFUZZINESSTHRESHOLD supported by columnstore join-views
WEIGHTIf a weights list is specified, it must be the same size as the number of (expanded) columns in<contains_columns>
LANGUAGE
SAP HANA Database - SQL Reference Manual
23 2012-08-21
LANGUAGE is used during preprocessing of the search string and as a pre-search filter. Only documents whichmatch the search string and the language specified are returned.
LINGUISTICLINGUISTIC returns true for those records where word-variants of the searchterms are found in the search-attributes (e.g. searching for 'cats' will also return records which contain 'cat')
Limitations: If there are multiple CONTAINS predicates specified in the where clause of a select statement,then only one of the predicates may consist of more than one column in the <contains_columns> list
The CONTAINS-predicate works only on column store tables (simple tables and join-views)
Examples:
Exact search
select * from T where contains(column1, 'dog OR cat') -- EXACT is implicit select * from T where contains(column1, 'dog OR cat', EXACT) select * from T where contains(column1, '"cats and dogs"') -- phrase search
Fuzzy search
select * from T where contains(column1, 'catz', FUZZY(0.8))
Linguistic search:
select * from T where contains(column1, 'catz', LINGUISTIC)
Freestyle search: The freestyle-search is a search mulitple columns.
select * from T where CONTAINS( (column1,column2,column3), 'cats OR dogz', FUZZY(0.7)) select * from T where CONTAINS( (column1,column2,column3), 'cats OR dogz', FUZZY(0.7))
SAP HANA Database - SQL Reference Manual
24 2012-08-21
Operators
You can perform arithmetic operations in expressions by using operators. Operators can be used forcalculation, value comparison or to assign values.
Unary and Binary Operators
Table 10. Unary and binary operators
Operator Operation Format Description
UnaryA unary operator appl ies to one operand or as ingle va lue express ion.
operator operand
unary plusoperator(+)
unary negationoperator(-)
logica lnegation(NOT)
BinaryBinary A binary operator appl ies to two operandsor two va lue express ions .
operand1 operatoroperand2
multipl i cativeoperators ( *, / )
addi tive operators (+,- )
comparisonoperators ( =,!=,<,>,<=,>=)
logica l operators (AND, OR )
Operator Precedence
An expression can use several operators. If the number of operators is greater than one then the SAP HANADatabase will evaluate them in order of operator precedence. You can change the order of evaluation byusing parentheses, as expressions contained within parentheses are always evaluated first.
If parentheses are not used, the operators have the precedence indicated by the table below. Please note,the SAP HANA Database will evaluate operators with equal precedence from left to right within anexpression.
Table 11. SQL operator precedence
Precedence Operator Operation
Highest () parentheses
+, - unary pos i tive and negative operation
*, / multipl i cation, divi s ion
+, - addi tion, subtraction
|| concatenation
=, !=, <, >, <=, >=, IS NULL, LIKE, BETWEEN compars ion
NOT logica l negation
AND conjunction
Lowes t OR dis junction
Arithmetic Operators
You use arithmetic operators to perform mathematical operations such as adding, subtracting, multiplying,dividing and negation of numeric values.
SAP HANA Database - SQL Reference Manual
25 2012-08-21
Table 12. Arithmetic operators
Operator Description
-<express ion> Negation. If the express ion i s the NULL va lue, the resul t i s NULL.
<express ion> +<express ion>
Addition. If ei ther express ion i s the NULL va lue, the resul t i s NULL.
<express ion> -<express ion>
Subtraction. If ei ther express ion i s the NULL va lue, the res ul t i s NULL.
<express ion> *<express ion>
Multipl i cation. If ei ther express ion i s NULL, the resul t i s NULL.
<express ion> /<express ion>
Divis ion. If ei ther express ion i s NULL, or i f the s econd express ion i s 0, an error i sreturned.
String Operators
A concatenation operator combines two items such as strings, expressions or constants into one.
Table 13. Concatenation operators
Operator Description
<express ion> || <express ion>String concatenation (two vertica l bars ).If ei ther s tring i s NULL, i t returns NULL.
For VARCHAR or NVARCHAR type strings, leading or trailing spaces are kept. If either string is of data typeNVARCHAR, the result has data type NVARCHAR and is limited to 5000 characters. The maximum length forVARCHAR concatenation is also limited to 5000 characters.
Comparsion Operators
Syntax:
<comparison_operation> ::= <expression1> <comparison_operator> <expression2>
Table 14. Comparison operators
Operator Description Example
= Equa l to SELECT * FROM students WHERE id = 25;
> Greater than SELECT * FROM students WHERE id > 25;
< Less than SELECT * FROM students WHERE id < 25;
>= Greater than or equa l to SELECT * FROM students WHERE id >= 25;
<= Less than or equa l to SELECT * FROM students WHERE id <= 25;
!=, <> Not equa lSELECT * FROM students WHERE id != 25; SELECT * FROM students WHERE id <> 25;
Logical Operators
Search conditions can be combined using AND or OR operators. You can also negate them using the NOToperator.
Table 15. Logical operators
Operator Syntax Description
AND
WHEREcondition1ANDcondition2
When us ing AND, the combined condi tion i s TRUE i f both condi tions are TRUE,FALSE i f ei ther condi tion i s FALSE, and UNKNOWN otherwise.
OR
WHEREcondition1ORcondition2
When us ing OR, the combined condi tion i s TRUE i f ei ther condi tion i s TRUE,FALSE i f both condi tions are FALSE, and UNKNOWN otherwise.
NOTWHERE NOTcondition
The NOT operator i s placed before a condi tion to negate the condi tion. The NOTcondition i s TRUE i f condi tion i s FALSE, FALSE i f condi tion i s TRUE, and UNKNOWNif condi tion i s UNKNOWN.
Set Operators
The operators described in this section perform set operations on the results of two or more queries.
SAP HANA Database - SQL Reference Manual
26 2012-08-21
Table 16. Set operators
Operator Returned Value
UNION Combines the resul ts of two or more select s tatements or query expres s ions
UNIONALL
Combines the resul ts of two or more select s tatements or query expres s ions , including a l ldupl icate rows .
INTERSECTCombines the resul ts of two or more select s tatements or query expres s ions , and returns a l lcommon rows .
EXCEPT Takes output from the fi rs t query and then removes rows selected by the second query.
SAP HANA Database - SQL Reference Manual
27 2012-08-21
Expressions
An expression is a clause that can be evaluated to return values.
Syntax:
<expression> ::= <case_expression> | <function_expression> | <aggregate_expression> | (<expression> ) | ( <subquery> ) | - <expression> | <expression> <operator> <expression> | <variable_name> | <constant> | [<correlation_name>.]<column_name>
Case Expressions
A case expression allows the user to use IF ... THEN ... ELSE logic without using procedures in SQL statements.
Syntax:
<case_expression> ::= CASE <expression> WHEN <expression> THEN <expression>, ... [ ELSE <expression>] { END | END CASE }
If the expression following the CASE statement is equal to the expression following the WHEN statement,then the expression following the THEN statement is returned. Otherwise the expression following the ELSEstatement is returned if it exists.
Function Expressions
SQL built-in functions can be used as an expression.
Syntax:
<function_expression> ::= <function_name> ( <expression>, ... )
Aggregate Expressions
An aggregate expression uses an aggregate function to calculate a single value from the values of multiplerows in a column.
Syntax:
<aggregate_expression> ::= COUNT(*) | <agg_name> ( [ ALL | DISTINCT ] <expression> ) <agg_name> ::= COUNT | MIN | MAX | SUM | AVG | STDDEV | VAR
Aggregatename
Description
COUNTCounts the number of rows returned by a query. COUNT(*) returns the number of rows , regardlessof the va lue of those rows and including dupl icate va lues . COUNT(<express ion>) returns thenumber of non-NULL va lues for that express ion returned by the query.
MIN Returns the minimum va lue of express ion.
MAX Returns the maximum va lue of express ion.
SUM Returns the sum of express ion.
AVG Returns the ari thmetica l mean of express ion.
STDDEV Returns the s tandard deviation of given express ion as the square root of VARIANCE function.
VAR Returns the variance of express ion as the square of s tandard deviation.
Subqueries in Expressions
SAP HANA Database - SQL Reference Manual
28 2012-08-21
A subquery is a SELECT statement enclosed in parentheses. The SELECT statement can contain one and onlyone select list item. When used as an expression a scalar subquery is allowed to return only zero or one value.
Syntax:
<scalar_subquery_expression> ::= (<subquery>)
Within the SELECT list of the top level SELECT, or in the SET clause of an UPDATE statement, you can use ascalar subquery anywhere that you can use a column name. However, scalar_subquery cannot be used insideGROUP BY clause.
Example:
For example, the following statement returns the number of employees in each department, grouped bydepartment name:
SELECT DepartmentName, COUNT(*), 'out of', (SELECT COUNT(*) FROM Employees) FROM Departments AS D, Employees AS E WHERE D.DepartmentID = E.DepartmentID GROUP BY DepartmentName;
SAP HANA Database - SQL Reference Manual
29 2012-08-21
SQL Functions
Introduction
This chapter describes SQL Functions that are provided by SAP HANA Database.
Data Type Conversion FunctionsDateTime FunctionsNumber FunctionsString FunctionsMiscellaneous Functions
Data Type Conversion Functions
Data type conversion functions are used to convert arguments from one data type to another, or to testwhether a conversion is possible.
CAST
Syntax
CAST (expression AS data_type)
Syntax Elements
expression - The expression to be converted. data type - The target data type. TINYINT | SMALLINT |INTEGER | BIGINT | DECIMAL | SMALLDECIMAL | REAL | DOUBLE | ALPHANUM | VARCHAR | NVARCHAR |DAYDATE | DATE | TIME | SECONDDATE | TIMESTAMP
Description
Returns the value of an expression converted to a supplied data type.
Example
SELECT CAST (7 AS VARCHAR) "cast" FROM DUMMY; cast 7
TO_ALPHANUM
Syntax
TO_ALPHANUM (value)
Description
Converts a given value to an ALPHANUM data type.
Example
SELECT TO_ALPHANUM ('10') "to alphanum" FROM DUMMY; to alphanum 10
TO_BIGINT
Syntax
TO_BIGINT (value)
Description
Converts a value to a BIGINT data type.
SAP HANA Database - SQL Reference Manual
30 2012-08-21
Example
SELECT TO_BIGINT ('10') "to bigint" FROM DUMMY; to bigint 10
TO_BINARY
Syntax
TO_BINARY (value)
Description
Converts a value to a BINARY data type.
Example
SELECT TO_BINARY ('abc') "to binary" FROM DUMMY; to binary 616263
TO_BLOB
Syntax
TO_BLOB (value)
Description
Converts a value to a BLOB data type. The argument value must be a binary string.
Example
SELECT TO_BLOB (TO_BINARY('abcde')) "to blob" FROM DUMMY; to blob abcde
TO_CHAR
Syntax
TO_CHAR (value [, format])
Description
Converts a given value to a CHAR character data type. If the format specifier is omitted, the conversion isperformed 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
SAP HANA Database - SQL Reference Manual
31 2012-08-21
Converts a value to a CLOB data type.
Example
SELECT TO_CLOB ('TO_CLOB converts the value to a CLOB data type') "to clob" FROM DUMMY; to clob TO_CLOB converts the value to a CLOB data type
TO_DATE
Syntax
TO_DATE (d [, format])
Description
Converts a date string d into a DATE data type. If the format specifier is omitted, the conversion is performedusing the date format model as explained in Date Formats.
Example
SELECT TO_DATE('2010-01-12', 'YYYY-MM-DD') "to date" FROM DUMMY; to date 2010-01-12
TO_DATS
Syntax
TO_DATS (d)
Description
Converts a date string d into an ABAP DATE string with format 'YYYYMMDD'.
Example
SELECT TO_DATS ('2010-01-12') "abap date" FROM DUMMY; abap date 20100112
TO_DECIMAL
Syntax
TO_DECIMAL (value [, precision, scale])
Description
Converts the value to a DECIMAL data type.
The precision is the total number of significant digits and can range from 1 to 34.
The scale is the number of digits from the decimal point to the least significant digit and can range from -
6,111 to 6,176. This means that the scale specifies the range of the exponent in the decimal number from 10-
6111 to 106176. If the scale is not specified, it defaults to 0. Scale is positive when the number has significantdigits to the right of the decimal point, and negative when the number has significant digits to the left of thedecimal 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 scaledepending on the stored value.
SAP HANA Database - SQL Reference Manual
32 2012-08-21
Example
SELECT TO_DECIMAL(7654321.888888, 10, 3) "to decimal" FROM DUMMY
to decimal 7654321.889
TO_DOUBLE
Syntax
TO_DOUBLE (value)
Description
Converts a value to a DOUBLE (double precision) data type.
Example
SELECT 3*TO_DOUBLE ('15.12') "to double" FROM DUMMY; to double 45.36
TO_INT
Syntax
TO_INT (value)
Description
Converts the value to an INTEGER data type.
Example
SELECT TO_INT('10') "to int" FROM DUMMY; to int 10
TO_INTEGER
Syntax
TO_INTEGER (value)
Description
Converts the value to an INTEGER data type.
Example
SELECT TO_INTEGER ('10') "to int" FROM DUMMY; to int 10
TO_NCHAR
Syntax
TO_NCHAR (value [, format])
Description
Converts the value to a NCHAR unicode character data type. If the format specifier is omitted, the conversion
SAP HANA Database - SQL Reference Manual
33 2012-08-21
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 type.
Example
SELECT TO_NCLOB ('TO_NCLOB converts the value to a NCLOB data type') "to nclob" FROM 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 type. If the format specifier is omitted, theconversion is performed using the date format model as explained in Date Formats.
Example
SELECT TO_NVARCHAR(TO_DATE('2009/12/31'), 'YY-MM-DD') "to nchar" FROM DUMMY; to nchar 09-12-31
TO_REAL
Syntax
TO_REAL (value)
Description
Converts a value to a REAL (single precision) data type.
Example
SELECT 3*TO_REAL ('15.12') "to real" FROM DUMMY; to real 45.36000061035156
TO_SECONDDATE
Syntax
TO_SECONDDATE (d [, format])
SAP HANA Database - SQL Reference Manual
34 2012-08-21
Description
Converts a date string d into a SECONDDATE data type. If the format specifier is omitted, the conversion isperformed 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 seconddate" FROM DUMMY; to seconddate 2010-01-11 13:30:00.0
TO_SMALLDECIMAL
Syntax
TO_SMALLDECIMAL (value)
Description
Converts the value to a SMALLDECIMAL data type.
Example
SELECT TO_SMALLDECIMAL(7654321.89) "to smalldecimal" FROM DUMMY;
to smalldecimal 7654321.89
TO_SMALLINT
Syntax
TO_SMALLINT (value)
Description
Converts the value to a SMALLINT data type.
Example
SELECT TO_SMALLINT ('10') "to smallint" FROM DUMMY; to smallint 10
TO_TIME
Syntax
TO_TIME (t [, format])
Description
Converts a time string t into the TIME data type. If the format specifier is omitted, the conversion isperformed 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
SAP HANA Database - SQL Reference Manual
35 2012-08-21
Syntax
TO_TIMESTAMP (d [, format])
Description
Converts a date string d into the TIMESTAMP data type. If the format specifier is omitted, the conversion isperformed 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 type. If the format specifier is omitted, the conversion isperformed 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
SAP HANA Database - SQL Reference Manual
36 2012-08-21
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.
SAP HANA Database - SQL Reference Manual
37 2012-08-21
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 GreenwichMean Time (GMT).
Example
SELECT CURRENT_UTCDATE "Coordinated Universal Date" FROM DUMMY; Coordinated Universal Time 2010-01-11
CURRENT_UTCTIME
Syntax
CURRENT_UTCTIME
Description
SAP HANA Database - SQL Reference Manual
38 2012-08-21
Returns the current UTC time.
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 timestamp.
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)
SAP HANA Database - SQL Reference Manual
39 2012-08-21
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', 'YYYY-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 EXTRACT (YEAR FROM TO_DATE ('2010-01-04', 'YYYY-MM-DD')) "extract" FROM DUMMY; 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
SAP HANA Database - SQL Reference Manual
40 2012-08-21
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 time t.
Example
SELECT MINUTE ('12:34:56') "minute" FROM DUMMY; minute 34
SAP HANA Database - SQL Reference Manual
41 2012-08-21
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
SAP HANA Database - SQL Reference Manual
42 2012-08-21
2010-01-01 16:34:19.894
QUARTER
Syntax
QUARTER (d, [, start_month ])
Description
Returns the numerical year quarter of date d. The first quarter starts in the month specified by start_month.If start_month is not specified the first quarter is assumed to begin in January.
Example
SELECT QUARTER (TO_DATE('2012-01-01', 'YYYY-MM-DD'), 2) "quarter" FROM DUMMY; quarter 2011-Q4
SECOND
Syntax
SECOND (t)
Description
Returns an integer representation of the second for time t.
Example
SELECT SECOND ('12:34:56') "second" FROM DUMMY; second 56
SECONDS_BETWEEN
Syntax
SECONDS_BETWEEN (d1, d2)
Description
Computes the number of seconds between date arguments d1 and d2, which is semantically equal to d2 - d1.
Example
SELECT SECONDS_BETWEEN ('2009-12-05', '2010-01-05') "seconds between" FROM DUMMY; Seconds between 2678400
UTCTOLOCAL
Syntax
UTCTOLOCAL (t, timezone)
Description
Convert the UTC(GMT) time t to the local time in a timezone
Example
SAP HANA Database - SQL Reference Manual
43 2012-08-21
SELECT UTCTOLOCAL (TO_TIMESTAMP('2012-01-01 01:00:00', 'YYYY-MM-DD HH24:MI:SS'), 'EST') "utctolocal" FROM DUMMY; utctolocal 2011-12-31 20:00:00.0
WEEK
Syntax
WEEK (d)
Description
Returns the week number of date d.
Please also see ISOWEEK
Example
SELECT WEEK (TO_DATE('2011-05-30', 'YYYY-MM-DD')) "week" FROM DUMMY; week 23
WEEKDAY
Syntax
WEEKDAY (d)
Description
Returns an integer representation of the day of the week for date d. The return value ranges from 0 to 6,representing Monday(0) through to Sunday(6).
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 numericvalues. When strings with numeric characters are provided as inputs implicit conversion from a string to anumber is performed automatically before results are computed.
ABS
SAP HANA Database - SQL Reference Manual
44 2012-08-21
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 radians, of the numeric argument n between -1 and 1.
Example
SELECT ASIN (0.5) "asin" FROM DUMMY; asin 0.5235987755982989
ATAN
Syntax
ATAN (n)
Description
Returns the arc-tangent, in radians, of the numeric argument n. The range of n is unlimited.
Example
SELECT ATAN (0.5) "atan" FROM DUMMY; atan 0.4636476090008061
SAP HANA Database - SQL Reference Manual
45 2012-08-21
ATAN2
Syntax
ATAN2 (n, m)
Description
Returns the arc-tangent, in radians, of the ratio of two numbers n and m. This produces the same result asATAN(n/m).
Example
SELECT ATAN2 (1.0, 2.0) "atan2" FROM DUMMY; atan2 0.4636476090008061
BINTOHEX
Syntax
BINTOHEX (expression)
Description
Converts a binary value to a hexadecimal value.
Example
SELECT BINTOHEX('AB') "bintohex" FROM DUMMY; bintohex 4142
BITAND
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-negativeintegers. The BITAND function returns a result with BIGINT type.
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;
SAP HANA Database - SQL Reference Manual
46 2012-08-21
ceiling 15
COS
Syntax
COS (n)
Description
Returns the cosine of the angle, in radians, of the argument n.
Example
SELECT COS (0.0) "cos" FROM DUMMY; cos 1.0
COSH
Syntax
COSH (n)
Description
Computes the hyperbolic cosine of the argument n.
Example
SELECT COSH (0.5) "cosh" FROM DUMMY; cosh 1.1276259652063807
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 argument n.
Example
SAP HANA Database - SQL Reference Manual
47 2012-08-21
SELECT EXP (1.0) "exp" FROM DUMMY; exp 2.718281828459045
FLOOR
Syntax
FLOOR (n)
Description
Returns the largest integer not greater than the numeric argument n.
Example
SELECT FLOOR (14.5) "floor" FROM DUMMY; floor 14
GREATEST
Syntax
GREATEST (n1 [, n2]...)
Description
Returns the greatest value among the arguments: n1, n2, ...
Example
SELECT GREATEST ('aa', 'ab', 'ba', 'bb') "greatest" FROM DUMMY; greatest bb
HEXTOBIN
Syntax
HEXTOBIN (value)
Description
Converts a hexadecimal value to a binary value.
Example
SELECT HEXTOBIN ('1a') "hextobin" FROM DUMMY; hextobin 1A
LEAST
Syntax
LEAST (n1 [, n2]...)
Description
Returns the least value among the arguments: n1, n2...
Example
SAP HANA Database - SQL Reference Manual
48 2012-08-21
SELECT LEAST('aa', 'ab', 'ba', 'bb') "least" FROM DUMMY; least aa
LN
Syntax
LN (n)
Description
Returns the natural logarithm of the argument n.
Example
SELECT LN (9) "ln" FROM DUMMY; ln 2.1972245773362196
LOG
Syntax
LOG (b, n)
Description
Returns the natural logarithm of a number n base b. Base b must be a positive value greater than 1 and nmust 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 greater than 0 and n is less than d, then n is returned.If n is less than 0 and n is greater than d, then n is returned.In other case that those mentioned above, remainder of the absolute value of n divided by theabsolute value of d is used to calculate remainder. If n is less than 0, then the returned remainderfrom MOD is a negative number, and if n is greater than 0, then the returned remainder from MOD isa positive number.
Example
SELECT MOD (15, 4) "modulus" FROM DUMMY; modulus
SAP HANA Database - SQL Reference Manual
49 2012-08-21
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 anegative value, and 0 if n is equal to zero.
Example
SELECT SIGN (-15) "sign" FROM DUMMY; sign -1
SIN
Syntax
SAP HANA Database - SQL Reference Manual
50 2012-08-21
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
SAP HANA Database - SQL Reference Manual
51 2012-08-21
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
SAP HANA Database - SQL Reference Manual
52 2012-08-21
CONCAT
Syntax
CONCAT (str1, str2)
Description
Returns a combined string consisting of str1 followed by str2. The concatenation operator (||) is identical tothis 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 Large Object (LOB) types, this function returns the lengthof the object in bytes.
Example
SAP HANA Database - SQL Reference Manual
53 2012-08-21
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 withinhaystack.
Example
SELECT LOCATE ('length in char', 'char') "locate" FROM DUMMY; Locate 11
SELECT LOCATE ('length in char', 'length') "locate" FROM DUMMY; Locate 1
SELECT LOCATE ('length in char', 'zchar') "locate" FROM DUMMY; Locate 0
LOWER
Syntax
LOWER(str)
Description
Converts all characters in string str to lowercase.
Note:The LOWER function is identical to the LCASE function.
Example
SELECT LOWER ('AnT') "lower" FROM DUMMY; lower ant
LPAD
Syntax
LPAD (str, n [, pattern])
Description
Pads the start of string str with spaces to make a string of n characters in length. If the pattern argument isprovided 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;
SAP HANA Database - SQL Reference Manual
54 2012-08-21
lpad 123451234512end
LTRIM
Syntax
LTRIM (str [, remove_set])
Description
Returns string str, trimmed of all leading spaces. If remove_set is specified, LTRIM removes all the characterscontained in this set from the start of string str. This process continues until a character not the inremove_set is reached.
Note:remove_set is treated as a set of characters and not as a search string.
Example
SELECT LTRIM ('babababAabend','ab') "ltrim" FROM DUMMY; ltrim Aabend
NCHAR
Syntax
NCHAR (n)
Description
Returns the Unicode character with the integer code number n.
Example
SELECT NCHAR (65) "nchar" FROM DUMMY; nchar A
REPLACE
Syntax
REPLACE (original_string, search_string, replace_string)
Description
Searches in original_string for all occurrences of search_string and replaces them with replace_string.
If original_string is an empty string, then the result will be an empty string.If two overlapping substrings match the search_string in the original_string, then only the firstoccurrence will be replaced.If original_string does not contain any occurrence of search_string, then original_string will bereturned 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
SAP HANA Database - SQL Reference Manual
55 2012-08-21
Syntax
RIGHT(str, n)
Description
Returns the rightmost n characters/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. If the pattern argument isprovided 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, trimmed of all trailing spaces. If remove_set is specified, RTRIM removes all the characterscontained in this set from the end of string str. This process continues until a character not the in remove_setis reached.
Note:remove_set is treated as a set of characters and not as a search string.
Example
SELECT RTRIM ('endabAabbabab','ab') "rtrim" FROM DUMMY; rtrim endabA
SUBSTR_AFTER
Syntax
SUBSTR_AFTER (str, pattern)
Description
Returns a substring of string str that follows the first occurrence of the pattern argument.
If str does not contain the pattern substring, then an empty string is returned.
SAP HANA Database - SQL Reference Manual
56 2012-08-21
If pattern is an empty string, then str is returned.If str or pattern is NULL, then NULL is returned.
Example
SELECT SUBSTR_AFTER ('Hello My Friend','My ') "substr after" FROM DUMMY; substr after Friend
SUBSTR_BEFORE
Syntax
SUBSTR_BEFORE (str, pattern)
Description
Returns a substring of string str before the first occurrence of the pattern argument in the target string.
If str does not contain the pattern substring, then an empty string is returned.If pattern is an empty string, then str is returned.If str or pattern is NULL, then NULL is returned.
Example
SELECT SUBSTR_BEFORE ('Hello My Friend','My') "substr before" FROM DUMMY; substr before Hello
SUBSTRING
Syntax
SUBSTRING (str, start_position [, string_length])
Description
Returns a substring of string str starting from start_position within the string. SUBSTRING can return theremaining part of a string from the start_position or optionally, a number of characters set by thestring_length parameter.
If start_position is less than 0, then it is considered as 1.If string_length is less than 1, then an empty string is returned.
Example
SELECT SUBSTRING ('1234567890',4,2) "substring" FROM DUMMY; substring 45
TRIM
Syntax
TRIM ([[LEADING | TRAILING | BOTH] trim_char FROM] str )
Description
Returns string str after removing leading and trailing spaces. The trimming operation is carried out eitherfrom the start (LEADING), end (TRAILING) or both(BOTH) ends of string str.
If either str or trim_char are a null values, then a NULL is returned.If no options are specified, TRIM removes both the leading and trailing substring trim_char from stringstr.If trim_char is not specified, then a single blank space is used.
SAP HANA Database - SQL Reference Manual
57 2012-08-21
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 characters in string str to uppercase.
Note:The UCASE function is identical to the UPPER function.
Example
SELECT UCASE ('Ant') "ucase" FROM DUMMY; ucase ANT
UNICODE
Syntax
UNICODE(c)
Description
Returns an integer containing the Unicode code point of the first character in the string, or NULL if the firstcharacter is not a valid encoding.
Example
SELECT UNICODE ('#') "unicode" FROM DUMMY; unicode 35
UPPER
Syntax
UPPER (str)
Description
Converts all characters in string str to uppercase.
Note:The UPPER function is identical to the UCASE function.
Example
SELECT UPPER ('Ant') "uppercase" FROM DUMMY; uppercase ANT
SAP HANA Database - SQL Reference Manual
58 2012-08-21
ANT
Miscellaneous Functions
COALESCE
Syntax
COALESCE (expression_list)
Description
Returns the first non-NULL expression from a list. At least two expressions must be contained inexpression_list, and all expressions must be comparable. The result will be NULL if all the arguments areNULL.
Example
CREATE TABLE coalesce_example (ID INT PRIMARY KEY, A REAL, B REAL); INSERT INTO coalesce_example VALUES(1, 100, 80); INSERT INTO coalesce_example VALUES(2, NULL, 63); INSERT INTO coalesce_example VALUES(3, NULL, NULL);
SELECT id, a, b, COALESCE (a, b*1.1, 50.0) "coalesce" FROM coalesce_example;
ID A B coalesce
1 100.0 80.0 100.0
2 NULL 63.0 69.30000305175781
3 NULL NULL 50.0
CURRENT_CONNECTION
Syntax
CURRENT_CONNECTION
Description
Returns the id of the current connection.
Example
SELECT CURRENT_CONNECTION "current connection" FROM DUMMY; current connection 2
CURRENT_SCHEMA
Syntax
CURRENT_SCHEMA
Description
Returns a string containing the current schema name.
Example
SELECT CURRENT_SCHEMA "current schema" FROM DUMMY; current schema SYSTEM
CURRENT_USER
SAP HANA Database - SQL Reference Manual
59 2012-08-21
Syntax
CURRENT_USER
Description
Returns the current user name at the current statement context. This will be user name which is currently atthe 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 return multiple levels of aggregations in a singleresult set. GROUPING_ID returns an integer value to identify which grouping set each row belongs to. Eachcolumn in GROUPING_ID must be an element of the GROUPING SETS.
GROUPING_ID is assigned by converting the bit vector generated from GROUPING SETS to a decimal numberby treating the bit vector as a binary number. When a bit vector is composed, 0 is assigned to each columnspecified in the GROUPING SETS and 1 otherwise in the order it appears in the GROUPING SETS. By treatingthe bit vector as a binary number, this function returns an integer value as the output.
Example
SELECT customer, year, product, SUM(sales), GROUPING_ID(customer, year, product) FROM guided_navi_tab GROUP BY GROUPING SETS ( (customer, year, product), (customer, year), (customer, product), (year, product), (customer), (year), (product));
SAP HANA Database - SQL Reference Manual
60 2012-08-21
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.
SAP HANA Database - SQL Reference Manual
61 2012-08-21
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 DUMMY;
map Two
SELECT MAP(99, 0, 'Zero', 1, 'One', 2, 'Two', 3, 'Three', 'Default') "map" FROM DUMMY;
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 canbe set by the client are 'APPLICATION', 'APPLICATIONUSER', and 'TRACEPROFILE'.
Session variables can be defined or modified using SET [SESSION] <variable_name> = <value> command, andunset using UNSET [SESSION] <variable_name>.
SESSION_CONTEXT returns an NVARCHAR with a maximum length of 512 characters.
Example
To read session variables use:
SAP HANA Database - SQL Reference Manual
62 2012-08-21
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
SAP HANA Database - SQL Reference Manual
63 2012-08-21
SQL Statements
This chapter describes the SQL statements that are supported by the SAP HANA Database.
Schema Definition and Manipulation StatementsData Manipulation StatementsSystem Management StatementsSession Management StatementsTransaction Management StatementsAccess Control StatementsData Import Export Statements
Schema Definition and Manipulation Statements
ALTER AUDIT POLICY
Syntax
ALTER AUDIT POLICY <policy_name> <audit_mode>
Syntax Elements
<policy_name> ::= <identifier>
The name of the audit policy to be altered.
<audit_mode> ::= ENABLE | DISABLE
The audit mode enables or disables the audit policy.
ENABLEEnables the audit policy.
DISABLEDisables the audit policy.
Description
The ALTER AUDIT POLICY statement enables or disables an audit policy. <policy_name> must specify anexisting audit policy.
Only database users having the system privilege AUDIT ADMIN are allowed to alter an audit policy. Eachdatabase user that has this privilege can alter any audit policy, regardless of if they are the creator of thepolicy.
A newly created audit policy is disabled by default and does not cause any auditing to occur. Therefore theaudit policy has to be enabled to make its audit actions take effect.
An audit policy can be disabled and enabled as often as required.
Configuration Parameters
The following configuration parameters for auditing are stored in global.ini, in the section on auditingconfiguration:
global_auditing_state ( 'true' / 'false' )Regardless of the number of enabled audit policies, auditing will only occur if the global_auditing_stateconfiguration 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_pathSpecifies the file path where the CSVTEXTFILE should be stored.
These parameters can be selected in monitoring view M_INIFILE_CONTENTS if the current user has the
SAP HANA Database - SQL Reference Manual
64 2012-08-21
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 database system configuration parameters
Only database users with system privilege CATALOG READ, DATA ADMIN or INIFILE ADMIN can view thecontent of the M_INIFILE_CONTENTS view. For all other database users this view will be empty.
Example
For this example you need to first create an audit policy called priv_audit using the following statement:
CREATE AUDIT POLICY priv_audit AUDITING SUCCESSFUL GRANT PRIVILEGE, REVOKE PRIVILEGE, GRANT ROLE, REVOKE ROLE LEVEL CRITICAL;
Now you can enable this audit policy with:
ALTER AUDIT POLICY priv_audit ENABLE;
You can also disable the same audit policy with:
ALTER AUDIT POLICY priv_audit DISABLE;
ALTER FULLTEXT INDEX
Syntax
ALTER FULLTEXT INDEX <index_name> <alter_fulltext_index_option>
Syntax Elements
<index_name> ::= <identifier>
The identifier of the fulltext index to be altered.
<alter_fulltext_index_option> ::= <fulltext_parameter_list> | <queue_command> QUEUE
Specifies whether the parameters of the fulltext index or the state of the fulltext index queue should bechanged. The latter is only possible for an asynchronous explicit fulltext index.
<fulltext_parameter_list> ::= <fulltext_parameter> [, ...]
A list of fulltext index parameters that are to be changed.
<fulltext_parameter> ::= FUZZY SEARCH INDEX <on_off> | PHRASE INDEX RATIO <index_ratio> | <change_tracking_elem>
<on_off> ::= ON | OFF
FUZZY SEARCH INDEXUse a fuzzy search index.
PHRASE INDEX RATIOSpecifies the phrase index ratio.
<index_ratio> ::= <float_literal>
Specifies the percentage of the phrase index ratio, the value used must be between 0.0 and 1.0
<change_tracking_elem> ::= SYNC[HRONOUS] | ASYNC[HRONOUS] [FLUSH [QUEUE] <flush_queue_elem>]
SYNC[HRONOUS]Changes the fulltext index to synchronous mode.
ASYNC[HRONOUS]
SAP HANA Database - SQL Reference Manual
65 2012-08-21
Changes the fulltext index to asynchronous mode.
<flush_queue_elem> ::= EVERY <integer_literal> MINUTES | AFTER <integer_literal> DOCUMENTS | EVERY <integer_literal> MINUTES OR AFTER <integer_literal> DOCUMENTS
When using an asynchronous index you use the flush_queue_elem to specify when to update the fulltextindex.
<queue_command> ::= FLUSH | SUSPEND | ACTIVATE
FLUSHUpdate the fulltext index with the documents in the queue which have already been processed.
SUSPENDSuspends the fulltext index processing queue.
ACTIVATEActivates the fulltext index processing queue.
Description
With this command you can either change the parameters of a fulltext index or the state of an indexprocessing queue. The queue is a mechanism used to enable a fulltext index to operate in asynchronousmanner, i.e. inserts are not blocked until a document is processed.
The ALTER FULLTEXT INDEX <index_name> <fulltext_elem_list> statement changes the parameters of afulltext index.
The ALTER FULLTEXT INDEX <index_name> <queue_parameters> statement changes the processing queuestate 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 isturned 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 <index_name> REBUILD
Syntax Elements
<index_name>::= <identifier>
Specifies the name of the index to be rebuilt.
Description
The ALTER INDEX statement rebuilds an index.
Example
The following example rebuilds the idx index.
ALTER INDEX idx REBUILD;
SAP HANA Database - SQL Reference Manual
66 2012-08-21
ALTER SEQUENCE
Syntax
ALTER SEQUENCE <sequence_name> [<alter_sequence_parameter_list>] [RESET BY <reset_by_subquery>]
Syntax Elements
<sequence_name> ::= <identifier>
The name of the sequence to be altered.
<alter_sequence_parameter_list> ::= <alter_sequence_parameter>, ...
<alter_sequence_parameter> ::= <sequence_parameter_restart_with> | <basic_sequence_parameter>
<sequence_parameter_restart_with> ::= RESTART WITH <restart_value>
<basic_sequence_parameter> ::= INCREMENT BY <increment_value> | MAXVALUE <maximum_value> | NO MAXVALUE | MINVALUE <minimum_value> | NO MINVALUE | CYCLE | NO CYCLE
RESTART WITHThe starting value of the sequence. If you do not specify a value for the RESTART WITH clause, the currentvalue of the sequence is used.
<restart_value> ::= <integer_literal>
An integer value between 0 and 4611686018427387903 which will be the first value provided by thesequence generator.
INCREMENT BYThe sequence increment.
<increment_value> ::= <integer_literal>
An integer value which will be used to increment or decrement the sequence value.
MAXVALUEDefines the maximum value that can be generated by the sequence.
<maximum_value> ::= <integer_literal>
A positive integer which defines the maximum value generated by the sequence. The maximum value mustbe between 0 and 4611686018427387903.
NO MAXVALUEWhen the NO MAXVALUE directive is used the maximum value for an ascending sequence will be4611686018427387903 and the maximum value for a descending sequences will be -1.
MINVALUEDefines the minimum value that can be generated by the sequence.
<minimum_value> ::= <integer_literal>
A positive integer which defines the minimum value generated by the sequence. The minimum value must bebetween 0 and 4611686018427387903.
NO MINVALUEWhen the NO MINVALUE directive is used, the minimum value for an ascending sequence is 1 and theminimum value for a descending is -4611686018427387903.
CYCLEWhen the CYCLE directive is used the sequence number will be restarted after it reaches its maximum orminimum value.
SAP HANA Database - SQL Reference Manual
67 2012-08-21
NO CYCLEWhen the NO CYCLE directive is used the sequence number will not be restarted after it reaches its maximumor minimum value.
<reset_by_subquery> ::= <subquery>
During a restart of the database, the system automatically executes the RESET BY statement and thesequence value is restarted with the value determined from the RESET BY subquery.
For details about subqueries please see Subquery
Description
The ALTER SEQUENCE statement is used to alter the parameters of a sequence generator.
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 table r, with a column a. You then change the reset-by subquery ofsequence 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 <table_name> { <add_column_clause> | <drop_column_clause> | <alter_column_clause> | <add_primary_key_clause> | <drop_primary_key_clause> | <preload_clause> | <table_conversion_clause> | <move_clause> | <add_range_partition_clause> | <move_partition_clause> | <drop_range_partition_clause> | <partition_by_clause> | <disable_persistent_merge_clause> | <enable_persistent_merge_clause> | <enable_delta_log> | <disable_delta_log> | <enable_automerge> | <disable_automerge> }
Syntax Elements
<table_name> ::= [<schema_name>.]<identifier> <add_column_clause> ::= ADD ( <column_definition> [<column_constraint>], ... ) <drop_column_clause> ::= DROP ( <column_name>, ... ) <alter_column_clause> ::= ALTER ( <column_definition> [<column_constraint>], ... ) <column_definition> ::= <column_name> <data_type> [<column_store_data_type>] [<ddic_data_type>] [DEFAULT <default_value>] [GENERATED ALWAYS AS <expression>]
SAP HANA Database - SQL Reference Manual
68 2012-08-21
<column_constraint> ::= NULL | NOT NULL | UNIQUE [BTREE | CPBTREE] | PRIMARY KEY [BTREE | CPBTREE] <column_name> ::= <identifier> <data_type> ::= DATE | TIME | SECONDDATE | TIMESTAMP | TINYINT | SMALLINT | INTEGER | BIGINT | SMALLDECIMAL | DECIMAL | REAL | DOUBLE | VARCHAR | NVARCHAR | ALPHANUM | SHORTTEXT | VARBINARY | BLOB | CLOB | NCLOB | TEXT <column_store_data_type> ::= CS_ALPHANUM | CS_INT | CS_FIXED | CS_FLOAT | CS_DOUBLE | CS_DECIMAL_FLOAT | CS_FIXED(p-s, s) | CS_SDFLOAT | CS_STRING | CS_UNITEDECFLOAT | CS_DATE | CS_TIME | CS_FIXEDSTRING | CS_RAW | CS_DAYDATE | CS_SECONDTIME | CS_LONGDATE | CS_SECONDDATE <ddic_data_type> ::= DDIC_ACCP | DDIC_ALNM | DDIC_CHAR | DDIC_CDAY | DDIC_CLNT | DDIC_CUKY | DDIC_CURR | DDIC_D16D | DDIC_D34D | DDIC_D16R | DDIC_D34R | DDIC_D16S | DDIC_D34S | DDIC_DATS | DDIC_DAY | DDIC_DEC | DDIC_FLTP | DDIC_GUID | DDIC_INT1 | DDIC_INT2 | DDIC_INT4 | DDIC_INT8 | DDIC_LANG | DDIC_LCHR | DDIC_MIN | DDIC_MON | DDIC_LRAW | DDIC_NUMC | DDIC_PREC | DDIC_QUAN | DDIC_RAW | DDIC_RSTR | DDIC_SEC | DDIC_SRST | DDIC_SSTR | DDIC_STRG | DDIC_STXT | DDIC_TIMS | DDIC_UNIT | DDIC_UTCM | DDIC_UTCL | DDIC_UTCS | DDIC_TEXT | DDIC_VARC | DDIC_WEEK <default_value> ::= NULL | <string_literal> | <signed_numeric_literal> | <unsigned_numeric_literal> <signed_numeric_literal> ::= [<sign>] <unsigned_numeric_literal> <sign> ::= + | - <unsigned_numeric_literal> ::= <exact_numeric_literal> | <approximate_numeric_literal> <exact_numeric_literal> ::= <unsigned_integer> [<period> [<unsigned_integer>]] | <period> <unsigned_integer> <period> ::= . <approximate_numeric_literal> ::= <mantissa> E <exponent> <mantissa> ::= <exact_numeric_literal> <exponent> ::= <signed_integer> <signed_integer> ::= [<sign>] <unsigned_integer> <unsigned_integer> ::= <digit>...
DEFAULTDefault specifies a value to be assigned to the column if an INSERT statement does not provide a value for thecolumn.
DATA TYPE in column definitionAvaliable data types are DATE, TIME, SECONDDATE, TIMESTAMP, TINYINT, SMALLINT, INTEGER, BIGINT,SMALLDECIMAL, DECIMAL, REAL, DOUBLE, VARCHAR, NVARCHAR, ALPHANUM, SHORTTEXT, VARBINARY,BLOB, CLOB, NCLOB and TEXT.
Available column store data types are CS_ALPHANUM, CS_INT, CS_FIXED, CS_FLOAT, CS_DOUBLE,CS_DECIMAL_FLOAT, CS_FIXED(p-s,s), CS_SDFLOAT, CS_STRING, CS_UNITEDECFLOAT, CS_DATE, CS_TIME,CS_FIXEDSTRING, CS_RAW, CS_DAYDATE, CS_SECONDTIME, CS_LONGDATE, and CS_SECONDDATE.
Available DDIC data types are DDIC_ACCP, DDIC_ALNM, DDIC_CHAR, DDIC_CDAY, DDIC_CLNT, DDIC_CUKY,DDIC_CURR, DDIC_D16D, DDIC_D34D, DDIC_D16R, DDIC_D34R, DDIC_D16S, DDIC_D34S, DDIC_DATS,DDIC_DAY, DDIC_DEC, DDIC_FLTP, DDIC_GUID, DDIC_INT1, DDIC_INT2, DDIC_INT4, DDIC_INT8,DDIC_LANG, DDIC_LCHR, DDIC_MIN, DDIC_MON, DDIC_LRAW, DDIC_NUMC, DDIC_PREC, DDIC_QUAN,DDIC_RAW, DDIC_RSTR, DDIC_SEC, DDIC_SRST, DDIC_SSTR, DDIC_STRG, DDIC_STXT, DDIC_TIMS,DDIC_UNIT, DDIC_UTCM, DDIC_UTCL, DDIC_UTCS, DDIC_TEXT, DDIC_VARC, DDIC_WEEK.
GENERATED ALWAYS ASSpecifies the expression to generate the column value in runtime.
<column_constraint> ::= NULL | NOT NULL | UNIQUE [BTREE | CPBTREE] | PRIMARY KEY [BTREE | CPBTREE]
NULL | NOT NULLThe NOT NULL constraint prohibits a column value from being NULL.If NULL is specified it is not considered a constraint, it represents a column that may contain a null value. Thedefault is NULL.
UNIQUESpecifies a column as a unique key.
SAP HANA Database - SQL Reference Manual
69 2012-08-21
A composite unique key enables the specification of multiple columns as a unique key. With a uniqueconstraint, multiple rows cannot have the same value in the same column.
PRIMARY KEYA primary key constraint is a combination of a NOT NULL constraint and a UNIQUE constraint. It prohibitsmultiple rows from having the same value in the same column.
BTREE | CPBTREESpecifies the index type. When column data types are character string types, binary string types, decimaltypes, or when the constraint is a composite key, or non-unique constraint, the default index type isCPBTREE. Otherwise, BTREE is used.BTREE keyword has to be used in order to use B+-tree index and the CPBTREE keyword has to be used for theCPB+-tree index.B+-tree is a tree which maintains sorted data that performs efficient insertion, deletion and search ofrecords.CPB+-tree stands for Compressed Prefix B+-Tree, which is based on pkB-tree. CPB+-tree is a very small indexbecause it uses 'partial key' that is only part of full key in index nodes. CPB+-tree shows better performancethan B+-Tree for larger keys.If the index type is omitted, the SAP HANA Database chooses the appropriate index considering the columndata types.
ALTER Increasing the length of a column can be done. When modifying column definition is tried in column store, noerror is returned because no check is done inside the database yet. An error may be returned if the data doesnot fit in the new data type defined when selecting the column. ALTER does not follow data type conversionrules yet.
Adding NOT NULL constraint to an existing column is allowed if
the table is empty orthe default value is specified when the table has data
<add_primary_key_clause> ::= ADD [CONSTRAINT <constraint_name>] PRIMARY KEY ( <column_name>, ... ) <constraint_name> ::= <identifier>
ADD PRIMARY KEY Adds a primary key constraint.
PRIMARY KEY A primary key constraint is a combination of a NOT NULL constraint and a UNIQUE constraint. It prohibitsmultiple rows from having the same value in the same column.
CONSTRAINT Specifies the name of a constraint.
<drop_primary_key_clause> ::= DROP PRIMARY KEY
DROP PRIMARY KEY Drops the primary key constraint.
<preload_clause> ::= PRELOAD ALL | PRELOAD ( <column_name> ) | PRELOAD NONE
PRELOAD sets/removes the preload flag of the given tables or columns. PRELOAD ALL sets preload flags of all columnsin the table, PRELOAD ( <column_name> ) sets the flags of columns specified, and PRELOAD NONE removesthe flags of all columns. As a consequence, these tables are automatically loaded into memory after an indexserver start. The current status of the preload flag is visible in the system table TABLES, column PRELOAD,possible values ('FULL', 'PARTIALLY', 'NO') and in system table TABLE_COLUMNS, column PRELOAD, possiblevalues ('TRUE', 'FALSE').
<table_conversion_clause> ::= [ALTER TYPE] {ROW [THREADS <number_of_threads>] | COLUMN [THREADS <number_of_threads> [BATCH <batch_size>]]}
ALTER TYPE ROW | COLUMN This command is used to convert the table storage from ROW to COLUMN or from COLUMN to ROW.
THREADS <number_of_threads> Specifies how many threads should be used in parallel for table conversion. The optimal value for number ofthreads should set to the number of available CPU cores.
SAP HANA Database - SQL Reference Manual
70 2012-08-21
Default: The default value is param_sql_table_conversion_parallelism that is, the number of CPU coresspecified in the indexserver.ini file.
BATCH <batch_size> Specifies the number of rows inserted in batch, and the default value is 2,000,000 which is the optimal value.Insert into column table will be immediately committed after every <batch_size> records insertion, whichmay reduce memory consumption. BATCH option can be used only when the table is converted from ROW toCOLUMN. However, the batch size more than 2,000,000 might cause high memory consumption, thus it isnot recommended to change this value.
A new table with a different storage type can be created from an existing table by copying the existingtable's columns and data. This command is used to convert the table storage from ROW to COLUMN or fromCOLUMN to ROW. If the source table was in ROW storage, then the created table will be in COLUMNstorage.
<move_clause> ::= MOVE [PARTITION <partition_number>] TO [LOCATION ]<host_port> [PHYSICAL] | MOVE [PARTITION <partition_number>] PHYSICAL
MOVE moves a table to another location in a distributed environment. The port number is the internalindexserver port number, 3xx03.
I you have a partitioned table you can only move individual parts by specifying the optional partition number.Moving a partitioned table without specifying a partition number will result in an error.
The PHYSICAL keyword is only for column store tables. Row store tables are always moved physical.
If the optional keyword PHYSICAL is specified, the persistence storage is immediately moved to the targethost. Otherwise move will just create a link inside the new host persistence pointing to the old hostpersistence. This link will be removed on the next merge or a another move operation without the TO<host_port> part.
The move PHYSICAL operation without TO <host_port> part will just remove persistence links that might stillexists from previouse move operations.
LOCATION is supported only for backward-compatibility
<add_range_partition_clause> ::= ADD <range_partition_clause> <range_partition_clause> ::= PARTITION <lower_value> <= VALUES < <upper_value> | PARTITION <value_or_values> = <target_value> | PARTITION OTHERS <lower_value> ::= <string_literal> | <numeric_literal> <upper_value> ::= <string_literal> | <numeric_literal> <target_value> ::= <string_literal> | <numeric_literal>
ADD PARTITION Adds a partition for tables partitioned with RANGE, HASH RANGE, ROUNDROBIN RANGE. When adding apartition to a table which is partitioned by range and with a rest partition, the rest partition can berepartitioned if needed.
<drop_range_partition_clause> ::= DROP <range_partition_clause> <range_partition_clause> ::= PARTITION <lower_value> <= VALUES < <upper_value> | PARTITION <value_or_values> = <target_value> | PARTITION OTHERS <lower_value> ::= <string_literal> | <numeric_literal> <upper_value> ::= <string_literal> | <numeric_literal> <target_value> ::= <string_literal> | <numeric_literal>
DROP PARTITION Drops a partition for tables partitioned with RANGE, HASH RANGE, ROUNDROBIN RANGE.
<partition_clause> ::= PARTITION BY <hash_partition> [,<range_partition> | ,<hash_partition>] | PARTITION BY <range_partition> | PARTITION BY <roundrobin_partition> [,<range_partition>]
<hash_partition> ::= HASH (<partition_expression>[, ...]) PARTITIONS { <num_partitions> | GET_NUM_SERVERS() }
<range_partition> ::= RANGE ( <partition_expression> ) ( <range_spec> ) <roundrobin_partition> ::= ROUNDROBIN PARTITIONS {<num_partitions> |
SAP HANA Database - SQL Reference Manual
71 2012-08-21
GET_NUM_SERVERS()}
<range_spec> ::= {<from_to_spec> | <single_spec>[,...] } [, PARTITION OTHERS] <from_to_spec> ::= PARTITION <lower_value> <= VALUES < <upper_value> <single_spec> ::= PARTITION VALUE <single_value> <partition_expression> ::= <column_name>| YEAR(<column_name>) | MONTH(<column_name>)
PARTITION BY Partitions table with RANGE, HASH RANGE, ROUNDROBIN RANGE. For table partition clause, refer toCREATE TABLE.
<merge_partition_clause> ::= MERGE PARTITIONS
MERGE PARTITIONS Merges all parts of a partitioned table into a non-partitioned table.
<disable_persistent_merge_clause> ::= DISABLE PERSISTENT MERGE
DISABLE PERSISTENT MERGE Instructs the merge-manager to use main-memory merges instead of persistent merges for the given table.
<enable_persistent_merge_clause> ::= ENABLE PERSISTENT MERGE
ENABLE PERSISTENT MERGE Instructs the merge-manager to use persistent merges for the given table (default behaviour).
<enable_delta_log> ::= ENABLE DELTA LOG
ENABLE DELTA LOG Enables logging for table. After enabling, you have to perform a savepoint to be sure that all data is persistedand you have to perfrom a data backup, else you can not recover this data.
<enable_delta_log> ::= DISABLE DELTA LOG
DISABLE DELTA LOG Disables logging for table. If logging is disabled, no log entries will be persisted for this table. Changes to thistable will only be written to the data area, when a savepoint is done. This can cause loss of committedtransaction, when the indexserver terminates. In case of termination, you have to truncate this table andinsert all data again.
Only use this command for initial load !
<enable_delta_log> ::= ENABLE AUTOMERGE
ENABLE AUTOMERGE Instructs the merge-manager to handle this table.
<enable_delta_log> ::= DISABLE AUTOMERGE
DISABLE AUTOMERGE Instructs the merge-manager to ignore this table.
Description
The ALTER TABLE statement changes the status of a table.
Example
Table t is created and the default value of column b is set to 10:
CREATE TABLE t (a INT, b INT); ALTER TABLE t ALTER (b INT DEFAULT 10);
Column c is added to table t:
ALTER TABLE t ADD (c NVARCHAR(10) DEFAULT 'NCHAR');
SAP HANA Database - SQL Reference Manual
72 2012-08-21
A primary key constraint, prim_key is created on table t:
ALTER TABLE t ADD CONSTRAINT prim_key PRIMARY KEY (a, b);
The table type of table t is changed to COLUMN:
ALTER TABLE t COLUMN;
The preload flags of column b and c are set:
ALTER TABLE t PRELOAD (b, c);
Table t is partitioned with RANGE, and another partition is added:
ALTER TABLE t PARTITION BY RANGE (a) (PARTITION VALUE = 1, PARTITION OTHERS); ALTER TABLE t ADD PARTITION 2 <= VALUES < 10;
The session type of table t is changed to HISTORY:
ALTER TABLE t CREATE HISTORY;
Logging of table t is disabled:
ALTER TABLE t DISABLE DELTA LOG;
CREATE AUDIT POLICY
Syntax
CREATE AUDIT POLICY <policy_name> AUDITING <audit_status_clause> <audit_action_list> LEVEL <audit_level>
Syntax Elements
<audit_status_clause> ::= SUCCESSFUL | UNSUCCESSFUL | ALL
<audit_action_list> ::= <audit_action_name>[,<audit_action_name>]...
<audit_action_name> ::= GRANT PRIVILEGE | REVOKE PRIVILEGE | GRANT STRUCTURED PRIVILEGE | REVOKE STRUCTURED PRIVILEGE | GRANT ROLE | REVOKE ROLE | GRANT ANY | REVOKE ANY | CREATE USER | DROP USER | CREATE ROLE | DROP ROLE | ENABLE AUDIT POLICY | DISABLE AUDIT POLICY | CREATE STRUCTURED PRIVILEGE | DROP STRUCTURED PRIVILEGE | ALTER STRUCTURED PRIVILEGE | CONNECT | SYSTEM CONFIGURATION CHANGE | SET SYSTEM LICENSE | UNSET SYSTEM LICENSE
<audit_level> ::= EMERGENCY | ALERT | CRITICAL | WARNING | INFO
Description
The CREATE AUDIT POLICY statement creates a new audit policy. This audit policy can be enabled afterwardsand will then cause the auditing of the specified audit actions to happen. Only database users having the system privilege AUDIT ADMIN are allowed to create an audit policy. The specified audit policy name must not be identical to the name of an existing audit policy. An audit policy defines which audit actions will be audited. Existing audit policies need to be enabled to makethe auditing happen.
The <audit_status_clause> defines, if only successful or unsuccessful or all executions of the specified auditactions are audited.
SAP HANA Database - SQL Reference Manual
73 2012-08-21
The following audit actions are available. They are grouped in several groups. Audit actions of one group canbe combined in one audit policy. Audit actions of different groups can not be combined in one audit policy.
Audit PolicyGroupNumber
Description
GRANT PRIVILEGE 1 audits the grant of privi leges to users or roles
REVOKE PRIVILEGE 1 audits the revoke of privi leges from users or roles
GRANT STRUCTUREDPRIVILEGE
1audits the grant of s tructured/ana lytica l privi leges to users orroles
REVOKE STRUCTUREDPRIVILEGE
1audits the revoke of s tructured/ana lytica l privi leges from usersor roles
GRANT ROLE 1 audi ts the grant of roles to users or roles
REVOKE ROLE 1 audi ts the revoke of roles from users or roles
GRANT ANY 1audits the grant of privi leges , s tructured privi leges or roles tousers or roles
REVOKE ANY 1audits the revoke of privi leges , s tructured privi leges or roles fromusers or roles
CREATE USER 2 audits the create of users
DROP USER 2 audits the drop of users
CREATE ROLE 2 audi ts the create of roles
DROP ROLE 2 audi ts the drop of roles
CONNECT 3 audits the connect of users to the database
SYSTEM CONFIGURATIONCHANGE
4 audits changes to the s ys tem configuration (e.g. INIFILE)
ENABLE AUDIT POLICY 5 audi ts the activation of audi t pol icies
DISABLE AUDIT POLICY 5 audi ts the deactivation of audi t pol icies
CREATE STRUCTUREDPRIVILEGE
6 audits the creation of s tructured/ana lytica l privi leges
DROP STRUCTUREDPRIVILEGE
6 audits the destruction of s tructured/ana lytica l privi lege
ALTER STRUCTUREDPRIVILEGE
6 audits the change of s tructured/ana lytica l privi lege
SET SYSTEM LICENSE 7 audi ts the ins ta l la tion of a l i cense
UNSET SYSTEM LICENSE 7 audi ts the deletion of l i censes
Each audit policy is assigned to a audit level. Possible levels, in decreasing order of importance, are:EMERGENCY, ALERT, CRITICAL, WARNING, INFO.
To make auditing happen, audit policies have to be created and enabled and the configuration parameterglobal_auditing_state (see below) has to be set to true;
Configuration Parameter
Currently the configuration parameter for auditing are stored in global.ini, section auditing configuration andare the following:
global_auditing_state ( 'true' / 'false' ) to activate / deactivate the whole auditing, no matter, how manyaudit policies are available and enabled. The default is false, meaning: no auditing will happen at all. default_audit_trail_type ( 'SYSLOGPROTOCOL' / 'CSVTEXTFILE' ) to specify, how to store the auditing results.SYSLOGPROTOCOL is the default. CSVTEXTFILE should be used only for testing purposes. default_audit_trail_path to specify where to store the file, in case CSVTEXTFILE had been selected.
As all configuration parameter, these parameters can be selected in view M_INIFILE_CONTENTS, if thecurrent user has the needed privilege to do so. But these parameter currently will only be seen in case theyhave been set explicitly. This means, they will not be seen with a newly installed database instance.
System and Monitoring Views
AUDIT_POLICY: shows all audit policies and their states M_INIFILE_CONTENTS: shows the configuration parameter concerning auditing
Only database users with system privilege CATALOG READ, DATA ADMIN or INIFILE ADMIN can see any infoout of the view M_INIFILE_CONTENTS. For other database users this view will be empty.
SAP HANA Database - SQL Reference Manual
74 2012-08-21
Example
A new audit policy named priv_audit is created which will audit successful commands concerning grantingand revoking of privileges and roles. This audit policy has the medium audit level CRITICAL. This policy has to be enabled explicity (see alter_audit_policy) to make the auditing of the audit policy tohappen.
CREATE AUDIT POLICY priv_audit AUDITING SUCCESSFUL GRANT PRIVILEGE, REVOKE PRIVILEGE, GRANT ROLE, REVOKE ROLE LEVEL CRITICAL;
CREATE FULLTEXT INDEX
Syntax
CREATE FULLTEXT INDEX <index_name> ON <tableref> '(' <column_name> ')' [<fulltext_parameter_list>]
Syntax
<index_name> ::= <string_literal>
Specifies the name of the fulltext index.
<fulltext_parameter_list> ::= <fulltext_parameter> [, ...]
<fulltext_parameter> ::= LANGUAGE COLUMN <column_name> | LANGUAGE DETECTION '(' <string_literal_list> ')' | MIME TYPE COLUMN <column_name> | <change_tracking_elem> | FUZZY SEARCH INDEX <on_off> | PHRASE INDEX RATIO <on_off> | CONFIGURATION <string_literal> | SEARCH ONLY <on_off> | FAST PREPROCESS <on_off>
<on_off> ::= ON | OFF
LANGUAGE COLUMNColumn where the language of a document is specified.
LANGUAGE DETECTIONSet of languages to be considered for language detection.
MIME TYPE COLUMNColumn where the mime-type of a document is specified.
FUZZY SEARCH INDEXSpecifies whether the fuzzy search index should be used.
PHRASE INDEX RATIOSpecifies the percentage of the phrase index. Value must be between 0.0 and 1.0
CONFIGURATIONPath to a custom configuration file for text analysis.
SEARCH ONLYIf set to ON the original document content is not stored.
FAST PREPROCESSIf set to ON, fast preprocessing is used, i.e. linguistic searches are not possible.
<change_tracking_elem> ::= SYNC[HRONOUS] | ASYNC[HRONOUS] [FLUSH [QUEUE] <flush_queue_elem>]
SYNCIf specified a synchronous fulltext index is created.
ASYNCIf specified an asynchronous fulltext index is created.
<flush_queue_elem> ::= EVERY <integer_literal> MINUTES | AFTER <integer_literal> DOCUMENTS
SAP HANA Database - SQL Reference Manual
75 2012-08-21
| EVERY <integer_literal> MINUTES OR AFTER <integer_literal> DOCUMENTS
Specifies when to update the fulltext index if an asynchronous index is used.
Description
The CREATE FULLTEXT INDEX statement creates an explicit fulltext index on the given table column.
Example
CREATE FULLTEXT INDEX i1 ON A(C) FUZZY SEARCH INDEX OFF SYNC LANGUAGE DETECTION ('EN','DE','KR')
The example above creates a synchronous fulltext index named 'i1' on column 'C' of table 'A' where the fuzzysearch index is not used and the set of languages for language detection consists of 'EN','DE' and 'KR'.
CREATE INDEX
Syntax
CREATE [UNIQUE] [BTREE | CPBTREE] INDEX <index_name> ON <table_name> (<column_name_order>, ...) [ASC | DESC]
Syntax Elements
<index_name> ::= [<schema_name>.]<identifier> <column_name_order> ::= <column_name> [ASC | DESC]
UNIQUEUsed to create unique indexes. Check for duplicates will occur when an index is created and when a record isadded to the table.
BTREE | CPBTREEUsed to select the kind of index to use.
BTREE keyword has to be used in order to use B+-tree index and the CPBTREE keyword has to be used for theCPB+-tree index.B+-tree is a tree which maintains sorted data that performs efficient insertion, deletion and search ofrecords.CPB+-tree stands for Compressed Prefix B+-Tree, which is based on pkB-tree. CPB+-tree is a very small indexbecause it uses 'partial key' that is only part of full key in index nodes. CPB+-tree shows better performancethan B+-Tree for larger keys.When column data types are character string types, binary string types, decimal types, or when theconstraint is a composite key, or a non-unique constraint, the default index type is CPBTREE; otherwise,BTREE is used.If neither BTREE nor CPBTREE keyword is specified, then SAP HANA Database chooses the appropriate indextype.
ASC | DESCSpecifies whether the index should be created in ascending or descending order.These keywords can be only used in the btree index, and can be specified only once for each column.
Description
The CREATE INDEX statement creates an index.
Example
Table t is created, then CPBTREE index idx is created on column b of table t with ascending order:
CREATE TABLE t (a INT, b NVARCHAR(10), c NVARCHAR(20)); CREATE INDEX idx ON t(b);
CPBTREE index idx1 is created on column a of table t with ascending order and column b with descedingorder:
CREATE CPBTREE INDEX idx1 ON t(a, b DESC);
SAP HANA Database - SQL Reference Manual
76 2012-08-21
CPBTREE index idx2 is created on column a and c of table t with desceding order:
CREATE INDEX idx2 ON t(a, c) DESC;
UNIQUE CPBTREE index idx3 is created on column b and c of table t with ascending order:
CREATE UNIQUE INDEX idx3 ON t(b, c);
UNIQUE BTREE index idx4 is created on column a of table t with ascending order:
CREATE UNIQUE INDEX idx4 ON t(a);
CREATE SCHEMA
Syntax
CREATE SCHEMA <schema_name> [OWNED BY <user_name>]
Syntax Elements
<schema_name> ::= <identifier> <user_name> ::= <identifier>
OWNED BYSpecifies the name of the schema owner. If omitted, the current user will be the owner of the schema.
Description
The CREATE SCHEMA statement creates a schema in the current database.
Example
CREATE SCHEMA my_schema OWNED BY system;
CREATE SEQUENCE
Syntax
CREATE SEQUENCE <sequence_name> [<common_sequence_parameter_list>] [RESET BY <subquery>]
Syntax Elements
<sequence_name> ::= <identifier> <common_sequence_parameter_list> ::= <common_sequence_parameter>, ... <common_sequence_parameter> ::= <sequence_parameter_start_with> | <basic_sequence_parameter> <basic_sequence_parameter> ::= INCREMENT BY n | MAXVALUE n | NO MAXVALUE | MINVALUE n | NO MINVALUE | CYCLE | NO CYCLE <sequence_parameter_start_with> ::= START WITH n
INCREMENT BYDefines the amount the next sequence value is incremented from the last value assigned. The default is 1.Specify a negative value to generate a descending sequence. An error is returned if the INCREMENT BY valueis 0
START WITHDefines the starting sequence value. If you do not specify a value for the START WITH clause, MINVALUE isused for ascending sequences and MAXVALUE is used for descending sequences.
MAXVALUEDefines the largest value generated by the sequence and must be between 0 and 4611686018427387903.
NO MAXVALUE
SAP HANA Database - SQL Reference Manual
77 2012-08-21
NO MAXVALUEWhen MAXVALUE is not specified, the maximum value for an ascending sequence is 4611686018427387903and the maximum value for a descending sequences is -1.
MINVALUEThe minimum value of a sequence can be specified after MINVALUE and is between 0 and4611686018427387903.
NO MINVALUEWhen MINVALUE is not specified, the minimum value for an ascending sequence is 1 and the minimum valuefor a descending is -4611686018427387903.
CYCLEThe sequence number will be reused after it reaches its maximum or minimum value.
NO CYCLEDefault option. The sequence number will not be reused after it reaches its maximum or minimum value.
RESET BYDuring the restart of the database, database automatically executes the RESET BY statement and thesequence value is restarted with the specified value from the statement after RESET BY.If RESET BY is not specified, the sequence value is stored persistently in database. During the restart of thedatabase, the next value of the sequence is generated from the saved sequence value.
Description
The CREATE SEQUENCE statement is used to create a sequence.
A sequence is used to generate unique integers by multiple users. CURRVAL is used to get the current valueof the sequence and NEXTVAL is used to get the next value of the sequence. CURRVAL is only valid aftercalling NEXTVAL in a session.
Example
Example 1:Sequence seq is created, then CURRVAL and NEXTVAL are used to get the values from the sequence:
CREATE SEQUENCE seq START WITH 11;
NEXTVAL returns 11:
SELECT seq.NEXTVAL FROM DUMMY;
CURRVAL returns 11:
SELECT seq.CURRVAL FROM DUMMY;
Example 2:If the sequence s is used to create a unique key on column A in the table R, then after a database is restarted,a UNIQUE key value can be created by automatically assigning the maximum value of column A to thesequence value using a RESET BY statement as follows:
CREATE TABLE r (a INT); CREATE SEQUENCE s RESET BY SELECT IFNULL(MAX(a), 0) + 1 FROM r; SELECT s.NEXTVAL FROM DUMMY;
CREATE SYNONYM
Syntax
CREATE [PUBLIC] SYNONYM <synonym_name> FOR <object_name>
Syntax Elements
<synonym_name> ::= <identifier>
<object_name> ::= <table_name> | <view_name> | <procedure_name> | <sequence_name>
SAP HANA Database - SQL Reference Manual
78 2012-08-21
Description
The CREATE SYNONYM creates an alternate name for a table, view, procedure or sequence.
You can use a synonym to re-point functions and stored procedures to differing tables, views or sequenceswithout needing to re-write the function or stored procedure.
The optional PUBLIC element allows for the creation of a public synonym. A public synonym can be accessedby any users, but the users that have proper privilege on its base object can access the base object.
Example
CREATE SYNONYM a_synonym FOR a;
CREATE TABLE
Syntax
CREATE [<table_type>] TABLE <table_name> <table_contents_source> [<logging_option> | <auto_merge_option> | <partition_clause> | <location_clause>]
Syntax Elements
<table_name> ::= [<schema_name>.]<identifier> <schema_name> ::= <identifier>
For descriptions on schema name and identifer, please refer to Identifiers.
table_type:
<table_type> ::= COLUMN | ROW | HISTORY COLUMN | GLOBAL TEMPORARY | LOCAL TEMPORARY
ROW, COLUMNIf the majority of access is through a large number of tuples but with only a few selected attributes,COLUMN-based storage should be used. If the majority of access involves selecting a few records with allattributes selected, ROW-based storage is preferable. The SAP HANA Database uses a combination to enablestorage and interpretation in both forms. You can define the type of organization for each table. The defaultvalue is ROW.
HISTORY COLUMNCreates a table with a particular transaction session type called 'HISTORY'. Tables with session type HISTORYsupport time travel; the execution of queries against historic states of the database is possible.
Timetravel can be done in the following ways.Session-level timetravel:SET HISTORY SESSION TO UTCTIMESTAMP = <utc_timestamp> SET HISTORY SESSION TO COMMIT ID = <commit_id> <utc_timestamp> ::= <string_literal> <commit_id> ::= <unsigned_integer>
A database session can be set back to a certain point-in-time. The COMMIT ID variant of the statement takesa commitid as a parameter. The value of the commitid parameter must occur in COMMIT_ID column of thesystem table SYS.TRANSACTION_HISTORY, otherwise an exception will be thrown. The COMMIT ID is usefulwhen using user defined snapshots. A user defined snapshot can be taken by simply storing the commitidwhich is assigned to a transaction during the commit phase. The commitid can be retrieved by executing thefollowing query directly after a transaction commit:
SELECT LAST_COMMIT_ID FROM M_TRANSACTIONSWHERE CONNECTION_ID = CURRENT_CONNECTION;
The TIMESTAMP-variant of the statement takes a timestamp as parameter. Internally, the timestamp isused to look up a (commit_time,commit_id)-pair inside the system-table SYS.TRANSACTION_HISTORY wherethe commit_time is close to the given timestamp (to be more precisely: choose pair where maximalCOMMIT_TIME is smaller or equal to the given timestamp; if no such pair is found an exception will beraised). The session then will be restored with the determined commit-id as in the COMMIT ID variant.To terminate a restored session to switch back to the current session, an explicit COMMIT or ROLLBACK hasto be executed on the DB connection.
SAP HANA Database - SQL Reference Manual
79 2012-08-21
to be executed on the DB connection.
Statement-level timetravel:
<subquery> AS OF UTCTIMESTAMP <utc_timestamp> <subquery> AS OF COMMIT ID <commit_id>
In order to be able to relate the commitid with the commit time, a system table SYS.TRANSACTION_HISTORYis maintained which stores additional information for each transaction which commits data for history table.For detailed information on setting session-level timetravel, please refer to SET HISTORY SESSION, and fordetails on <subquery>, please refer to Subquery.
Note:. Autocommit has to be turned off when a session should be restored (otherwise an exception will be thrownwith an appropriate error message). Non-history tables in restored sessions always show their current snapshot. Only data query statement (select) is allowed inside restored sessions.. A history table must have a primary key. The session type can be checked from the column, SESSION_TYPE of the system table SYS.TABLES.
GLOBAL TEMPORARYTable definition is globally available while data is visible only to the current session. The table is truncated atthe end of the session.
Metadata in a global temporary table is persistent meaning the metadata exists until the table is droppedand the metadata is shared across sessions. Data in a global temporary table is session-specific meaning onlythe owner session of the global temporary table is allowed to insert/read/truncate the data, exists for theduration of the session and data from the global temporary table is automatically dropped when the sessionis terminated. Global temporary table can be dropped only when the table does not have any record in it.
Supported operations on Global Temporary Table:1. Create without a primary key2. Rename table3. Rename column4. Truncate5. Drop6. Create or Drop view on top of global temporary table7. Create synonym8. Select9. Select into or Insert10. Delete11. Update12. Upsert or Replace
LOCAL TEMPORARYThe table definition and data is visible only to the current session. The table is truncated at the end of thesession.
Metadata exists for the duration of the session and is session-specific meaning only the owner session of thelocal temporary table is allowed to see. Data in a local temporary table is session-specific meaning only theowner session of the local temporary table is allowed to insert/read/truncate the data, exists for the durationof the session and data from the local temporary table is automatically dropped when the session isterminated.
Supported operations on Global Temporary Table:1. Create without a primary key2. Truncate3. Drop4. Select5. Select into or Insert6. Delete7. Update8. Upsert or Replace
table_contents_source:
<table_contents_source> ::= (<table_element>, ...) | <like_table_clause> [WITH [NO] DATA] | [(<column_name>, ...)] <as_table_subquery> [WITH [NO] DATA]] <table_element> ::= <column_definition> [<column_constraint>] | <table_constraint> (<column_name>, ... ) <column_definition> ::= <column_name> <data_type> [<column_store_data_type>] [<ddic_data_type>] [DEFAULT <default_value>] [GENERATED ALWAYS AS <expression>]
SAP HANA Database - SQL Reference Manual
80 2012-08-21
<column_name> ::= <identifier> <data_type> ::= DATE | TIME | SECONDDATE | TIMESTAMP | TINYINT | SMALLINT | INTEGER | BIGINT | SMALLDECIMAL | DECIMAL | REAL | DOUBLE | VARCHAR | NVARCHAR | ALPHANUM | SHORTTEXT | VARBINARY | BLOB | CLOB | NCLOB | TEXT <column_store_data_type> ::= CS_ALPHANUM | CS_INT | CS_FIXED | CS_FLOAT | CS_DOUBLE | CS_DECIMAL_FLOAT | CS_FIXED(p-s, s) | CS_SDFLOAT | CS_STRING | CS_UNITEDECFLOAT | CS_DATE | CS_TIME | CS_FIXEDSTRING | CS_RAW | CS_DAYDATE | CS_SECONDTIME | CS_LONGDATE | CS_SECONDDATE <ddic_data_type> ::= DDIC_ACCP | DDIC_ALNM | DDIC_CHAR | DDIC_CDAY | DDIC_CLNT | DDIC_CUKY | DDIC_CURR | DDIC_D16D | DDIC_D34D | DDIC_D16R | DDIC_D34R | DDIC_D16S | DDIC_D34S | DDIC_DATS | DDIC_DAY | DDIC_DEC | DDIC_FLTP | DDIC_GUID | DDIC_INT1 | DDIC_INT2 | DDIC_INT4 | DDIC_INT8 | DDIC_LANG | DDIC_LCHR | DDIC_MIN | DDIC_MON | DDIC_LRAW | DDIC_NUMC | DDIC_PREC | DDIC_QUAN | DDIC_RAW | DDIC_RSTR | DDIC_SEC | DDIC_SRST | DDIC_SSTR | DDIC_STRG | DDIC_STXT | DDIC_TIMS | DDIC_UNIT | DDIC_UTCM | DDIC_UTCL | DDIC_UTCS | DDIC_TEXT | DDIC_VARC | DDIC_WEEK <default_value> ::= NULL | <string_literal> | <signed_numeric_literal> | <unsigned_numeric_literal> <signed_numeric_literal> ::= [<sign>] <unsigned_numeric_literal> <sign> ::= + | - <unsigned_numeric_literal> ::= <exact_numeric_literal> | <approximate_numeric_literal> <exact_numeric_literal> ::= <unsigned_integer> [<period> [<unsigned_integer>]] | <period> <unsigned_integer> <period> ::= . <approximate_numeric_literal> ::= <mantissa> E <exponent> <mantissa> ::= <exact_numeric_literal> <exponent> ::= <signed_integer> <signed_integer> ::= [<sign>] <unsigned_integer> <unsigned_integer> ::= <digit>...
DEFAULTDefault specifies a value to be assigned to the column if an INSERT statement does not provide a value for thecolumn.
DATA TYPE in column definitionAvaliable data types are DATE, TIME, SECONDDATE, TIMESTAMP, TINYINT, SMALLINT, INTEGER, BIGINT,SMALLDECIMAL, DECIMAL, REAL, DOUBLE, VARCHAR, NVARCHAR, ALPHANUM, SHORTTEXT, VARBINARY,BLOB, CLOB, NCLOB and TEXT.
Available column store data types are CS_ALPHANUM, CS_INT, CS_FIXED, CS_FLOAT, CS_DOUBLE,CS_DECIMAL_FLOAT, CS_FIXED(p-s,s), CS_SDFLOAT, CS_STRING, CS_UNITEDECFLOAT, CS_DATE, CS_TIME,CS_FIXEDSTRING, CS_RAW, CS_DAYDATE, CS_SECONDTIME, CS_LONGDATE, and CS_SECONDDATE.
Available DDIC data types are DDIC_ACCP, DDIC_ALNM, DDIC_CHAR, DDIC_CDAY, DDIC_CLNT, DDIC_CUKY,DDIC_CURR, DDIC_D16D, DDIC_D34D, DDIC_D16R, DDIC_D34R, DDIC_D16S, DDIC_D34S, DDIC_DATS,DDIC_DAY, DDIC_DEC, DDIC_FLTP, DDIC_GUID, DDIC_INT1, DDIC_INT2, DDIC_INT4, DDIC_INT8,DDIC_LANG, DDIC_LCHR, DDIC_MIN, DDIC_MON, DDIC_LRAW, DDIC_NUMC, DDIC_PREC, DDIC_QUAN,DDIC_RAW, DDIC_RSTR, DDIC_SEC, DDIC_SRST, DDIC_SSTR, DDIC_STRG, DDIC_STXT, DDIC_TIMS,DDIC_UNIT, DDIC_UTCM, DDIC_UTCL, DDIC_UTCS, DDIC_TEXT, DDIC_VARC, DDIC_WEEK.
GENERATED ALWAYS ASSpecifies the expression to generate the column value in runtime.
<column_constraint> ::= NULL | NOT NULL | UNIQUE [BTREE | CPBTREE] | PRIMARY KEY [BTREE | CPBTREE]
NULL | NOT NULLThe NOT NULL constraint prohibits a column value from being NULL.If NULL is specified it is not considered a constraint, it represents a column that may contain a null value. Thedefault is NULL.
UNIQUESpecifies a column as a unique key.A composite unique key enables the specification of multiple columns as a unique key. With a uniqueconstraint, multiple rows cannot have the same value in the same column.
PRIMARY KEY
SAP HANA Database - SQL Reference Manual
81 2012-08-21
A primary key constraint is a combination of a NOT NULL constraint and a UNIQUE constraint. It prohibitsmultiple rows from having the same value in the same column.
BTREE | CPBTREESpecifies the index type. When column data types are character string types, binary string types, decimaltypes, or when the constraint is a composite key, or non-unique constraint, the default index type isCPBTREE. Otherwise, BTREE is used.BTREE keyword has to be used in order to use B+-tree index and the CPBTREE keyword has to be used for theCPB+-tree index.B+-tree is a tree which maintains sorted data that performs efficient insertion, deletion and search ofrecords.CPB+-tree stands for Compressed Prefix B+-Tree, which is based on pkB-tree. CPB+-tree is a very small indexbecause it uses 'partial key' that is only part of full key in index nodes. CPB+-tree shows better performancethan B+-Tree for larger keys.If the index type is omitted, the SAP HANA Database chooses the appropriate index considering the columndata types.
<table_constraint> ::= UNIQUE [BTREE | CPBTREE] | PRIMARY KEY [BTREE | CPBTREE]
This defines a table constraint which can be used on one or more columns of a table. There are two kinds of atable constraint. They are:
<like_table_clause> ::= LIKE <like_table_name> <like_table_name> ::= <table_name>
Creates a table that has the same definition as like_table_name. All the column definitions with constraintsand default values are copied from like_table_name. Data is filled from the specified table when WITH DATAoption is provided, however, the default value is WITH NO DATA.
<as_table_subquery> ::= AS '(<subquery>)
Creates a table and fills it with the data computed by the <subquery>. Only NOT NULL constraints are copiedby this clause. If column_names are specified, specified column_names override the column names from<subquery>. The default value is WITH DATA.
WITH [NO] DATA Specifies whether the data is copied from <subquery> or <like_table_clause>.
<logging_option> ::= LOGGING | NO LOGGING [RETENTION <retention_period>] <retention_period> ::= <unsigned_integer>
LOGGING | NO LOGGINGLOGGING (default value) specifies that table logging is activated.NO LOGGING specifies that logging is deactivated. A NO LOGGING table means that the definition of thetable is persistent and globally available, data is temporary and global.
RETENTIONSpecifies the retention time in seconds of the column table created by NOLOGGING. After the specifiedretention period has elapsed, the table will be dropped if used physical memory of the host reaches above80%.
<auto_merge_option> ::= AUTO MERGE | NO AUTO MERGE
AUTO MERGE | NO AUTO MERGEAUTO MERGE (default value) specifies that automatic delta merge is triggered.
<partition_clause> ::= PARTITION BY <hash_partition> [, <range_partition> | , <hash_partition>] | PARTITION BY <range_partition> | PARTITION BY <roundrobin_partition> [,<range_partition>] <hash_partition> ::= HASH (<partition_expression> [, ...]) PARTITIONS {<num_partitions> | GET_NUM_SERVERS()} <range_partition> ::= RANGE (<partition_expression>) (<range_spec>, ...) <roundrobin_partition> ::= ROUNDROBIN PARTITIONS {<num_partitions> | GET_NUM_SERVERS()} [, <range_partition>] <range_spec> ::= {<from_to_spec> | <single_spec>} [, ...] [, PARTITION OTHERS] <from_to_spec> ::= PARTITION <lower_value> <= VALUES < <upper_value> <single_spec> ::= PARTITION VALUE <target_value> <partition_expression> ::= <column_name> | YEAR(<column_name>) | MONTH(<column_name>) <lower_value> ::= <string_literal> | <numeric_literal>
SAP HANA Database - SQL Reference Manual
82 2012-08-21
<upper_value> ::= <string_literal> | <numeric_literal> <target_value> ::= <string_literal> | <numeric_literal> <num_partitions> ::= <unsigned_integer>
GET_NUM_SERVERS() is the function that returns the number of servers. PARTITION OTHERS means that all other values that are not specified in partition specification make onepartition. It is possible to determine the index servers on which the partitions are created. If you specify the LOCATION,the partitions will be created on these instances using round robin. Duplicates in the list will be removed. Ifyou specify exactly the same number of instances as partitions in the partition specification, then eachpartition will be assigned to the respective instance in the list. All index servers in the list have to belong tothe same instance.If no locations are specified, the partitions will be created randomly. If the number of partitions matches thenumber of servers - for example by using GET_NUM_SERVERS() - it is ensured that multiple CREATE TABLEcalls distribute the partitions in the same way. In case of a multi-level partitioning, this applies for the numberof partitions of the first level. This mechanism is useful if several tables are to be created which have asemantic relation to each other.
<location_clause> ::= AT [LOCATION] {'<host>:<port>' | ('<host>:<port>', ...)} <host> ::= <string_literal> <port> ::= <unsigned_integer>
AT LOCATIONA table can be created in the specified location with host:port. Location list can be specified when creatingpartitioned tables that are distributed on multiple instances. When location list is provided without<partition_clause>, the table is created on the first location specified.If location information is not provided, the table will be automatically assigned to one node. This option canbe used for both row store and column store tables in a distributed environment.
Description
The CREATE TABLE statement creates a table. Tables are created without data except when<as_table_subquery> or <like_table_clause> is used with the WITH DATA option.
Example
Table A is created, which has INTEGER-type column A and B. Column A has the primary key constraint:
CREATE TABLE A (A INT PRIMARY KEY, B INT);
A partitioned table P1 is created, which has DATE-type column U. Column U has the primary key constraintand is used as RANGE-partitioning column:
CREATE COLUMN TABLE P1 (U DATE PRIMARY KEY) PARTITION BY RANGE (U) (PARTITION '2010-02-03' <= VALUES < '2011-01-01', PARTITION VALUE = '2011-05-01');
A partitioned table P2 is created, which has INTEGER-type column I, J and K. Column I and J make the primarykey constraint and are used as HASH-partitioning column. Column K is used as sub HASH-partitioning column:
CREATE COLUMN TABLE P2 (I INT, J INT, K INT, PRIMARY KEY(I, J)) PARTITION BY HASH (I, J) PARTITIONS 2, HASH (K) PARTITIONS 2;
A Table C1 is created, which has the same definition as table A. Table C1 also has the same records as table A:
CREATE COLUMN TABLE C1 LIKE A WITH DATA;
A Table C2 is created, which has the same column data type and NOT NULL constraint as table A. Table C2has no records:
CREATE TABLE C2 AS (SELECT * FROM A) WITH NO DATA;
CREATE TRIGGER
Syntax
CREATE TRIGGER <trigger_name> <trigger_action_time> <trigger_event> ON <subject_table_name> [REFERENCING <transition_list>] [<for_each_row>] BEGIN [<trigger_decl_list>]
SAP HANA Database - SQL Reference Manual
83 2012-08-21
[<proc_handler_list>] <trigger_stmt_list> END
Syntax Elements
<trigger_name> ::= <identifier>
The name of trigger you create.
<subject_table_name> ::= <identifier>
The name of table your trigger is defined on. For descriptions on identifer, see Identifiers.
<trigger_action_time> ::= BEFORE | AFTER
Specify when trigger acction occur.
BEFORETrigger is executed before the subject table operation.
AFTERTrigger is executed after the subject table operation.
<trigger_event> ::= INSERT | DELETE | UPDATE
Specify which data modification command activate trigger action.
<transition_list> ::= <transition> | <transition_list> , <transition> <transition> ::= <trigger_transition_old_or_new> <trigger_transition_var_or_table> <trans_var_name> | <trigger_transition_old_or_new> <trigger_transition_var_or_table> AS <trans_var_name>
When trigger transition variable is declared, trigger can access records that are being changed by triggertriggering DML.While row level trigger execution, <trans_var_name>.<column_name> represents corresponding columnrecord being changed in trigger.Here <column_name> is subject table's column name. See example of transition variable
<trigger_transition_old_or_new> ::= OLD | NEW <trigger_transition_var_or_table> ::= ROW <trans_var_name> ::= <identifier>
OLD You can access old record of DML in trigger, which is to-be-replaced-by-update old record or deleted-old-record. UPDATE trigger and DELETE trigger can have OLD ROW transition variable.
NEWYou can access new record of DML in trigger, which is to-be-inserted new record or to-be-updated newrecord.UPDATE trigger and INSERT trigger can have NEW ROW transition variable.
Only transition variable is supported.Transition table is not supported feature. If you put 'TABLE' as <trigger_transition_var_or_table>, you will see not-supported-feature error.
<for_each_row> ::= FOR EACH ROW
The trigger will be called in a row-wise fashion. Row level trigger execution is default mode without FOR EACH ROW syntaxCurrently statement-wise trigger is not supported.
<trigger_decl_list> ::= DECLARE <trigger_decl> | <trigger_decl_list> DECLARE <trigger_decl> <trigger_decl> ::= <trigger_var_decl> | <trigger_condition_decl>
SAP HANA Database - SQL Reference Manual
84 2012-08-21
<trigger_var_decl> ::= <var_name> CONSTANT <data_type> [<not_null>] [<trigger_default_assign>] ; | <var_name> <data_type> [<not_null>] [<trigger_default_assign>] ; <var_name> ::= <identifer> <data_type> ::= DATE | TIME | SECONDDATE | TIMESTAMP | TINYINT | SMALLINT | INTEGER | BIGINT | SMALLDECIMAL | DECIMAL | REAL | DOUBLE | VARCHAR | NVARCHAR | ALPHANUM | SHORTTEXT | VARBINARY | BLOB | CLOB | NCLOB | TEXT <not_null> ::= NOT NULL <trigger_default_assign> ::= DEFAULT <expression> | := <expression> <trigger_condition_decl> ::= <condition_name> CONDITION ; | <condition_name> CONDITION FOR <sql_error_code> ; <condition_name> ::= <identifier> <sql_error_code> ::= SQL_ERROR_CODE <int_const>
trigger_decl_listYou can declare trigger variable or condition.Declared variable can be used scalar value assignment or referenced in trigger SQL statement. Declared condition name can be referenced when exception handler.
CONSTANT When CONSTANT kewword was given, you cannot change the variable while trigger execution.
<proc_handler_list> ::= <proc_handler> | <proc_handler_list> <proc_handler> <proc_handler> ::= DECLARE EXIT HANDLER FOR <proc_condition_value_list> <trigger_stmt> <proc_condition_value_list> ::= <proc_condition_value> | <proc_condition_value_list> , <proc_condition_value> <proc_condition_value> ::= SQLEXCEPTION | SQLWARNING | <sql_error_code> | <condition_name>
Exception handler can be declared for catching with existing sql exception, specific error code number or condition name declared on condition variable.
<trigger_stmt_list> ::= <trigger_stmt> | <trigger_stmt_list> <trigger_stmt> <trigger_stmt> ::= <proc_block> | <proc_assign> | <proc_if> | <proc_loop> | <proc_while> | <proc_for> | <proc_foreach> | <proc_signal> | <proc_resignal> | <trigger_sql>
Trigger body syntax is a part of procedure body syntax. See detail of create procedure definition in SAP HANA Database SQLScript guide.The syntax of trigger body complies with that of procedure, which are nested block(proc_block),scalar variable assign(proc_assign), if block(proc_if), loop block(proc_loop), for block(proc_for), for each block(proc_foreach), exception signal(proc_signal), exception resignal(proc_resignal), and sql statement(proc_sql).
<proc_block> ::= BEGIN [<trigger_decl_list>]
SAP HANA Database - SQL Reference Manual
85 2012-08-21
[<proc_handler_list>] <trigger_stmt_list> END ;
You can add another 'BEGIN ... END;' block in a nested way.
<proc_assign> ::= <var_name> := <expression> ;
var_name is variable name, which should be declared previously.
<proc_if> ::= IF <condition> THEN <trigger_stmt_list> [<proc_elsif_list>] [<proc_else>] END IF ;
<proc_elsif_list> ::= ELSEIF <condition> THEN <trigger_stmt_list>
<proc_else> ::= ELSE <trigger_stmt_list>
For descriptions on condition, refer to <condition> in SELECT.Using IF ... THEN ... ELSEIF ... END IF, you can control execution flow with condition.
<proc_loop> ::= LOOP <trigger_stmt_list> END LOOP ;
<proc_while> ::= WHILE <condition> DO <trigger_stmt_list> END WHILE ;
<proc_for> ::= FOR <column_name> IN [<reverse>] <expression> <DDOT_OP> <expression> DO <trigger_stmt_list> END FOR ;
<column_name> ::= <identifier> <reverse> ::= REVERSE <DDOT_OP> ::= ..
<proc_foreach> ::= FOR <column_name> AS <column_name> [<open_param_list>] DO <trigger_stmt_list> END FOR ;
<open_param_list> ::= ( <expr_list> )
<expr_list> ::= <expression> | <expr_list> , <expression>
<proc_signal> ::= SIGNAL <signal_value> [<set_signal_info>] ;
<proc_resignal> ::= RESIGNAL [<signal_value>] [<set_signal_info>] ;
<signal_value> ::= <signal_name> | <sql_error_code>
<signal_name> ::= <identifier>
<set_signal_info> ::= SET MESSEGE_TEXT = '<message_string>'
<message_string> ::= <identifier>
SET MESSEGE_TEXTIf you set your own message with SET MESSAGE_TEXT,the message is delivered to users when specified error is thrown from trigger execution.
SIGNAL statement provide raise an exception explicitly. User-defined range (10000 ~ 19999) will be allowed for the error code to issue. RESIGNAL statement provide raise an exception on the action statement in exception handler. If error code is not specified, RESIGNAL will throw up the catched exception.
<trigger_sql> ::= <select_into_stmt> | <insert_stmt> | <delete_stmt> | <update_stmt> | <replace_stmt> | <upsert_stmt>
For descriptions on insert_stmt, refer to INSERT.For descriptions on delete_stmt, refer to DELETE.For descriptions on update_stmt, refer to UPDATE.
SAP HANA Database - SQL Reference Manual
86 2012-08-21
For descriptions on replace_stmt and upsert_stmt, refer to REPLACE | UPSERT.
<select_into_stmt> ::= SELECT <select_list> INTO <var_name_list> <from_clause > [<where_clause>] [<group_by_clause>] [<having_clause>] [{<set_operator> <subquery>, ... }] [<order_by_clause>] [<limit>]
<var_name_list> ::= <var_name> | <var_name_list> , <var_name>
<var_name> ::= <identifier>
For descriptions on select_list, from_clause, where_clause, group_by_clause, having_clause, set_operator, subquery, order_by_clause, limit, refer to SELECT.
var_name is scalar variable name which should be declared before.You can assign selected item value to the scalar variable.
Description
CREATE TRIGGER statement creates a trigger.A trigger is special kind of stored procedure that automatically executes when an event occurs on a certaintable.CREATE TRIGGER command defines a set of statements that is executed when a givenoperation(INSERT/UPDATE/DELETE)takes place on a given object(subject table)
Only database users having the TRIGGER privilege for the given <subject_table_name> are allowed to createa trigger for that table. Current trigger limitation is described below:
INSTEAD_OF trigger is not supported.Access of subject table which is table that trigger is defined on, is not allowed in trigger body,which means any insert/update/delete/replace/select for table which trigger is on is not allowed. Only row level trigger is supported. Statement level trigger is not supported. Row level trigger means trigger action will be executed for every row changes. Statement level trigger means trigger action will be executed once for a statement execution.Syntax 'FOR EACH ROW' means row-wise trigger execution and it is default mode. Even when 'FOREACH ROW' is not defined, it is still row level trigger.Transition table (OLD/NEW TABLE) is not supported. When trigger SQL statement want to refer to data that are being changed by trigger-triggering-eventlike insert/update/delete, transition variable/table will be a way SQL statement in trigger body access old and new data. Transition variable is used by row level trigger while transition table is used by statement level trigger.Trigger execution on partitioned table to multiple host or table in slave node is not supported.A table can have only one trigger for each DML operation which would be a insert trigger, a update trigger and a delete trigger and three of them all can beactivated together.Therefore, a table can have maximum three triggers total.Not supported trigger action feature(while procedure does) : resultset assignment(select resultset assignment to tabletype), exit/continue command(execution flow control), cursor open/fetch/close(get each record data of search result by cursor and access record in loop), procedure call(call another proecedure), dynomic sql execution(build SQL statements dynamically at runtime of SQLScript), return(end SQL statement execution)
System and Monitoring Views
TRIGGERS is system view for trigger.
System view TRIGGERS shows: SCHEMA_NAME, TRIGGER_NAME, TRIGGER_OID, OWNER_NAME, OWNER_OID,SUBJECT_TABLE_SCHEMA, SUBJECT_TABLE_NAME, TRIGGER_ACTION_TIME, TRIGGER_EVENT, TRIGGERED_ACTION_LEVEL,DEFINITION
SAP HANA Database - SQL Reference Manual
87 2012-08-21
Example
You first need table which trigger is defined on.
CREATE TABLE TARGET ( A INT);
You also need tables which trigger accesses and modifies.
CREATE TABLE SAMPLE ( A INT);
Following is example of create trigger.
CREATE TRIGGER TEST_TRIGGER AFTER INSERT ON TARGET FOR EACH ROW BEGIN DECLARE SAMPLE_COUNT INT; SELECT COUNT(*) INTO SAMPLE_COUNT FROM SAMPLE; IF :SAMPLE_COUNT = 0 THEN INSERT INTO SAMPLE VALUES(5); ELSEIF :SAMPLE_COUNT = 1 THEN INSERT INTO SAMPLE VALUES(6); END IF; END;
Trigger TEST_TRIGGER will be executed after any record insert execution for TARGET table.Since SAPMLE table record count is zero in the first insert try, the trigger TEST_TRIGGER will insert 5 toSAMPLE table.In the second insertion to TARGET table, the trigger insert 6 to SAMPLE table because its count is two.
INSERT INTO TARGET VALUES (1); SELECT * FROM SAMPLE; 5 INSERT INTO TARGET VALUES (2); SELECT * FROM SAMPLE; 5 6
Followings are more example of create trigger. FOR/WHILE Example
CREATE TABLE TARGET ( A INT); CREATE TABLE SAMPLE ( A INT); CREATE TRIGGER TEST_TRIGGER_WHILE_UPDATE AFTER UPDATE ON TARGET BEGIN DECLARE found INT := 1; DECLARE val INT := 1; WHILE :found <> 0 DO SELECT count(*) INTO found FROM sample WHERE p = :val; IF :found = 0 THEN INSERT INTO sample VALUES(:val,100000); END IF; val := :val + 1; END WHILE; END;
CREATE TABLE TARGET ( A INT); CREATE TABLE control_tab(id INT PRIMARY KEY, name VARCHAR(30), payment INT); CREATE TABLE message_box(message VARCHAR(200), log_time TIMESTAMP);
CREATE TRIGGER TEST_TRIGGER_FOR_INSERT AFTER INSERT ON TARGET BEGIN DECLARE v_id INT := 0; DECLARE v_name VARCHAR(20) := ''; DECLARE v_pay INT := 0; DECLARE v_msg VARCHAR(200) := ''; DELETE FROM message_box; FOR v_id IN 100 .. 103 DO SELECT name, payment INTO v_name, v_pay FROM control_tab WHERE id = :v_id; v_msg := :v_name || ' has ' || TO_CHAR(:v_pay); INSERT INTO message_box VALUES (:v_msg, CURRENT_TIMESTAMP);
SAP HANA Database - SQL Reference Manual
88 2012-08-21
END FOR; END;
handler Examples
CREATE TABLE TARGET ( A INT); CREATE TABLE MYTAB (I INTEGER PRIMARY KEY); CREATE TRIGGER MYTRIG_SQLEXCEPTION AFTER INSERT ON TARGET BEGIN DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT ::SQL_ERROR_CODE, ::SQL_ERROR_MESSAGE FROM DUMMY; INSERT INTO MYTAB VALUES (1); INSERT INTO MYTAB VALUES (1); -- expected unique violation error: 301 -- not reached END; CREATE TRIGGER MYTRIG_SQL_ERROR_CODE AFTER UPDATE ON TARGET BEGIN DECLARE EXIT HANDLER FOR SQL_ERROR_CODE 301 SELECT ::SQL_ERROR_CODE, ::SQL_ERROR_MESSAGE FROM DUMMY; INSERT INTO MYTAB VALUES (1); INSERT INTO MYTAB VALUES (1); -- expected unique violation error: 301 -- not reached END; CREATE TRIGGER MYTRIG_CONDITION AFTER DELETE ON TARGET BEGIN DECLARE MYCOND CONDITION FOR SQL_ERROR_CODE 301; DECLARE EXIT HANDLER FOR MYCOND SELECT ::SQL_ERROR_CODE, ::SQL_ERROR_MESSAGE FROM DUMMY; INSERT INTO MYTAB VALUES (1); INSERT INTO MYTAB VALUES (1); -- expected unique violation error: 301 -- not reached END;
SIGNAL/RESIGNAL Examples
CREATE TABLE TARGET ( A INT); CREATE TABLE MYTAB (I INTEGER PRIMARY KEY);
CREATE TRIGGER MYTRIG_SIGNAL AFTER INSERT ON TARGET BEGIN DECLARE MYCOND CONDITION FOR SQL_ERROR_CODE 10001; DECLARE EXIT HANDLER FOR MYCOND SELECT ::SQL_ERROR_CODE, ::SQL_ERROR_MESSAGE FROM DUMMY; INSERT INTO MYTAB VALUES (1); SIGNAL MYCOND SET MESSAGE_TEXT = 'my error'; -- not reached END; CREATE TRIGGER MYTRIG_RESIGNAL AFTER UPDATE ON TARGET BEGIN DECLARE MYCOND CONDITION FOR SQL_ERROR_CODE 10001; DECLARE EXIT HANDLER FOR MYCOND RESIGNAL; INSERT INTO MYTAB VALUES (1); SIGNAL MYCOND SET MESSAGE_TEXT = 'my error'; -- not reached END;
Transition variable Example
CREATE TABLE TARGET ( A INT, B VARCHAR(10)); CREATE TABLE SAMPLE_OLD ( A INT, B VARCHAR(10)); CREATE TABLE SAMPLE_NEW ( A INT, B VARCHAR(10)); INSERT INTO TARGET VALUES ( 1, 'oldvalue');
CREATE TRIGGER TEST_TRIGGER_VAR_UPDATE AFTER UPDATE ON TARGET REFERENCING NEW ROW mynewrow, OLD ROW myoldrow FOR EACH ROW BEGIN INSERT INTO SAMPLE_new VALUES(:mynewrow.a, :mynewrow.b) INSERT INTO SAMPLE_old VALUES(:myoldrow.a, :myoldrow.b)
SAP HANA Database - SQL Reference Manual
89 2012-08-21
END;
UPDATE TARGER SET b = 'newvalue' WHERE A = 1; SELECT * FROM SAMPLE_NEW; 1, 'newvalue' SELECT * FROM SAMPLE_OLD; 1, 'oldvalue'
CREATE VIEW
Syntax
CREATE VIEW <view_name> [(<column_name>, ... )] AS <subquery>
Syntax Elements
<view_name> ::= [<schema_name>.]<identifier> <schema_name> ::= <identifier> <column_name> ::= <identifier>
Description
The CREATE VIEW statement effectively creates virtual table based on the results of an SQL statement. It isnot a table in a real sense as it does not contain data in itself.
When a column name is specified along with the view name, a query result is displayed with that columnname. If a column name is omitted, a query result gives an appropriate name to the column automatically.The number of column names has to be the same as the number of columns returned from <subquery>.
Update operations on views are supported if the following conditions are met:. Each column in the view must map to a column of a single table. If a column in the base table has NOT NULL constraint without default value, the column must be included inview columns to be an insertable view. Update operation on a view is allowed without this condition.. Must not contain an aggregate or analytic function in a SELECT list for example, the followings are notallowed:. TOP, SET, DISTINCT operator in a SELECT list. GROUP BY, ORDER BY clause. Must not contain a subquery in a SELECT list. Must not contain a sequence value(CURRVAL, NEXTVAL). Must not contain a column view as the base view
If base views or tables are updatable, a view on the base views or tables can be updatable if the aboveconditions are met.
Example
View v is created as selects all records from table a:
CREATE VIEW v AS SELECT * FROM a;
DROP AUDIT POLICY
Syntax
DROP AUDIT POLICY <policy_name>
Syntax Elements
<policy_name> ::= <identifier>
Description
The DROP AUDIT POLICY statement drops an audit policy. <policy_name> must specify an existing auditpolicy. Only database users having the system privilege AUDIT ADMIN are allowed to drop an audit policy. Eachdatabase user having this privilege is allowed to drop any audit policy, no matter if he created it or not. Even if an audit policy is dropped, it may happen, that the audit action specified in the dropped audit policywill be audited further. This will happen, if another audit policy is enabled and specifies that audit action aswell.
SAP HANA Database - SQL Reference Manual
90 2012-08-21
To switch off an audit policy temporarily, it can be disabled and need not be dropped.
System and Monitoring Views
AUDIT_POLICY: shows all audit policies and their states M_INIFILE_CONTENTS: shows the configuration parameter concerning auditing
Only database users with system privilege CATALOG READ, DATA ADMIN or INIFILE ADMIN can see any infoout of the view M_INIFILE_CONTENTS. For other database users this view will be empty.
Example
Assuming that the creation of an audit policy happened before using the following statement:
CREATE AUDIT POLICY priv_audit AUDITING SUCCESSFUL GRANT PRIVILEGE, REVOKE PRIVILEGE, GRANT ROLE, REVOKE ROLE LEVEL CRITICAL;
Now this audit policy has to be dropped.
DROP AUDIT POLICY priv_audit;
DROP FULLTEXT INDEX
Syntax
DROP FULLTEXT INDEX <fulltext_index_name>
Syntax Elements
fulltext_index_name ::= <identifier>
Specifies the index to be dropped.
Description
The DROP FULLTEXT INDEX statement removes a fulltext index.
Example
DROP FULLTEXT INDEX idx;
DROP INDEX
Syntax
DROP INDEX <index_name>
Syntax Elements
index_name ::= <identifier>
The index name identifier specifies the index to be dropped.
Description
The DROP INDEX statement removes an index.
Example
DROP INDEX idx;
DROP SCHEMA
Syntax
DROP SCHEMA <schema_name> [<drop_option>]
SAP HANA Database - SQL Reference Manual
91 2012-08-21
Syntax Elements
<drop_option> ::= CASCADE | RESTRICT
Default = RESTRICT
Restrict drop behavior will drop the object when there is no dependent object. If there is a dependent object,an error will be thrown. Cascaded drop drops the object and dependent objects.
Description
The DROP SCHEMA statement removes a schema.
Example
Schema my_schema is created, table my_schema.t is created and then my_schema is dropped with CASCADEoption:
CREATE SCHEMA my_schema; CREATE TABLE my_schema.t (a INT); DROP SCHEMA my_schema CASCADE;
DROP SEQUENCE
Syntax
DROP SEQUENCE <sequence_name> [<drop_option>]
Syntax Elements
<drop_option> ::= CASCADE | RESTRICT
Default = RESTRICT
Cascaded drop drops the object and dependent objects. When CASCADE option is not specified, non-cascadeddrop behavior drops the object and does not drop the dependent objects, but invalidates the dependentobjects (VIEW, PROCEDURE).
The invalidated object can be revalidated when an object that has same schema and object name is created.Object ID, schema name, and object name pair is reserved for revalidating dependent objects.
Restrict drop behavior will drop the object when there is no dependent object. If there is a dependent object,an error will be thrown.
Description
The DROP SEQUENCE statement removes a sequence.
Example
DROP SEQUENCE s;
DROP SYNONYM
Syntax
DROP [PUBLIC] SYNONYM <synonym_name> [<drop_option>]
Syntax Elements
<synonym_name> ::= <identifier> <drop_option> ::= CASCADE | RESTRICT
Default = RESTRICT
Cascaded drop drops the object and dependent objects. When CASCADE option is not specified, non-cascadeddrop behavior drops the object and does not drop the dependent objects, but invalidates the dependent
SAP HANA Database - SQL Reference Manual
92 2012-08-21
objects (VIEW, PROCEDURE).
The invalidated object can be revalidated when an object that has same schema and object name is created.Object ID, schema name, and object name pair will be reserved for revalidating dependent objects.
Restrict drop behavior will drop the object when there is no dependent object. If there is a dependent object,an error will be thrown.
Description
The DROP SYNONYM statement removes a synonym. The optional PUBLIC element allows for the removal ofa public synonym.
Example
Table a is created, then synonym a_synonym and public synonym pa_synonym are created for table a:
CREATE TABLE a (c INT); CREATE SYNONYM a_synonym FOR a; CREATE PUBLIC SYNONYM pa_synonym FOR a;
Synonym a_synonym and public synonym pa_synonym are dropped:
DROP SYNONYM a_synonym; DROP PUBLIC SYNONYM pa_synonym;
DROP TABLE
Syntax
DROP TABLE <table_name> [<drop_option>]
Syntax Elements
<table_name> ::= [<schema_name>.]<identifier> <schema_name> ::= <identifier> <drop_option> ::= CASCADE | RESTRICT
Default = RESTRICT
Cascaded drop drops the object and dependent objects. When CASCADE option is not specified, non-cascadeddrop behavior drops the object and does not drop the dependent objects, but invalidates the dependentobjects (VIEW, PROCEDURE).
The invalidated object can be revalidated when an object that has the same schema and object name iscreated. The object ID, schema name, and object name pair will be reserved for revalidating dependentobjects.
Restrict drop behavior drops the object when there is no dependent object. If there is a dependent object, anerror is thrown.
Description
The DROP TABLE statement deletes a table.
Example
Table A is created, then dropped:
CREATE TABLE A(C INT); DROP TABLE A;
DROP TRIGGER
Syntax
DROP TRIGGER <trigger_name>
Syntax Elements
SAP HANA Database - SQL Reference Manual
93 2012-08-21
<trigger_name> ::= <identifier>
The name of the trigger to be dropped.
Description
The DROP TRIGGER statement deletes a trigger. Only database users having the TRIGGER privilege for the table which the trigger was defined on, areallowed to drop a trigger for that table.
Example
For this example you need to first create a trigger called test_trigger like below :
CREATE TABLE TARGET ( A INT); CREATE TABLE SAMPLE ( A INT); CREATE TRIGGER TEST_TRIGGER AFTER UPDATE ON TARGET BEGIN INSERT INTO SAMPLE VALUES(3); END;
Now you can drop trigger with:
DROP TRIGGER TEST_TRIGGER;
DROP VIEW
Syntax
DROP VIEW <view_name> [<drop_option>]
Syntax Elements
<view_name> ::= [<schema_name>.]<identifier> <schema_name> ::= <identifier> <drop_option> ::= CASCADE | RESTRICT
Default = RESTRICT
Cascaded drop drops the object and dependent objects. When CASCADE option is not specified, non-cascadeddrop behavior drops the object and does not drop the dependent objects, but invalidates the dependentobjects (VIEW, PROCEDURE).
The invalidated object can be revalidated when an object that has same schema and object name is created.Object ID, schema name, and object name pair will be reserved for revalidating dependent objects.
Restrict drop behavior will drop the object when there is no dependent object. If there is a dependent object,an error will be thrown.
Description
The DROP VIEW statement removes a view.
Example
Table t is created, then view v is created as selects all records from table t:
CREATE TABLE t (a INT); CREATE VIEW v AS SELECT * FROM t;
View v is dropped:
DROP VIEW v;
RENAME COLUMN
Syntax
SAP HANA Database - SQL Reference Manual
94 2012-08-21
RENAME COLUMN <table_name>.<old_column_name> TO <new_column_name>
Syntax Elements
<old_column_name> ::= <identifier> <new_column_name> ::= <identifier>
Description
The RENAME COLUMN statement changes the name of a column.
For the information on column name, please refer to Identifiers.
Example
Table B is created:
CREATE TABLE B (A INT PRIMARY KEY, B INT);
The list of column names in table B is shown:
SELECT COLUMN_NAME, POSITION FROM TABLE_COLUMNS WHERE SCHEMA_NAME = CURRENT_SCHEMA AND TABLE_NAME = 'B' ORDER BY POSITION;
Column A is renamed to C:
RENAME COLUMN B.A TO C;
The list of column names in table B after renaming is shown:
SELECT COLUMN_NAME, POSITION FROM TABLE_COLUMNS WHERE SCHEMA_NAME = CURRENT_SCHEMA AND TABLE_NAME = 'B' ORDER BY POSITION;
RENAME INDEX
Syntax
RENAME INDEX <old_index_name> TO <new_index_name>
Syntax Elements
<old_index_name> ::= <identifier> <new_index_name> ::= <identifier>
Description
The RENAME INDEX statement changes the name of an index.
For the information on index name, please refer to Identifiers.
Example
Table B is created, then index idx is created on column B of table B:
CREATE TABLE B (A INT PRIMARY KEY, B INT); CREATE INDEX idx on B(B);
The list of index names in table B is shown:
SELECT INDEX_NAME FROM INDEXES WHERE SCHEMA_NAME = CURRENT_SCHEMA AND TABLE_NAME = 'B';
Index idx is renamed to new_idx:
RENAME INDEX idx TO new_idx;
The list of index names in table B after renaming is shown:
SAP HANA Database - SQL Reference Manual
95 2012-08-21
SELECT INDEX_NAME FROM INDEXES WHERE SCHEMA_NAME = CURRENT_SCHEMA AND TABLE_NAME = 'B';
RENAME TABLE
Syntax
RENAME TABLE <old_table_name> TO <new_table_name>
Syntax Elements
<old_table_name> ::= <identifier> <new_table_name> ::= <identifier>
Description
The RENAME TABLE statement changes the name of a table to new_table_name in the same schema.
For the information on table name, please refer to Identifiers.
Example
Table A is created in current schema:
CREATE TABLE A (A INT PRIMARY KEY, B INT);
The list of table names in current schema is shown:
SELECT TABLE_NAME FROM TABLES WHERE SCHEMA_NAME = CURRENT_SCHEMA;
Table A renamed to B:
RENAME TABLE A TO B;
The list of table names in current schema after renaming is shown:
SELECT TABLE_NAME FROM TABLES WHERE SCHEMA_NAME = CURRENT_SCHEMA;
Schema mySchema is created, then table mySchema.A is created:
CREATE SCHEMA mySchema; CREATE TABLE mySchema.A (A INT PRIMARY KEY, B INT);
The list of table names in schema mySchema is shown:
SELECT TABLE_NAME FROM TABLES WHERE SCHEMA_NAME = 'MYSCHEMA';
Table mySchema.A is renamed to B:
RENAME TABLE mySchema.A TO B;
The list of table names in schema mySchema after renaming is shown:
SELECT TABLE_NAME FROM TABLES WHERE SCHEMA_NAME = 'MYSCHEMA';
ALTER TABLE ALTER TYPE
Syntax
<table_conversion_clause> ::= [ALTER TYPE] { ROW [THREADS <number_of_threads>] | COLUMN [THREADS <number_of_threads> [BATCH <batch_size>]] }
Syntax Elements
<number_of_threads> ::= <numeric_literal>
Specifies how many threads should be used in parallel for table conversion. The optimal value for number of
SAP HANA Database - SQL Reference Manual
96 2012-08-21
threads should set to the number of available CPU cores.
<batch_size> ::= <numeric_literal>
Specifies the number of rows inserted in batch, and the default value is 2,000,000 which is the optimal value.An insertion into a column table will be immediately committed after every bach_size records insertion,which may reduce memory consumption. BATCH option can be used only when the table is converted fromROW to COLUMN. However, the batch size more than 2,000,000 might cause high memory consumption,thus it is not recommended to change this value.
Description
A new table with a different storage type can be created from an existing table by copying the existingtable's columns and data. This command is used to convert the table storage from ROW to COLUMN or fromCOLUMN to ROW. If the source table was in ROW storage, then the created table will be in COLUMNstorage.
Configuration Parameters
The default number of threads used for table conversion is specified in [sql] section of indexserver.initable_conversion_parallelism = <numeric_literal> (initial value is 8)
Example
For this example you need to first create tables to be converted.
CREATE COLUMN TABLE col_to_row (col1 INT, col2 INT) CREATE ROW TABLE row_to_col (col1 INT, col2 INT)
col_to_row table will be created in COLUMN storage and row_to_col table will be created in ROW storage
Now you can convert the storage type of col_to_row table from COLUMN to ROW with:
ALTER TABLE col_to_row ALTER TYPE ROW
You can also convert the storage type of row_to_col table from ROW to COLUMN with:
ALTER TABLE row_to_col ALTER TYPE COLUMN
In order to convert in batch mode you need to add a batch option at the end of statement:
ALTER TABLE row_to_col ALTER TYPE COLUMN BATCH 10000
TRUNCATE TABLE
Syntax
TRUNCATE TABLE <table_name>
Description
Deletes all rows from a table. TRUNCATE is faster than DELETE FROM when deleting all records from a table,but TRUNCATE cannot be rollbacked. To rollback from deleting records, "DELETE FROM <table_name>"should be used.
HISTORY tables can also be truncated just like normal tables by executing this command. All parts of thehistory table (main, delta, history main and history delta) will be deleted and the content will be lost.
Data Manipulation Statements
DELETE
Syntax
DELETE [HISTORY] FROM <table_name> [WHERE <condition>]
Syntax Elements
SAP HANA Database - SQL Reference Manual
97 2012-08-21
<table_name> ::= [<schema_name>.]<identifier> <schema_name> ::= <identifier>
For descriptions on identifier, please refer to Identifiers.
<condition> ::= <condition> OR <condition> | <condition> AND <condition> | NOT <condition> | ( <condition> ) | <predicate>
For descriptions on predicates, please refer to Predicates.
Description
The DELETE statement deletes records from a table where the condition is met. If the WHERE clause isomitted, then it removes all records from a table.
DELETE HISTORY
DELETE HISTORY will mark the chosen records of the history-part of the history-table for deletion. This meansthat after executing this command, timetravel queries referencing the deleted rows may still see these rows.In order to physically delete these rows the following statements have to be executed:
ALTER SYSTEM RECLAIM VERSION SPACE; MERGE HISTORY DELTA of <table_name>;
Please note that in some cases even the execution of the two statements above may not lead to physicaldeletion.
To check whether the rows are physically deleted, the following statement can be helpful:
SELECT * FROM <table_name> WHERE <condition> WITH PARAMETERS ('REQUEST_FLAGS'= ('ALLCOMMITTED','HISTORYONLY'));
Note:The “WITH PARAMETERS ('REQUEST_FLAGS'= ('ALLCOMMITTED','HISTORYONLY'))” clause may onlybe used for the purpose of validating the result of using the DELETE HISTORY statement.
Example
CREATE TABLE T (KEY INT PRIMARY KEY, VAL INT); INSERT INTO T VALUES (1, 1); INSERT INTO T VALUES (2, 2); INSERT INTO T VALUES (3, 3);
In the example below, one record will be deleted.
DELETE FROM T WHERE KEY = 1;
KEY VAL
2 2
3 3
EXPLAIN PLAN
EXPLAIN PLAN
EXPLAIN PLAN [SET STATEMENT_NAME = <statement_name>] FOR \ref sql_subquery
Syntax Elements
<statement_name> ::= string literal used to identify the name of a specific execution plan in the output table for a given SQL statement.
It is set to NULL if the SET STATEMENT_NAME is not specified.
Description
The EXPLAIN PLAN statement is used to evaluate the execution plan that the SAP HANA Database follows toexecute an SQL statement. The result of the evaluation is stored into the EXPLAIN_PLAN_TABLE view for
SAP HANA Database - SQL Reference Manual
98 2012-08-21
later user examination.
The SQL statement must be data manipulation statement, thus a schema definition language statementcannot be used with the EXPLAIN PLAN command.
You can obtain SQL plan from EXPLAIN_PLAN_TABLE view. The view is shared by all users. Here is an exampleof reading an SQL plan from the view.
<tr><td>SELECT * FROM EXPLAIN_PLAN_TABLE;</td></tr>
Columns in EXPLAIN_PLAN_TABLE view:
Table 1: Column name and description
Column Name Description
STATEMENT_NAMEThe s tring speci fied as STATEMENT_NAME on executing the EXPLAIN PLAN command. Thisi s used to dis tinguish plans from each other when there are multiple plans in theEXPLAIN_PLAN_TABLE view.
OPERATOR_NAME Name of an operator. Deta i l s are described in the fol lowing s ection.
OPERATOR_DETAILSDeta i l s of an operator. Predicates and expres s ions used by the operator are s hownhere.
SCHEMA_NAME Name of the schema of the accessed table.
TABLE_NAME Name of the accessed table.
TABLE_TYPEType of the accessed table. One of the fol lowing options : COLUMN TABLE, ROW TABLE,MONITORING VIEW, JOIN VIEW, OLAP VIEW, CALCULATION VIEW and HIERARCHY VIEW.
TABLE_SIZE Estimated number of rows in the accessed table
OUTPUT_SIZE Estimated number of rows produced by an operator
SUBTREE_COSTEstimated cost of executing the subtree s tarting from an operator. This va lue i s only forrelative comparison.
OPERATOR_ID ID of an operator unique in a plan. IDs are integers s tarting from 1.
PARENT_OPERATOR_IDOPERATOR_ID of the parent of an operator. The shape of an SQL plan i s a tree and thetopology of the tree can be reconstructed us ing OPERATOR_ID andPARENT_OPERATOR_ID. PARENT_OPERATOR_ID of the root operator i s shown as NULL.
LEVELLevel from the root operator. Level of the root operator i s 1, level of a chi ld of the rootoperator i s 2 and so on. This can be uti l i zed for output indentation.
POSITIONPos i tion in the parent operator. Pos i tion of the fi rs t chi ld i s 1, pos i tion of the secondchi ld i s 2 and so on.
HOST The hostname where an operator was executed
PORT The TCP/IP port used to connect to the host
TIMESTAMP Date and time when the EXPLAIN PLAN command was executed.
CONNECTION_ID ID of the connection where the EXPLAIN PLAN command was executed.
EXECUTION_ENGINE Type of the execution engine where an operator i s executed: COLUMN or ROW
OPERATOR_NAME column in EXPLAIN_PLAN_TABLE view: Table 2. List of column engine operators shownin the OPERATOR_NAME column.
Operator Name Des cription
COLUMNSEARCH
Starting pos i tion of column engine operators . OPERATOR_DETAILS l i s ts projected columns .
LIMIT Operator for l imiting the number of output rows
ORDER BY Operator for sorting output rows
HAVING Operator for fi l tering with predicates on top of grouping and aggregation
GROUP BY Operator for grouping and aggregation
DISTINCT Operator for dupl icate el imination
FILTER Operator for fi l tering with predicates
JOIN Operator for joining input relations
COLUMN TABLE Information about accessed column table
MULTIPROVIDEROperator for producing union-a l l of multiple resul ts having the same grouping andaggregation
Table 3. List of row engine operators shown in the OPERATOR_NAME column.
OperatorName
Description
ROW SEARCH Starting pos i tion of row engine operators . OPERATOR_DETAILS l i s ts projected columns .
SAP HANA Database - SQL Reference Manual
99 2012-08-21
LIMIT Operator for l imiting number of output rows
ORDER BY Operator for sorting output rows
HAVING Operator for fi l tering with predicates on top of grouping and aggregation
GROUP BY Operator for grouping and aggregation
MERGEAGGREGATION
Operator for merging the resul ts of multiple para l lel grouping and aggregations
DISTINCT Operator for dupl icate el imination
FILTER Operator for fi l tering with predicates
UNION ALL Operator for producing union-a l l of input relations
MATERIALIZEDUNION ALL
Operator for producing union-a l l of input relations with intermediate resul t materia l i zation
BTREE INDEXJOIN
Operator for joining input relations through B-tree index searches . Join type suffix can beadded. For example, B-tree index join for left outer join i s s hown as BTREE INDEX JOIN (LEFTOUTER). Join without join type suffix means inner join.
CPBTREEINDEX JOIN
Operator for joining input relations through CPB-tree index searches . Join type suffix can beadded.
HASH JOINOperator for joining input relations through probing hash table bui l t on the fly. Join type suffixcan be added.
NESTED LOOPJOIN
Operator for joining input relations through nested looping. Join type suffix can be added.
MIXEDINVERTEDINDEX JOIN
Operator for joining an input relation of row s tore format with a column table without formatconvers ion us ing an inverted index of the column table. Join type suffix can be added.
BTREE INDEXSEARCH
Table access through B-tree index search
CPBTREEINDEX SEARCH
Table access through CPB-tree index search
TABLE SCAN Table access through scanning
AGGR TABLE Operator for aggregating base table di rectly
MONITORSEARCH
Monitoring view access through search
MONITORSCAN
Monitoring view access through scanning
COLUMN SEARCH is a mark for the starting position of column engine operators and ROW SEARCH is a markfor the starting position of row engine operators. In the example below, the intermediate result produced bya COLUMN SEARCH (ID 10) is consumed by a ROW SEARCH (ID 7), and the intermediate result produced bythe ROW SEARCH (ID 7) is consumed by another COLUMN SEARCH (ID 1). The operators below the lowestCOLUMN SEARCH (ID 10) explain how the COLUMN SEARCH (ID 10) is executed. The operators between theROW SEARCH (ID 7) and the COLUMN SEARCH (ID 10) explain how the ROW SEARCH (ID 7) processes theintermediate result produced by the COLUMN SEARCH (ID 10). The operators between the top COLUMNSEARCH (ID 1) and the ROW SEARCH (ID 7) explain how the top COLUMN SEARCH (ID 1) processes theintermediate result produced by the ROW SEARCH (ID 7). Table 4. Operators
OPERATOR_NAME OPERATOR_ID PARENT_OPERATOR_ID LEVEL POSITION
COLUMN SEARCH 1 NULL 1 1
LIMIT 2 1 2 1
ORDER BY 3 2 3 1
GROUP BY 4 3 4 1
JOIN 5 4 5 1
COLUMN TABLE 6 5 6 1
<fontcolor="BLUE">ROW SEARCH</font>
<fontcolor="BLUE">7</font>
<fontcolor="BLUE">5</font>
<fontcolor="BLUE">6</font>
<fontcolor="BLUE">2</font>
BTREE INDEX JOIN 8 7 7 1
BTREE INDEX JOIN 9 8 8 1
<fontcolor="RED">COLUMN SEARCH</font>
<fontcolor="RED">10</font>
<fontcolor="RED">9</font>
<fontcolor="RED">9</font>
<fontcolor="RED">1</font>
FILTER 11 10 10 1
COLUMN TABLE 12 11 11 1
Example of SQL plan explanation Here is an example of SQL plan explanation of a query. The query is fromTPC-H Benchmark. In the example, all tables are located on row store.
DELETE FROM expla in_plan_table WHERE s tatement_name = 'TPC-H Q10';
SAP HANA Database - SQL Reference Manual
100 2012-08-21
EXPLAIN PLAN SET STATEMENT_NAME = 'TPC-H Q10' FORSELECT TOP 20 c_custkey, c_name, SUM(l_extendedprice * (1 - l_discount)) AS revenue, c_acctba l , n_name, c_address , c_phone, c_commentFROM cus tomer, orders , l inei tem, nationWHERE c_custkey = o_cus tkey AND l_orderkey = o_orderkey AND o_orderdate >= '1993-10-01' AND o_orderdate < ADD_MONTHS('1993-10-01',3) AND l_returnflag = 'R' AND c_nationkey = n_nationkeyGROUP BYc_custkey,c_name,c_acctba l ,c_phone,n_name,c_address ,c_commentORDER BY revenue DESC;
SELECT operator_name, operator_deta i l s , table_nameFROM expla in_plan_tableWHERE s tatement_name = 'TPC-H Q10';
The following is the plan explanation of the above query.
OPERATOR_NAME OPERATOR_DETAILS TABLE_NAME
ROW SEARCHCUSTOMER.C_CUSTKEY, CUSTOMER.C_NAME, SUM(LINEITEM.L_EXTENDEDPRICE * (1 - LINEITEM.L_DISCOUNT)), CUSTOMER.C_ACCTBAL, NATION.N_NAME, CUSTOMER.C_ADDRESS, CUSTOMER.C_PHONE, CUSTOMER.C_COMMENT
None
LIMIT NUM RECORDS: 20
ORDER BY SUM(LINEITEM.L_EXTENDEDPRICE * (1 - LINEITEM.L_DISCOUNT)) DESC None
MERGE AGGREGATION NUM PARTITIONS: 4 None
GROUP BYGROUPING: NATION.N_NAME, R_CUSTOMER.C_CUSTKEY, AGGREGATION: SUM(LINEITEM.L_EXTENDEDPRICE * (1 - LINEITEM.L_DISCOUNT))
None
CPBTREE INDEX JOININDEX NAME: _SYS_TREE_RS_279_#0_#P0,INDEX CONDITION: ORDERS.O_ORDERKEY = LINEITEM.L_ORDERKEY,INDEX FILTER: 'R' = LINEITEM.L_RETURNFLAG
LINEITEM
BTREE INDEX JOININDEX NAME: _SYS_TREE_RS_285_#0_#P0,INDEX CONDITION: CUSTOMER.C_NATIONKEY = NATION.N_NATIONKEY
NATION
BTREE INDEX JOININDEX NAME: _SYS_TREE_RS_283_#0_#P0,INDEX CONDITION: ORDERS.O_CUSTKEY = CUSTOMER.C_CUSTKEY
CUSTOMER
TABLE SCAN FILTER CONDITION: ORDERS.O_ORDERDATE < '1994-01-01' AND ORDERS.O_ORDERDATE >= '1993-10-01' ORDERS
This means that:1. TABLE SCAN will be executed on ORDERS with the FILTER CONDITION.2. BTREE INDEX JOIN will be executed with the B-tree index of CUSTOMER and the result of the below TABLESCAN.3. BTREE INDEX JOIN will be executed with the B-tree index of NATION and the result of the below BTREEINDEX JOIN.4. CPBTREE INDEX JOIN will be executed with the CPB-tree index of LINEITEM and the result of the belowBTREE INDEX JOIN.5. GROUP BY will be executed with the result of the below CPBTREE INDEX JOIN, with 4 threads.6. MERGE AGGREGATION will be executed with the result of the GROUP BY below.
INSERT
Syntax
SAP HANA Database - SQL Reference Manual
101 2012-08-21
INSERT INTO <table_name> [ <column_list_clause> ] { <value_list_clause> | <subquery> }
Syntax Elements
<table_name> ::= [ <schema_name>. ]<identifier> <schema_name> ::= <identifier>
<column_list_clause> ::= ( <column_name>, ... ) <column_name> ::= <identifier>
For descriptions on identifier, please refer to Identifiers.
<value_list_clause> ::= VALUES ( <expression>, ... )
For descriptions on expressions, please refer to Expressions.
Description
The INSERT statement adds records to a table. A subquery that returns records can be used to insert recordsinto the table. If the subquery does not return any records, then the database will not insert any records intothe table. The column list can be specified with the INSERT statement. The column which isn't included in thecolumn list will be shown as a default value. If the column list is omitted, the database inserts all columns inthe table.
Example
CREATE TABLE T (KEY INT PRIMARY KEY, VAL1 INT, VAL2 NVARCHAR(20));
In the below example, you can insert the values.
INSERT INTO T VALUES (1, 1, 'The first');
KEY VAL1 VAL2
1 1 The fi rs t
You can insert a new value into the specified column.
INSERT INTO T (KEY) VALUES (2);
KEY VAL1 VAL2
1 1 The fi rs t
2 NULL NULL
And you can use the subquery.
INSERT INTO T SELECT 3, 3, 'The third' FROM DUMMY;
KEY VAL1 VAL2
1 1 The fi rs t
2 NULL NULL
3 3 The thi rd
LOAD
Syntax
LOAD <table_name> {DELTA | ALL | (<column_name>, ...)}
Description
The LOAD statement loads the column store table data to memory explicitely instead of on first access.
Syntax Elements
<table_name> ::= <identifier>
The name of the table to be loaded into memory
SAP HANA Database - SQL Reference Manual
102 2012-08-21
<column_name> ::= <identifier>
The name of the column to be loaded into memory.
DELTADELTA part of the column store table is loaded into memory. Since the column store is read optimized andcompressed, deltas are introduced to optimize insert or updates. All insertions are passed to a delta.
ALL ALL data of the column store table in main and delta is loaded into memory.
Example
The example below loads the whole table a_table into memory
LOAD a_table all;
The example below loads the columns a_column and another_column of table a_table into memory
LOAD a_table (a_column,another_column);
The load status of a table can be querieed by
select loaded from m_cs_tables where table name = '<table_name>'
MERGE DELTA
Syntax
MERGE [HISTORY] DELTA OF <table_name> [PART n] [WITH PARAMETERS (<parameter_key_value>, ...)]
Syntax Elements
WITH PARAMETERS (<parameter_list>):
Column store-specific options can be passed in using the "WITH PARAMETERS" clause.
<table_name> ::= [<schema_name>.]<identifier> <schema_name> ::= <identifier> <parameter_list> ::= <parameter>,<parameter_list> <parameter> ::= <parameter_name> = <parameter_setting> <parameter_name> ::= 'SMART_MERGE' | 'MEMORY_MERGE' <parameter_setting> ::= 'ON' | 'OFF'
Current parameters: 'SMART_MERGE' = 'ON' | 'OFF' When SMART_MERGE is ON, the database does a smartmerge, this means database decides whether to merge or not based on merge criteria specified inautomerge section of indexserver configuration
'MEMORY_MERGE' = 'ON' | 'OFF' Database merges table delta part in memory only, it will not be persisted.
Description
The MERGE DELTA statement merges the column store table delta part to its main part. Since the columnstore is read optimized and compressed, deltas are introduced to optimize insert or updates in the optimizedway. All insertions are passed to the delta part. At a certain point in time, the delta can be merged into themain column table. Delta will be merged into main column table.
HISTORY - Can be specified to merge the history delta part into the history main part on column storetemporal tables. The table is a temporal table with additional table history.PART - Can be specified to merge the delta of a specific table partition to its main part. The table waspartitioned.
Example
MERGE DELTA OF A; Merges the column store table delta part to its main part.
MERGE DELTA OF A WITH PARAMETERS('SMART_MERGE' = 'ON'); Smart merges the column store table delta part to its main part.
SAP HANA Database - SQL Reference Manual
103 2012-08-21
MERGE DELTA OF A WITH PARAMETERS('SMART_MERGE' = 'ON', 'MEMORY_MERGE' = 'ON'); Smart merges the column store table delta part to its main part non-persistent, in memory only.
MERGE DELTA OF A PART 1; Merge the delta of partition no. 1 of table with name "A" to main part of partion no. 1.
MERGE HISTORY DELTA OF A; Merge the history delta part of table with name "A" into its history main part.
MERGE HISTORY DELTA OF A PART 1; Merges the column store table delta part of the history of table with name "A" to its history main part.
REPLACE | UPSERT
Syntax
UPSERT <table_name> [ <column_list_clause> ] { <value_list_clause> [ WHERE <condition> | WITH PRIMARY KEY ] | <subquery> } REPLACE <table_name> [ <column_list_clause> ] { <value_list_clause> [ WHERE <condition> | WITH PRIMARY KEY ] | <subquery> }
Syntax Elements
<table_name> ::= [ <schema_name>. ]<identifier> <schema_name> ::= <identifier>
<column_list_clause> ::= ( <column_name>, ... ) <column_name> ::= <identifier>
For descriptions on identifier, please refer to Identifiers.
<value_list_clause> ::= VALUES ( <expression>, ... )
For descriptions on expressions, please refer to Expressions.
<condition> ::= <condition> OR <condition> | <condition> AND <condition> | NOT <condition> | ( <condition> ) | <predicate>
For descriptions on predicates, please refer to Predicates.
Description
Descriptions to detailed syntax elements of this SQL Command.
The UPSERT or REPLACE statement without a subquery is similar to the UPDATE statement. The onlydifference is when the WHERE clause condition is false, it adds a new record to the table like the INSERTstatement.
In case of a table which has a PRIMARY KEY, the PRIMARY KEY column must be included in the column list.Columns defined with NOT NULL without default specification have to be included in the column list as well.Other columns are filled with default value or NULL if not specified.
The UPSERT or REPLACE statement with a subquery works like the INSERT statement, except that if an oldrow in the table has the same value as a new row for a PRIMARY KEY, then the old row is changed by valuesof the returned record from a subquery. Unless the table has a PRIMARY KEY, it becomes equivalent toINSERT because there is no index to be used to determine whether or not a new row duplicates another.
The UPSERT or REPLACE statement with a 'WITH PRIMARY KEY' is same as one with the subquery. It worksbased on the PRIMARY KEY.
Example
CREATE TABLE T (KEY INT PRIMARY KEY, VAL INT);
You can insert a new value.
SAP HANA Database - SQL Reference Manual
104 2012-08-21
UPSERT T VALUES (1, 1);
KEY VAL
1 1
If the condition in WHERE clause is false, a new value will be inserted.
UPSERT T VALUES (2, 2) WHERE KEY = 2;
KEY VAL
1 1
2 2
And you can update the first record of the column "VAL".
UPSERT T VALUES (1, 9) WHERE KEY = 1;
KEY VAL
1 9
2 2
Or you can use the "WITH PRIMARY KEY" keyword.
UPSERT T VALUES (1, 8) WITH PRIMARY KEY;
KEY VAL
1 8
2 2
You can also insert values with a subquery.
UPSERT T SELECT KEY + 2, VAL FROM T;
KEY VAL
1 8
2 2
3 8
4 2
SELECT
Syntax
<select_statement> ::= <subquery> [ <for_update> | <time_travel> ] | ( <subquery> ) [ <for_update> | <time_travel> ] <subquery> ::= <select_clause> <from_clause> [<where_clause>] [<group_by_clause>] [<having_clause>] [{<set_operator> <subquery>, ... }] [<order_by_clause>] [<limit>]
Syntax Elements
SELECT clause
The select clause specifies an output to be returned either to users or to an outer select clause if exists.
<select_clause> ::= SELECT [TOP <integer>] [ ALL | DISTINCT ] <select_list> <select_list> ::= <select_item>[, ...] <select_item> ::= [<table_name>.] <asterisk> | <expression> [ AS <column_alias> ] <table_name> ::= [<schema_name>.] <identifier> <schema_name> ::= <identifier> <column_name> ::= <identifier> <column_alias> ::= <identifier> <asterisk> ::= *
SAP HANA Database - SQL Reference Manual
105 2012-08-21
TOP n TOP can be used to return the first n records from the SQL statement.
DISTINCT and ALL DISTINCT can be used to return only one copy of each set of duplicate records selected. ALL can be used to return all rows selected, including all copies of duplicates. The default is ALL.
select_list The select list allows users to specify columns they want to retrieve from tables.
asterisk Asterisk (*) can be used to select all columns from all tables or views listed in the FROM clause. If a schemaname and a table name or a table name is provided with asterisk(*), it is used to limit the scope of the resultset to the specified table. column_alias A column alias can be used to represent an expression simply.
FROM clause
The from clause specifies inputs such as tables, views, and subqueries to be used in the select statement.
<from_clause> ::= FROM {<table>, ... } <table> ::= <table_name> [ [AS] <table_alias> ] | <subquery> [ [AS] <table_alias> ] | <joined_table>
<table_alias> ::= <identifier> <joined_table> ::= <table> [<join_type>] JOIN <table> ON <predicate> | <table> CROSS JOIN <table> | <joined_table>
<join_type> ::= INNER | { LEFT | RIGHT | FULL } [OUTER]
table alias A table alias can be used to represent a table or a subquery simply.
The join_type specifies the type of join being performed. LEFT indicates a left outer join, RIGHT indicates aright outer join, and FULL indicates a full outer join. OUTER may or may not be used when an outer join isbeing performed. ON <predicate> The ON clause specifies a join predicate. CROSS JOIN CROSS indicates that a cross join is being performed. A cross join produces the cross-product of two tables.
WHERE clause
The WHERE clause is used to specify predicates on inputs in the FROM clause, so users can retrieve thedesired records.
<where_clause> ::= WHERE <condition> <condition> ::= <condition> OR <condition> | <condition> AND <condition> | NOT <condition> | ( <condition> ) | <predicate> <predicate> ::= <comparison_predicate> | <range_preciate> | <in_predicate> | <exist_predicate> | <like_predicate> | <null_predicate> <comparison_predicate> ::= <expression> { = | != | <> | > | < | >= | <= } [ ANY | SOME | ALL ] ({<expression_list> | <subquery>}) <range_predicate> ::= <expression> [NOT] BETWEEN <expression> AND <expression> <in_predicate> ::= <expression> [NOT] IN ( { <expression_list> | <subquer
SAP HANA Database - SQL Reference Manual
106 2012-08-21
y> } ) <exist_predicate> ::= [NOT] EXISTS ( <subquery> ) <like_predicate> ::= <expression> [NOT] LIKE <expression> [ESCAPE <expression>] <null_predicate> ::= <expression> IS [NOT] NULL
<expression_list> ::= {<expression>, ... }
GROUP BY clause
<group_by_clause> ::=
GROUP BY { <group_by_expression_list> | <grouping_set> } <group_by_expression_list> ::= { <expression>, ... }
<grouping_set> ::= { GROUPING SETS | ROLLUP | CUBE } [BEST <integer>] [LIMIT <integer>[OFFSET <integer>] ] [WITH SUBTOTAL] [WITH BALANCE] [WITH TOTAL] [TEXT_FILTER <filterspec> [FILL UP [SORT MATCHES TO TOP]]] [STRUCTURED RESULT [WITH OVERVIEW] [PREFIX <string_literal>] | MULTIPLE RESULTSETS] ( <grouping_expression_list> )
<grouping_expression_list> ::= { <grouping_expression>, ... } <grouping_expression> ::= <expression> | ( <expression>, ... ) | ( ( <expression>, ... ) <order_by_clause> )
The GROUP BY clause is used to group the selected rows based on the values in the specified columns.
GROUPING SETS Generates results with specified multiple groupings of data in a single statement. If no additional options suchas best and limit are set, the result is the same as UNION ALL of the aggregation of each specified group. Forexample, "select col1, col2, col3, count(*) from t group by grouping sets ( (col1, col2), (col1, col3) )" isequivalent to "select col1, col2, NULL, count(*) from t group by col1, col2 union all select col1, NULL, col3,count(*) from t group by col1, col3". In the grouping-sets query each of (col1, col2) and (col1, col3) specifiesthe grouping.
ROLLUP Generates results with multiple levels of aggregation in a single statement. For example, "rollup (col1, col2,col3)" is equivalent to "grouping sets ( (col1, col2, col3), (col1, col2), (col1) )" with an additional aggregationwithout grouping. Thus, the number of grouping that result set contains is the number of columns in ROLLUPlist plus one for last aggregation if there is no additional option.
CUBE Generates results with multiple levels of aggregations in a single statement. For example, "cube (col1, col2,col3)" is equivalent to "grouping sets ( (col1, col2, col3), (col1, col2), (col1, col3), (col2, col3), (col1), (col2),(col3) )" with an additional aggregation without grouping. Thus, the number of grouping that result setcontains is the same as all possible permutations of columns in the CUBE list plus one for the last aggregationif there is no additional option.
BEST n Returns only the top-n grouping sets sorted in descending order of the number of rows aggregated in eachgrouping set. n can be any of zero, positive, and negative. When n is zero, it is the same with no BEST option.When n is negative, it means sorting in ascending order.
LIMIT n1 [OFFSET n2] Returns the first n1 grouped records after skipping n2 ones for each grouping set.
WITH SUBTOTAL Returns for each grouping set an additional subtotal of the returned results as controlled by OFFSET or LIMIT.Unless OFFSET and LIMIT is set, the value is the same as the one for WITH TOTAL.
WITH BALANCE Returns for each grouping set an additional aggregated value of the remaining values not returned ascontrolled by OFFSET or LIMIT.
WITH TOTAL Returns for each grouping set an additional row that is the aggregated total value. OFFSET and LIMIT options
SAP HANA Database - SQL Reference Manual
107 2012-08-21
cannot change this value.
TEXT_FILTER <filterspec> Performs text filtering or highlighting on the grouping columns with <filterspec>, which is a single-quotedstring that follows the below syntax.
<filterspec> ::= '[<prefix>]<element>{<subsequent>, ...}' <prefix> ::= + | - | NOT <element> ::= <token> | <phrase> <token> ::= !! Unicode letters or digits <phrase> ::= !! double-quoted string that does not contain double quotations inside <subsequent> ::= [<prefix_subsequent>]<element> <prefix_subsequent> ::= + | - | NOT | AND | AND NOT | OR
A filter defined by <filterspec> is a token/phrase or tokens/phrases connected with logical operators such asAND, OR and NOT. A token matches a string that contains its corresponding word case-insensitively. Forexample, 'ab' matches 'ab cd' and 'cd Ab' but does not match 'abcd' A token can contain wildcard characters 'that matches any string and ' that matches any character. Inside phrase, however, ' and ' do not work aswildcard characters. With tokens and phrases logical operators AND, OR and NOT may be used together.Since OR is the default operator, 'ab cd' is the same as 'ab OR cd' Note that logical operators should bewritten in uppercase characters. As a kind of logical operators, prefixes '+' and '-' mean inclusion (AND) andexclusion (AND NOT), respectively. For example, 'ab -cd' is the same as 'ab AND NOT cd' If there is no FILL UPoption, only grouped records that have matching values are returned. Note that a filter is applied to only thefirst grouping column in each grouping set.
FILL UP Returns not only matched grouped records, but also non-matched ones. Function text_filter is useful toidentify which one is matched. Refer to 'Related Functions' below.
SORT MATCHES TO TOP Returns matching values before non-matching ones for each grouping set. This option cannot be used withSUBTOTAL, BALANCE and TOTAL.
STRUCTURED RESULT Returns results as temporary tables. For each grouping set a single temporary table is created. If WITHOVERVIEW option is set, an additional temporary table is created for the overview of grouping sets. Thenames of temporary tables are specified by PREFIX option.
WITH OVERVIEW Returns the overview in a separate table additionally.
PREFIX value Specifies a prefix for naming the temporary tables. It must start with "#", which means the temporary table.If omitted, the default prefix is "#GN". Then, the concatenation of this prefix value and a nonnegative integernumber is used as the name of temporary tables; for example, "#GN0", "#GN1" and "#GN2". Refer to'Return Format' below.
MULTIPLE RESULTSETS Returns results in multiple result sets.
Related Functions grouping_id ( <grouping_column1, ..., grouping_columnn> ) function returns an integer number to identifywhich grouping set each grouped record belongs to. text_filter ( <grouping_column> ) function, which is usedwith TEXT_FILTER, FILL UP, and SORT MATCHES TO TOP, displays matching values or NULL. NULL is displayedfor non-matching values when FILL UP option is specified.
Return Format If neither STRUCTURED RESULT nor MULTIPLE RESULTSETS is set, the unioned result of all grouping sets isreturned, with NULL values filling up attributes that are not included in a specific grouping set. WithSTRUCTURED RESULT, temporary tables are created additionally which can be queried using "SELECT *FROM <table name>" in the same session. The name of the tables follows the form
<PREFIX>0: this table will contain the overview if WITH OVERVIEW is specified <PREFIX>n: n-th grouping set subject to re-ordering by the BEST parameter With MULTIPLE RESULTSETS, multiple result sets are returned. Grouped records for each grouping setare in a single result set.
HAVING clause
The HAVING clause is used to select the specified groups that satisfy the predicates. If this clause is omitted,all groups are selected.
SAP HANA Database - SQL Reference Manual
108 2012-08-21
<having_clause> ::= HAVING <condition>
SET OPERATORS
The set operators enable more than one select statements to be combined and only one result set isreturned.
<set_operator> ::= UNION [ ALL | DISTINCT ] | INTERSECT [DISTINCT] | EXCEPT [DISTINCT]
UNION ALL Selects all records from all select statements. Duplicates are not removed.
UNION [DISTINCT] Selects all unique records from all select statements by removing duplicates found from different selectstatements. UNION is the same as UNION DISTINCT.
INTERSECT [DISTINCT] Returns all unique records that exist in all select statements in common.
EXCEPT [DISTINCT] Returns all unique records from the first select statements after removing the duplicates in the followingselect statements.
ORDER BY clause
<order_by_clause> ::= ORDER BY { <order_by_expression>, ... } <order_by_expression> ::= <expression> [ ASC | DESC ] | <position> [ ASC | DESC <position> ::= <integer>
The ORDER BY clause is used to sort records by expressions or positions. A position means the index of theselect list. For "select col1, col2 from t order by 2", 2 indicates col2 as the second expression used in theselect list. ASC is used to sort records in ascending order and DESC is used to sort records in descending order.The default value is ASC.
LIMIT
LIMIT keyword specifies the number of output records.
<limit> ::= LIMIT <integer> [ OFFSET <integer> ]
LIMIT n1 [OFFSET n2] Returns the first n1 records after skipping n2 ones.
FOR UPDATE
FOR UPDATE keywords lock the selected records so that other users cannot lock or change the records untilend of this transaction.
<for_update> ::= FOR UPDATE
TIME TRAVEL
Keywords related wtih time travel can be used for statement-level time travel to go back to the snapshotspecified by commit_id or utctimestamp.
<time_travel> ::= AS OF { { COMMIT ID <commit_id> } | { UTCTIMESTAMP <timestamp> } }
Time travel is possible only with a history column table. <commit_id> can be obtained fromm_history_index_last_commit_id after each commit and its related <timestamp> can be obtained fromsys.m_transaction_history. Here is an example.
create history column table x ( a int, b int ); // after turnning off auto commit insert into x values (1,1); commit; select last_commit_id from m_history_index_last_commit_id where session_id = current_connection; // e.g., 10 insert into x values (2,2);
SAP HANA Database - SQL Reference Manual
109 2012-08-21
commit; select last_commit_id from m_history_index_last_commit_id where session_id = current_connection; // e.g., 20 delete from x; commit; select last_commit_id from m_history_index_last_commit_id where session_id = current_connection; // e.g., 30 select * from x as of commit id 30; // return nothing select * from x as of commit id 20; // return two records (1,1) and (2,2) select * from x as of commit id 10; // return one record (1,1)
select commit_time from sys.transaction_history where commit_id = 10; // e.g., '2012-01-01 01:11:11' select commit_time from sys.transaction_history where commit_id = 20; // e.g., '2012-01-01 02:22:22' select commit_time from sys.transaction_history where commit_id = 30; // e.g., '2012-01-01 03:33:33'
select * from x as of utctimestamp '2012-01-02 02:00:00'; // return one record (1,1) select * from x as of utctimestamp '2012-01-03 03:00:00'; // return two records (1,1) and (2,2) select * from x as of utctimestamp '2012-01-04 04:00:00'; // return nothing
Example
Here is t1 table.
drop table t1;
create column table t1 ( id int primary key, customer varchar(5), year int, product varchar(5), sales int ); insert into t1 values(1, 'C1', 2009, 'P1', 100); insert into t1 values(2, 'C1', 2009, 'P2', 200); insert into t1 values(3, 'C1', 2010, 'P1', 50); insert into t1 values(4, 'C1', 2010, 'P2', 150); insert into t1 values(5, 'C2', 2009, 'P1', 200); insert into t1 values(6, 'C2', 2009, 'P2', 300); insert into t1 values(7, 'C2', 2010, 'P1', 100); insert into t1 values(8, 'C2', 2010, 'P2', 150);
The following GROUPING SETS query is equivalent to the second below group-by query. Note that two groupsinside grouping sets in the first query are specified at each group by in the second query.
select customer, year, product, sum(sales) from t1 group by GROUPING SETS ( (customer, year), (customer, product) );
select customer, year, NULL, sum(sales) from t1 group by customer, year union all select customer, NULL, product, sum(sales) from t1 group by customer, product;
ROLLUP and CUBE are concise representations of grouping sets that are used frequently. The followingROLLUP query is equivalent to the second below grouping-set query.
select customer, year, sum(sales) from t1 group by ROLLUP(customer, year);
select customer, year, sum(sales) from t1 group by grouping sets ( (customer, year), (customer) ) union all select NULL, NULL, sum(sales)
SAP HANA Database - SQL Reference Manual
110 2012-08-21
from t1;
The following CUBE query is equivalent to the second below grouping-set query.
select customer, year, sum(sales) from t1 group by CUBE(customer, year);
select customer, year, sum(sales) from t1 group by grouping sets ( (customer, year), (customer), (year) ) union all select NULL, NULL, sum(sales) from t1;
BEST 1 specifies that the following query returns only top-1 best group. In this example, 4 records exist for(customer, year) group and 2 records exist for (product) group, so the former 4 records are returned. For'BEST -1' instead of 'BEST 1', the latter 2 records are returned.
select customer, year, product, sum(sales) from t1 group by grouping sets BEST 1 ( (customer, year), (product) );
LIMIT 2 limits the number of records to maximum 2 for each group. For (customer, year) group, the numberof its records are 4, then only first 2 records will be returned. For (product) group, the number of its recordsare 2, so all the records will be returned.
select customer, year, product, sum(sales) from t1 group by grouping sets LIMIT 2 ( (customer, year), (product) );
WITH SUBTOTAL produces additional one record for each group to display subtotal of returned records.These subtotal records get NULL for each of customer, year, product columns and the sum of sum(sales)values in the select list.
select customer, year, product, sum(sales) from t1 group by grouping sets LIMIT 2 WITH SUBTOTAL ( (customer, year), (product) );
WITH BALNACE produces additional one record for each group to display subtotal of unreturned records.
select customer, year, product, sum(sales) from t1 group by grouping sets LIMIT 2 WITH BALANCE ( (customer, year), (product) );
WITH TOTAL produces additional one record for each group to display total of all grouped records withoutregard that the records are returned or not.
select customer, year, product, sum(sales) from t1 group by grouping sets LIMIT 2 WITH TOTAL ( (customer, year), (product)
SAP HANA Database - SQL Reference Manual
111 2012-08-21
);
TEXT_FILTER allows users to retrieve the first column of each group with a given <filterspec>. The followingquery will search columns ending with '2': customers for the first grouping set and products for the secondone. Only matched three records will be returned. TEXT_FILTER function in the select list is useful to seewhich values are matched.
select customer, year, product, sum(sales), text_filter(customer), text_filter(product) from t1 group by grouping sets TEXT_FILTER '*2' ( (customer, year), (product) );
FILL UP is used to return both matched and non-matched records with <filterspec>. Therefore, the followingquery returns six records whereas the previous query does three ones.
select customer, year, product, sum(sales), text_filter(customer), text_filter(product) from t1 group by grouping sets TEXT_FILTER '*2' FILL UP ( (customer, year), (product) );
SORT MATCHES TO TOP is used to raise matched records up. For each grouping set, its grouped records willbe sorted.
select customer, year, product, sum(sales), text_filter(customer), text_filter(product) from t1 group by grouping sets TEXT_FILTER '*2' FILL UP SORT MATCHES TO TOP ( (customer, year), (product) );
STRUCTURED RESULT creates temporary tables: one for each grouping set and one more for the overviewtable optionally. "#GN1" table is for (customer, year) grouping set and "#GN2" table is for (product) one.Note that each table contains only related columns. That is, "#GN1" table does not have "product" columnand "#GN2" table does not have "customer" and "year" columns.
select customer, year, product, sum(sales) from t1 group by grouping sets STRUCTURED RESULT ( (customer, year), (product) );
select * from "#GN1"; select * from "#GN2";
WITH OVERVIEW creates a temporary table "#GN0" for the overview table.
drop table "#G1"; drop table "#G2";
select customer, year, product, sum(sales) from t1 group by grouping sets structured result WITH OVERVIEW ( (customer, year), (product) );
select * from "#GN0"; select * from "#GN1"; select * from "#GN2";
Users can change the names of temporary tables by using PREFIX keyword. Note that the names still muststart with '#', which is the prefix of temporary tables.
SAP HANA Database - SQL Reference Manual
112 2012-08-21
select customer, year, product, sum(sales) from t1 group by grouping sets STRUCTURED RESULT WITH OVERVIEW PREFIX '#MYTAB' ( (customer, year), (product) );
select * from "#MYTAB0"; select * from "#MYTAB1"; select * from "#MYTAB2";
Temporary tables are dropped when the corresponding session is closed or when a user executes a dropcommand. A list of temporary tables are seen in m_temporary_tables.
select * from m_temporary_tables;
MULTIPLE RESULTSETS returns resultsets as multiple resultsets. In SAP HANA Studio, the following query willreturn three resultsets: one is for the overview table and two are for grouping sets.
select customer, year, product, sum(sales) from t1 group by grouping sets MULTIPLE RESULTSETS ( (customer, year), (product) );
UNLOAD
Syntax
UNLOAD <table_name>
Syntax Elements
<table_name> ::= <identifier>
The name of the table to be unloaded from memory
Description
The UNLOAD statement unloads the column store table from memory. This can be done to free up memory.The table will be loaded again on next access.
Example
In the example below the table a_table is to be unloaded from memory
UNLOAD a_table;
The load status of a table can be querieed by
select loaded from m_cs_tables where table name = '<table_name>'
UPDATE
Syntax
UPDATE <table_name> [ <alias_name> ] <set_clause> [ WHERE <condition> ]
Syntax Elements
<table_name> ::= [<schema_name>.]<identifier> <schema_name> ::= <identifier> <alias_name> ::= [AS] <identifier>
For descriptions on identifier, please refer to Identifiers.
SAP HANA Database - SQL Reference Manual
113 2012-08-21
<set_clause> ::= SET {<column_name> = <expression>},...
For descriptions on expressions, please refer to Expressions.
<condition> ::= <condition> OR <condition> | <condition> AND <condition> | NOT <condition> | ( <condition> ) | <predicate>
For descriptions on predicates, please refer to Predicates.
Description
The UPDATE statement changes the values of the records of a table where the condition is met. If theWHERE clause condition is true, the result of expression is assigned to that column. If the WHERE clause isomitted, then it updates all records of a table.
Example
CREATE TABLE T (KEY INT PRIMARY KEY, VAL INT); INSERT INTO T VALUES (1, 1); INSERT INTO T VALUES (2, 2);
If the condition in WHERE clause is true, the record will be updated.
UPDATE T SET VAL = VAL + 1 WHERE KEY = 1;
KEY VAL
1 2
2 2
If the WHERE clause is omitted, all records will be updated.
UPDATE T SET VAL = KEY + 10;
KEY VAL
1 11
2 12
System Management Statements
SET SYSTEM LICENSE
Syntax
SET SYSTEM LICENSE '<license key>'
Description
Install a license key to the database instance. The license key (<license key>="">) is to be copied and pastedfrom the license key file. The system privilege LICENSE ADMIN is required to execute this command.
Example
SET SYSTEM LICENSE '----- Begin SAP License ----- SAPSYSTEM=HD1 HARDWARE-KEY=K4150485960 INSTNO=0110008649 BEGIN=20110809 EXPIRATION=20151231 LKEY=... SWPRODUCTNAME=SAP-HANA SWPRODUCTLIMIT=2147483647 SYSTEM-NR=00000000031047460'
ALTER SYSTEM ALTER CONFIGURATION
Syntax
SAP HANA Database - SQL Reference Manual
114 2012-08-21
ALTER CONFIGURATION (<filename>, <layer>[, <layer_name>]) SET | UNSET <parameter_key_value_list> [ WITH RECONFIGURE]
Syntax Elements
<filename> ::= <string_literal>
The filename is 'indexserver.ini' in the case of row-store engine configuration. The filename used must be oneof the ini files located on the 'DEFAULT' layer. If the file selected by filename does not exist on the requiredlayer, the file will be created in the case of a SET command.
<layer> ::= <string_literal>
Sets the target layer for the configuration change. This parameter can be either 'SYSTEM' or 'HOST'. TheSYSTEM layer is the recommended layer for customer settings. The HOST layer should generally only be usedfor minor configuration, for example parameters contained in daemon.ini.
<layer_name> ::= <string_literal>
If the layer parameter above is set to 'HOST', layer_name is used to target either a tenant name or a targethost name. For example, 'selxeon12' would target the 'selxeon12' host.
SET The SET command updates the value of a key if the key already exists, or inserts it if required.
UNSET The UNSET command removes a key and its associated value.
<parameter_key_value_list> ::= {(<section_name>,<parameter_name>) = <parameter_value>},...
Specifies the section, key and value of the ini file parameter to be altered as follows:
<section_name> ::= <string_literal>
The section name of the parameter to be altered.
<parameter_name> ::= <string_literal>
The name of the parameter to be altered.
<parameter_value> ::= <string_literal>
The value of the parameter to be altered.
WITH RECONFIGURE When WITH RECONFIGURE is specified the configuration changes will be directly applied to the running SAPHANA Database instance.When WITH RECONFIGURE is not specified the new configuration will be written to the ini file, however thenew value is not applied to the current running system and will only be applied at the next startup of thedatabase. This means that there can be inconsistencies between the ini file contents and the actualconfiguration value that the SAP HANA Database is currently using.
Description
Sets or removes configuration parameters in an ini file. Ini file configuration is used for the layeredconfiguration for DEFAULT, SYSTEM, HOST layers.
Note:The DEFAULT layer configuration cannot be changed or removed using this command.
The following is an example of ini file locations:
DEFAULT: /usr/sap/<SYSTEMNAME>/HDB<INSTANCENUMBER>/exe/config/indexserver.iniSYSTEM: /usr/sap/<SYSTEMNAME>/SYS/global/hdb/custom/config/indexserver.iniHOST: /usr/sap/<SYSTEMNAME>/HDB<INSTANCENUMBER>/<HOSTNAME>/indexserver.ini
The priority of the configuration layers is as follows: DEFAULT < SYSTEM < HOST.
SAP HANA Database - SQL Reference Manual
115 2012-08-21
This means that the layer that has the highest priority is the HOST layer, followed by the SYSTEM layer andfinally the DEFAULT layer. The configuration with the highest priority will be applied to the runningenvironment. If the highest priority level configuration is removed, then the configuration with the nexthighest priority will be applied.
System and Monitoring Views
Currently available ini files are listed in the M_INIFILES system table and the current configuration is availablein M_INIFILE_CONTENTS system table.
Example
Example syntax to change system layer configuration is as follows:
ALTER SYSTEM ALTER CONFIGURATION ('filename', 'layer') SET ('section1', 'key1') = 'value1', ('section2', 'key2') = 'value2', ... [WITH RECONFIGURE];
ALTER SYSTEM ALTER CONFIGURATION ('filename', 'layer', 'layer_name' ) UNSET ('section1', 'key1'), ('section2'), ...[WITH RECONFIGURE];
ALTER SYSTEM ALTER SESSION SET
Syntax
ALTER SYSTEM ALTER SESSION <session_id> SET <key> = <value>
Syntax Elements
<session_id> ::= <unsigned_integer>
The session ID of the session where the variable should be set.
<key> ::= <string_literal>
The key of a session variable. The maximum length of key is 32 characters.
<value> ::= <string_literal>
The desired value of a session variable. The maximum length of value is 512 characters.
Description
With this command you can set session variables of database sessions.
Note:There are several read-only session variables that you cannot change with this command:APPLICATION, APPLICATIONUSER, TRACEPROFILE.
Session variables can be retrieved using SESSION_CONTEXT function and unset using the ALTER SYSTEMALTER SESSION UNSET command.
Example
In the example below you set the variable 'MY_VAR' to 'dummy' in session 200006.
ALTER SYSTEM ALTER SESSION 200006 SET 'MY_VAR'= 'dummy';
ALTER SYSTEM ALTER SESSION UNSET
Syntax
ALTER SYSTEM ALTER SESSION <session_id> UNSET <key>
Syntax Elements
<session_id> ::= <unsigned_integer>
The session ID of the session where the variable should be unset.
SAP HANA Database - SQL Reference Manual
116 2012-08-21
<key> ::= <string_literal>
The key of a session variable. The maximum length of key is 32 characters.
Description
With this command you can unset session variables of database sessions.
Note:There are several read-only session variables that you cannot change with this command:APPLICATION, APPLICATIONUSER, TRACEPROFILE.
Session variables can be retrieved using SESSION_CONTEXT function.
Example
Getting the session variables of the current session
SELECT * FROM M_SESSION_CONTEXT WHERE CONNECTION_ID = CURRENT_CONNECTION
Removing a session variable from the specified session
ALTER SYSTEM ALTER SESSION 200001 UNSET 'MY_VAR';
ALTER SYSTEM CANCEL [WORK IN] SESSION
Syntax
ALTER SYSTEM CANCEL [WORK IN] SESSION <session_id>
Syntax Elements
<session_id> ::= <string_literal>
The session ID of the required session.
Description
Cancels the currently executing statement by specifying session ID. The cancelled session will be rolled backafter cancelling, the executing statement will return the error code 139 (current operation cancelled byrequest and transaction rolled back).
Example
You use the following query to obtain the current connection IDs and the statements which they areexecuting.
SELECT C.CONNECTION_ID, PS.STATEMENT_STRING FROM M_CONNECTIONS C JOIN M_PREPARED_STATEMENTS PS ON C.CONNECTION_ID = PS.CONNECTION_ID AND C.CURRENT_STATEMENT_ID = PS.STATEMENT_ID WHERE C.CONNECTION_STATUS = 'RUNNING' AND C.CONNECTION_TYPE = 'Remote'
Using the connection ID information you obtained using the query above, you can now cancel a running queryas shown below.
ALTER SYSTEM CANCEL SESSION '200001'
ALTER SYSTEM CLEAR SQL PLAN CACHE
Syntax
ALTER SYSTEM CLEAR SQL PLAN CACHE
Description
SAP HANA Database - SQL Reference Manual
117 2012-08-21
The SQL PLAN CACHE stores plans generated by previous SQL statement executions. The plan cache is used bythe SAP HANA Database to speed up query exectution if the same SQL statement is executed again.The plancache also collects some statistics regarding plan preparation and execution.
You can find details about the contents of the SQL plan cache from the following monitoring views:M_SQL_PLAN_CACHE, M_SQL_PLAN_CACHE_OVERVIEW
The ALTER SYSTEM CLEAR SQL PLAN CACHE statement removes all the SQL plans that are not currentlyexecuting from the plan cache. The command also removes all plans having reference count of '0' from theplan cache and resets all the statistics of the remaining plans. Lastly the command also reset the contents ofM_SQL_PLAN_CACHE_OVERVIEW monitoring view.
Example
ALTER SYSTEM CLEAR SQL PLAN CACHE
ALTER SYSTEM CLEAR TRACES
Syntax
ALTER SYSTEM CLEAR TRACES (<trace_type_list>)
Syntax Elements
<trace_type_list> ::= <trace_type> [,...]
You can clear multiple traces simultaneously by adding multiple trace_types in a comma delimited list.
<trace_type> ::= <string_literal>
You can selectively clear specific trace files by setting the trace_type to one of the following types:
<trace_type> Trace Files
ALERT *a lert_*.trc
CLIENT loca lcl ient_*.trc
CRASHDUMP *.crashdump.*
EMERGENCYDUMP *.emergencydump.*
* a l l *.trc fi les of services l i s ted below
INDEXSERVER,NAMESERVER,...,DAEMON open *.trc fi les of a s ingle service type
Description
You use the ALTER SYSTEM CLEAR TRACES to clear trace contents from trace files. When you use thiscommand all trace files that were opened by the SAP HANA Database will be removed or cleared. Ondistributed systems, this command will clear all trace files on all hosts.
Use this command to reduce disk space used by large tracefiles, e.g. when trace components are set to INFOor DEBUG.
You can monitor trace files and trace file contents using the M_TRACEFILES, M_TRACEFILE_CONTENTSsystem tables respectively.
Examples
To clear the alert trace file you use the following command:
ALTER SYSTEM CLEAR TRACES('ALERT');
To clear the alert and client trace files you use the following command:
ALTER SYSTEM CLEAR TRACES('ALERT', 'CLIENT');
ALTER SYSTEM DISCONNECT SESSION
Syntax
SAP HANA Database - SQL Reference Manual
118 2012-08-21
ALTER SYSTEM DISCONNECT SESSION <session_id>
Syntax Elements
<session_id> ::= <string_literal>
The session ID of the session to be disconnected.
Description
You use ALTER SYSTEM DISCONNECT SESSION to disconnect a specified session from the database. Beforedisconnection any currently running operations associated with the session will be terminated.
Example
You use the command below to obtain the session IDs of idle sessions.
SELECT CONNECTION_ID, IDLE_TIME FROM M_CONNECTIONS WHERE CONNECTION_STATUS = 'IDLE' AND CONNECTION_TYPE = 'Remote' ORDER BY IDLE_TIME DESC
You use the command below to disconnect a session.
ALTER SYSTEM DISCONNECT SESSION '200001'
ALTER SYSTEM LOGGING
Syntax
ALTER SYSTEM LOGGING <on_off>
Syntax Elements
<on_off> ::= ON | OFF
Description
Logging is enabled or disabled.
While logging is disabled, no log entries are persisted. Only the data area will be writtten, when a savepoint isdone. This can cause loss of committed transactions, when the indexserver terminated in the middle of aload. In case of termination, you have to truncate and insert all data again.
After enable logging you have to perform a savepoint to be sure that all data is persisted and you have toperfrom a data backup, else you can not recover this data.
Only use this command for initial load !
You can also do this for single column tables with ALTER TABLE ... ENABLE/DISABLE DELTA LOG
ALTER SYSTEM RECLAIM DATAVOLUME
Syntax
ALTER SYSTEM RECLAIM DATA VOLUME [SPACE] [<host_port>] <percentage_of_overload_size> <shrink_mode>
Syntax Elements
<host_port> ::= 'host_name:port_number'
Specifies the server on which the size of the persistency should be reduced.
<percentage_of_overload_size> ::= <int_const>
Specifies to which percentage of the overload size the data volume should be reduced.
SAP HANA Database - SQL Reference Manual
119 2012-08-21
<shrink_mode> ::= DEFRAGMENT | SPARSIFY
Specifies the strategy to reduce the persistency size. DEFRAGEMENT is the default. Please note thatSPARSIFY is not supported yet and reserved for future use.
Description
The command should be used when unused space inside the persistencies should be freed. It reduces datavolume size to a N% of overload size; it works like defragmenting a hard disk, pages scattered around thedata volume will be moved to the front of the data volume and the free space at the end of the data volumewill be truncated.
If <host_port> is omitted the statement is distributed to all servers with persistence.
Example
In the example below the persistencies of all servers in the landscape are defragmented and reduced to120% of the overload size.
ALTER SYSTEM RECLAIM DATAVOLUME 120 DEFRAGMENT
ALTER SYSTEM RECLAIM LOG
Syntax
ALTER SYSTEM RECLAIM LOG
Description
You use this command when the database has accumulated a lot of log segments and you want to reclaimdisk space of currently unused log segments.
Log segment accumulation can be caused in several ways. For example, when the automatic log backup isnot operational for a long period or the log savepoint is blocked for an extended time. When such an issueoccurs you use the ALTER SYSTEM RECLAIM LOG command only after the root cause of the log accumulationhas been fixed.
Example
You reclaim disk space of currently unused log segments using the following command:
ALTER SYSTEM RECLAIM LOG
ALTER SYSTEM RECLAIM VERSION SPACE
Syntax
ALTER SYSTEM RECLAIM VERSION SPACE
Description
Performs MVCC version garbage collection for resource reuse.
Example
ALTER SYSTEM RECONFIGURE SERVICE
Syntax
ALTER SYSTEM RECONFIGURE SERVICE (<service_name>,<host>,<port>)
Syntax Element
<service_name> ::= <string_literal>
The name of the service you wish to reconfigure. See M_SERVICE_TYPES monitoring view for a list ofavailable service types.
SAP HANA Database - SQL Reference Manual
120 2012-08-21
<host> ::= <string_literal> <port> ::= <integer>
The host and port number where you would like to reconfigure a service.
Description
You use ALTER SYSTEM RECONFIGURE SERVICE to reconfigures a specified service by applying the currentconfiguration parameters.
This command is used after changing multiple configuration parameters with ALTER CONFIGURATIONwithout RECONFIGURE option. See ALTER SYSTEM ALTER CONFIGURATION
To reconfigure a specific service specify <host> and <port> and leave <service_name> empty.
To reconfigure all services of a type, specify <service_name> and leave <host> and <port> empty.
To reconfigure all services, leave all parameters empty.
Example
You use the following command to reconfigure all services on the ld8520.sap.com host using port number30303:
ALTER SYSTEM RECONFIGURE SERVICE ('','ld8520.sap.com',30303)
You use the following command to reconfigure all services of type indexserver:
ALTER SYSTEM RECONFIGURE SERVICE ('indexserver','',0)
See Also
ALTER SYSTEM ALTER CONFIGURATION
ALTER SYSTEM REMOVE TRACES
Syntax
ALTER SYSTEM REMOVE TRACES (<host>, <trace_file_name_list>) <trace_file_name_list> ::= <trace_file>,...
Syntax Elements
<host> :== <string_literal>
The name of the host where the traces are to be removed.
<trace_file_name_list> ::= <trace_file> [,..]
You can remove multiple traces simultaneously by adding multiple trace_file entries in a comma delimitedlist.
<trace_file> :== see table below.
You set the trace_file parameter to one of the file specifications shown in the table below.
Trace Type <trace_file>
ALERT *a lert_*.trc
CLIENT loca lcl ient_*.trc
CRASHDUMP *.crashdump.*
EMERGENCYDUMP *.emergencydump.*
* a l l *.trc fi les of services l i s ted below
INDEXSERVER,NAMESERVER,...,DAEMON open *.trc fi les of a s ingle service type
Description
SAP HANA Database - SQL Reference Manual
121 2012-08-21
You use this command to Delete the trace files on a specified host to reduce disk space used by large tracefiles. When a service has a trace file open it cannot be deleted. In this case you can clear the trace file usingthe ALTER SYSTEM CLEAR TRACES command.
Example
You use the command below to delete all of the ALERT traces from the lu873.sap.com host.
ALTER SYSTEM REMOVE TRACES ('lu873.sap.com', '*alert_*.trc');
See Also
ALTER SYSTEM CLEAR TRACES
ALTER SYSTEM RESET MONITORING VIEW
Syntax
ALTER SYSTEM RESET MONITORING VIEW <view_name>
Syntax Elements
<view_name> ::= <identifier>
The name of the resettable monitoring view to be reset.
Note:Not all monitoring views can be reset using this command. You can identify a view as being able tobe reset as its view name will have the suffix "_RESET".
Description
You use this command to reset statistics data for the specified monitoring view.
You use this command to define a starting point for your measurements. First, you reset the monitoring view,then execute an action. After the action is completed, query "_RESET" version of the monitor view to get thestatistical information gathered since the last reset.
Example
In the example below you reset the "SYS"."M_HEAP_MEMORY_RESET" monitoring view.
ALTER SYSTEM RESET MONITORING VIEW "SYS"."M_HEAP_MEMORY_RESET"
ALTER SYSTEM SAVE PERFTRACE
Syntax
ALTER SYSTEM SAVE PERFTRACE [INTO FILE <file_name>]
Syntax Elements
<file_name> ::= <string_literal>
The file where raw performance data will be saved.
Description
You use this command to collect raw performance trace data from .prf files and save the information into asingle .tpt file. The .tpt file will be saved in the trace directory of your SAP HANA Database instance. If you donot specify a file name then 'perftrace.tpt' will be used.
The performance trace data (.tpt) file can be downloaded from 'SAP HANA Computing Studio'->Diagnosis-Files and then the performance trace can be loaded and analyzed with HDBAdmin in any SAP HANADatabase instance.
Monitoring View
SAP HANA Database - SQL Reference Manual
122 2012-08-21
The status of the performance trace can be monitored from M_PERFTRACE.
Example
You save raw performance trace data into the 'mytrace.tpt' file using the following command:
ALTER SYSTEM SAVE PERFTRACE INTO FILE 'mytrace.tpt'
ALTER SYSTEM SAVEPOINT
Syntax
ALTER SYSTEM SAVEPOINT
Description
Executes a savepoint on the persistence manager. A savepoint is a point in time when a complete consistentimage of the database is persisted on the disk. The consistent image can be used to restart the database.
Normally, the savepoint is executed periodically, as configured by parameter savepoint_interval_s insection [persistence]. For special (normally test) purposes, the savepoint may be disabled. In this case, youcan use this command to manually execute a savepoint.
ALTER SYSTEM START PERFTRACE
Syntax
ALTER SYSTEM START PERFTRACE [<user_name>] [<application_user_name>] [PLAN_EXECUTION] [FUNCTION_PROFILER] [DURATION <duration_seconds>]
Syntax Element
<user_name> ::= <identifier>
Restrict perftrace collection to the given SQL user name
<application_user_name> ::= <identifier>
Restrict perftrace collection to the given application user name. the applcation user can be defined withsession variable APPLICATIONUSER
PLAN_EXECUTION
Collect plan execution details
FUNCTION_PROFILER
Collect function level details.
<duration_seconds> ::= <numeric literal>
After duration seconds the perftrace is automatically stopped. If not specified, perftrace will only stop withALTER SYSTEM STOP PERFTRACE.
Description
Start Performance Trace.
With 'Explain Plan' or 'Visualize Plan' you can see statement execution on a logical level. With 'PerfomanceTrace' the statement execution will be recorded on thread + function level.
Only one perftrace can be active at one time.
The status of performance trace can be monitored from M_PERFTRACE.
Example
ALTER SYSTEM START PERFTRACE sql_user app_user PLAN_EXECUTION FUNCTION_PROFILER
SAP HANA Database - SQL Reference Manual
123 2012-08-21
ALTER SYSTEM STOP PERFTRACE
Syntax
ALTER SYSTEM STOP PERFTRACE
Description
Stop a previously started Performance Trace. After stop, the performance trace data has to be collected andsaved with ALTER SYSTEM SAVE PERFTRACE.
Example
ALTER SYSTEM STOP PERFTRACE
ALTER SYSTEM STOP SERVICE
Syntax
ALTER SYSTEM STOP SERVICE <host_port> [IMMEDIATE [WITH COREFILE]]
Syntax Element
<host_port> ::= <host_name:port_number> | ('<host_name>',<port_number>)
Location of service to be stopped.
IMMEDIATE
Immmediately stop (kill) service without waiting for regular shutdown.
WITH COREFILE
Write a core file
Description
Stop or kill a single or multiple services. The service will typically be restarted by the daemon.
Required after changing a configuration parameter that can not be changed online.
Example
ALTER SYSTEM STOP SERVICE 'ld8520:30303'
UNSET SYSTEM LICENSE ALL
Syntax
UNSET SYSTEM LICENSE ALL
Description
Deletes all currently installed license keys. After using this command the system will be locked downimmediately and will require a new valid license key before it can be used further. The system privilegeLICENSE ADMIN is required to execute this command.
Example
UNSET SYSTEM LICENSE ALL
Session Management Statements
CONNECT
SAP HANA Database - SQL Reference Manual
124 2012-08-21
Syntax
CONNECT <connect_option>
Syntax Elements
<connect_option> ::= <user_name> PASSWORD <password> | WITH SAML ASSERTION '<xml>' <password> ::= <letter_or_digit>...
Description
Connect to the database instance by specifying user_name and password or by specifying a SAML assertion.
Example
CONNECT my_user PASSWORD myUserPass1
SET HISTORY SESSION
Syntax
SET HISTORY SESSION TO <when>
Elements
<when>:
User should specify an exact moment when the session is to travel
<when> ::= NOW | COMMIT ID <commit_id> | UTCTIMESTAMP <utc_timestamp> <commit_id> ::= <unsigned_integer> <utc_timestamp> ::= <string_literal>
Description
SET HISTORY SESSSION makes current session to see a previous version of history tables. User may specify theversion in COMMIT ID or UTCTIMESTAMP format, or may get back to current version by specify NOW. AfterSET HISTORY SESSION command with a COMMIT ID or UTCTIMESTAMP is issued, current session sees an oldversion of history tables, and cannot write anything to the system. If NOW option is given, current sessiongets back to a normal session, and sees current version of history tables and be able to write to the system.This command only works for history tables, and visibility on normal tables is not affected.
Example
SELECT CURRENT_UTCTIMESTAMP FROM SYS.DUMMYSELECT LAST_COMMIT_ID FROM M_HISTORY_INDEX_LAST_COMMIT_ID WHERE SESSION_ID =CURRENT_CONNECTION COMMITSET HISTORY SESSION TO UTCTIMESTAMP '2012-03-09 07:01:41.428'SET HISTORY SESSION TO NOW
SET SCHEMA
Syntax
SET SCHEMA <schema_name>
Syntax Elements
Schema_name schema name string
Description
You can change the current schema of the session. The current schema is used when database object names
SAP HANA Database - SQL Reference Manual
125 2012-08-21
such as table names are not prefixed with the schema name.
SET [SESSION]
Syntax
SET [SESSION] <key> = <value>
Syntax Elements
<key> ::= <string_literal>
The key of a session variable. The maximum length of key is 32 characters.
<value> ::= <string_literal>
The desired value of a session variable. The maximum length of value is 512 characters.
Description
With this command you can set session variables of your own database session by providing key and valuepairs.
Note:There are several available read-only session variables that you cannot change with this command:APPLICATION, APPLICATIONUSER, TRACEPROFILE.
Session variables can be retrieved using SESSION_CONTEXT function and unset using the UNSET [SESSION]command.
Example
SET 'MY_VAR' = 'dummy';
SELECT SESSION_CONTEXT('MY_VAR') FROM dummy;
UNSET 'MY_VAR';
UNSET [SESSION]
Syntax
UNSET [SESSION] <key>
Syntax Elements
<key> ::= <string_literal>
The key of a session variable. The maximum length of key is 32 characters.
Description
Using UNSET [SESSION] you can unset session variables of the current session.
Note:There are several read-only session variables and they are APPLICATION, APPLICATIONUSER,TRACEPROFILE.
Example
SET 'MY_VAR'= 'dummy';
SELECT SESSION_CONTEXT('MY_VAR') FROM dummy;
UNSET 'MY_VAR';
Transaction Management Statements
SAP HANA Database - SQL Reference Manual
126 2012-08-21
COMMIT
Syntax
COMMIT
Description
The system supports transactional consistency which guarantees current job to be either completely appliedto the system or disposed. If a user wants to apply current job to the system persistently, the user shouldissue COMMIT command. If COMMIT command is issued and successfully processed, any change on thesystem which current transaction has done is applied to the system and the change will be visible to otherjobs which will start in the future. The job which has already committed via COMMIT command cannot bereverted. In a distributed system, standard 2-phase-commit protocol is complied. In the first phase,transaction coordinator consults every participant whether if it is ready to commit, and sends the result tothe participants in the second phase. COMMIT command only works with 'autocommit' disabled session.
Example
COMMIT
LOCK TABLE
Syntax
LOCK TABLE <table_name> IN EXCLUSIVE MODE [NOWAIT]
Description
LOCK TABLE command explicitly tries to acquire an exclusive lock for a table. If NOWAIT option is specified, itjust tries to acquire lock for the table. If it fails to acquire lock with NOWAIT option specified, an error code isreturned, but current transaction is not rolled-back.
Example
LOCK TABLE mytaable IN EXCLUSIVE MODE NOWAIT
ROLLBACK
Syntax
ROLLBACK
Description
The system supports transactional consistency which guarantees current job to be either completely appliedto the system or disposed. In the middle of a transaction, it can be explicitly reverted as it has not beenperformed via ROLLBACK command. After ROLLBACK command is issued, any change on the system whichcurrent transaction has done is completely reverted and current session is to be in an idle state. ROLLBACKcommand only works with 'autocommit' disabled session.
Example
ROLLBACK
SET TRANSACTION
Syntax
SET TRANSACTION <isolation_level> | <transaction_access_mode>
Syntax Elements
isolation_level ::= ISOLATION LEVEL <level>
SAP HANA Database - SQL Reference Manual
127 2012-08-21
The isolation level sets the statement level read consistency of the data in the database. If isolation_level isommited the default is READ COMMITTED
level ::= READ COMMITTED | REPEATABLE READ | SERIALIZABLE
READ COMMITTED The READ COMMITTED isolation level provides statement level read consistency during a transaction. Eachstatement in a transaction sees commited state of the data in the database as the execution of thestatement begins. This means that each statement in the same transaction may see varying snapshots of thedata in the database as they are executed as data can be commited during the transaction.
REPEATABLE READ/SERIALIZABLE The REPEATABLE READ/SERIALIZABLE isolation level provides transaction level snapshot isolation. Allstatements of a transaction see the same snapshot of the database data. This snapshot contains all changesthat were committed at the time the transaction started along with the changes made by the transactionitself.
transaction_access_mode ::= READ ONLY | READ WRITE
The SQL-transaction access mode controls if a transaction can modify data during execution. Iftransaction_access_mode is ommited the default is READ ONLY.
READ ONLY When READ ONLY access mode is set, then only read operations with SELECT statements are allowed. Anexception will be thrown if update or insert operations are attempted whilst in this mode.
READ WRITE When READ WRITE access mode is set, statements within a transaction can freely read or make changes tothe database data as required.
Description
The SAP HANA Database uses multi-version concurrency control (MVCC) to ensure consistent readoperations. Concurrent read operations see a consistent view of the database data without blockingconcurrent write operations. Updates are implemented by inserting new versions of data and not byoverwriting existing records.
The isolation level specified determines the lock operation type that will be used. The system supports bothstatement level snapshot isolation and transaction level snapshot isolation.
For statement snapshot isolation use level READ COMMITTED.For transaction snapshot isolation use REPEATABLE READ or SERIALIZABLE.
During a transaction when rows are inserted, updated or deleted, the system sets exclusive locks on theaffected rows for the duration of the transaction. The system also sets shared locks on the affected tables forthe duration of the transaction. This guarantees that the table is not dropped or altered while rows of thetable are being updated. The database releases these locks at the end of the transaction.
Note:Reading a row does not set any locks on either tables or rows within the database regardless of theisolation level used.
Data Definition Language and Transaction Isolation
Data Definition Language (DDL) statements (CREATE TABLE, DROP TABLE, CREATE VIEW, etc) always takean instantaneous effect on following SQL statements regardless of the transaction isolation level being used.For an example of this behaviour please consider the following sequence:
1. A long running SERIALIZABLE isolation transaction begins operating on Table C.2. From outside the transaction some DDL is executed which adds a new column to Table C.3. From within the SERIALIZABLE isolation transaction the new column will be accessible as soon as the
DDL statement completes. This access occurs regardless of the isolation level of the transaction.
Example
SET TRANSACTION READ COMMITTED;
Access Control Statements
ALTER SAML PROVIDER
SAP HANA Database - SQL Reference Manual
128 2012-08-21
ALTER SAML PROVIDER <saml_provider_name> WITH SUBJECT <subject_name> ISSUER <issuer_distinguished_name>
Syntax Elements
<saml_provider_name> ::= <simple_identifier>
<subject_name> ::= <string_literal> <issuer_distinguished_name> ::= <string_literal>
Description
The ALTER SAML PROVIDER statement changes the property of a SAML provider known to the SAP HANAdatabase. <saml_provider_name> has to be an existing SAML provider. Only database users having the system privilege USER ADMIN are allowed to change a SAML provider.
The <subject_name> and the <issuer_distinguished_name> are the corresponding names provided in thecertificate of the SAML identity provider.
System and Monitoring Views
SAML_PROVIDERS: shows all SAML providers with their subject name and issuer_name.
Syntax
ALTER USER
Syntax
ALTER USER <user_name> <alter_user_option>
Syntax Elements
<user_name> ::= <identifier>
<alter_user_option> ::= PASSWORD <password> [<user_parameter_option>] | <user_parameter_option> | IDENTIFIED EXTERNALLY AS <external_identity> [<user_parameter_option>] | RESET CONNECT ATTEMPTS | DROP CONNECT ATTEMPTS | DISABLE PASSWORD LIFETIME | FORCE PASSWORD CHANGE | DEACTIVATE [USER NOW] | ACTIVATE [USER NOW] | DISABLE <authentication_mechanism> | ENABLE <authentication_mechanism> | ADD IDENTITY <provider_identity>... | ADD IDENTITY <external_identity> FOR KERBEROS | DROP IDENTITY <provider_info>... | DROP IDENTITY FOR KERBEROS
<password> ::= <letter_or_digit>...
<user_parameter_option> ::= <set_user_parameters> [<clear_user_parameter_option>] | <clear_user_parameter_option>
<set_user_parameters> ::= SET PARAMETER CLIENT = <string_literal>
<clear_user_parameter_option> ::= CLEAR PARAMETER CLIENT | CLEAR ALL PARAMETERS
<external_identity> ::= <simple_identifier>
SAP HANA Database - SQL Reference Manual
129 2012-08-21
| <string_literal>
<authentication_mechanism> ::= PASSWORD | KERBEROS | SAML
<provider_identity> ::= <mapped_user_name> FOR SAML PROVIDER <saml_provider_name> | <external_identity> FOR KERBEROS <mapped_user_name> ::= ANY | <string_literal> <saml_provider_name> ::= <simple_identifier>
<provider_info> ::= FOR SAML PROVIDER <saml_provider_name>
Description
The ALTER USER statement modifies the database user. <user_name> must specify an existing databaseuser. Each user can do the ALTER USER statement for his own. But not all of the <alter_user_option>s can bespecified by the user himself. The ALTER USER statement for other users with all <alter_user_option>s canonly be done by users having the system privilege USER ADMIN.
Users created with PASSWORD cannot be changed to EXTERNALLY and vice versa: the users created withEXTERNALLY cannot be changed to PASSWORD. But their <password> or their <external_identity> can bechanged.
You can change a user's password with this command. Password must follow the rules defined for the currentdatabase. The password rules include the minimal password length and the definition which of the charactertypes ( lower, upper, digit, special characters ) have to be part of the password. The password for a user hasto be changed regularly according to the password policy specified for the database instance or changed bythe user himself when first connecting to the database instance.
You can change the external authentication. External users are authenticated using an external system, e.g.a Kerberos system. Such users do not have a password, but , e.g. a Kerberos principal name. For detailedinformation about external identities, contact your domain administrator.
<user_parameter_option> can be used to set, change or clean the user parameter CLIENT.<set_user_parameters> can be used to set the user parameter CLIENT for a user in the database.When using reports this user parameter CLIENT can be used to restrict the access rights of user <user_name>to info concerning the specified client. The <user_parameter_option> can not be specified by the user himself.
If the number of MAXIMUM_INVALID_CONNECT_ATTEMPTS (see monitoring view M_PASSWORD_POLICY) isreached before a successful (correct user/password-combination) connect is done, then this user is locked forsome minutes before being allowed to connect (even with correct user/password-combination) again. Withthe command ALTER USER <user_name> RESET CONNECT ATTEMPTS a user with system privilege USER ADMIN can reset the number of invalid attempts to 0 and therefore allowthe user to connect immediately.
Information on invalid connect attempts having happened can be checked in system viewINVALID_CONNECT_ATTEMPTS. With the commandALTER USER <user_name> DROP CONNECT ATTEMPTS a user with system privilege USER ADMIN or the user himself can delete the information of invalid connectattempts having happened.
With the commandALTER USER <user_name> DISABLE PASSWORD LIFETIME a user with system privilege USER ADMIN can exclude user <user_name> from all password-life-time-checks.This should be used only for technical users, not for normal database users. Please check the description ofconfiguration parameters concerning the password policy.
With the commandALTER USER <user_name> FORCE PASSWORD CHANGE a user with system privilege USER ADMIN can force user <user_name> to change his password immediatelyafter the next connect before being allowed to work any further.
With the commandALTER USER <user_name> DEACTIVATE USER NOW
SAP HANA Database - SQL Reference Manual
130 2012-08-21
a user with system privilege USER ADMIN can deactivate / lock the user account of user <user_name>. Afterthe user account is deactivated / locked, the user cannot connect to the SAP HANA database. To re-activate /unlock user <user_name> a user with system privilege USER ADMIN has either to use the command ALTERUSER <user_name> ACTIVATE USER NOW or, in case of a user with PASSWORD authentication mechanism,to reset the user's password with ALTER USER <user_name> PASSWORD <password>. With the commandALTER USER <user_name> ACTIVATE USER NOW a user with system privilege USER ADMIN can re-activate / unlock the user account of user <user_name>who had been deactivated before.
Configuration Parameter
Conguration parameters concerning the password can be checked with the monitoring viewM_PASSWORD_POLICY. These parameter are stored in indexserver.ini, section 'password policy'. The description of the parameters concerned can be found in SAP HANA Security Guide, Appendix, PasswordPolicy Parameters.
System and Monitoring Views
USERS: shows all users, their creator, creation date and some info about their current states. USER_PARAMETERS: shows the defined user_parameters; currently only CLIENT is available. INVALID_CONNECT_ATTEMPTS: shows how many invalid connect attempts were made for each user. LAST_USED_PASSWORDS: shows info about dates of last password-changes per user. M_PASSWORD_POLICY: shows configuration parameters describing the allowed layout of the password andits lifetimes.
Example
A user with user_name NEW_USER had been created before with the possibility to connect using the givenpassword and with an assertion of the existing SAML provider OUR_PROVIDER. The <mapped_user_name>was set to ANY as the assertion will provide the database user name. This was done with the followingstatement:
CREATE USER new_user PASSWORD Password1 WITH IDENTITY ANY FOR SAML PROVIDER OUR_PROVIDER;
Now this user shall be forced to change his password. And to force him really hard, his possibility to connectusing SAML is disabled.
ALTER USER new_user FORCE PASSWORD CHANGE; ALTER USER new_user DISABLE SAML;
Assuming the user has tried to connect with a wrong password too often, the administrator now wants toreset the number of invalid connect attempts to zero.
ALTER USER new_user RESET CONNECT ATTEMPTS;
The user new_user shall be allowed to use KERBEROS - mechanism to authenticate. Therefore the externalidentity for this connect mechanism has to be defined. Additionally the user has to be allowed to connectusing KERBEROS as this is not done internally when the external identity is defined.
ALTER USER new_user ADD IDENTITY 'testkerberosName' FOR KERBEROS; ALTER USER new_user ENABLE KERBEROS;
On the other hand the user new_user will loose the possibility to use an assertion of SAML providerOUR_PROVIDER.
ALTER USER new_user DROP IDENTITY FOR SAML PROVIDER OUR_PROVIDER;
In the end the administrator wants to disallow any connection for this user new_user, for example because ofsuspicious work he did recently.
ALTER USER new_user DEACTIVATE;
CREATE ROLE
Syntax
SAP HANA Database - SQL Reference Manual
131 2012-08-21
CREATE ROLE <role_name>
Syntax Elements
<role_name> ::= <identifier>
Description
The CREATE ROLE statement creates a new role. Only database users having the system privilege ROLE ADMIN are allowed to create a role. The specified role name must not be identical to the name of an existing user or role.
A role is a named collection of privileges and can be granted to either a user or a role. If you want to allowseveral database users to perform the same actions, you can create a role, grant the needed privileges tothis role, and grant the role to the different database users. Every user is allowed to grant privileges to an existing role, but only users having system privilege ROLEADMIN are allowed to grant roles to roles and users.
There are 4 roles, which are delivered with the SAP HANA database:
PUBLIC Every database user has been granted this role implicitly. This role contains read-only access to system views, monitoring views and execute privilege for someprocedures. These privileges can not be revoked. This role can be granted further privileges which can be revoked afterwards.
MODELING This role contains all privileges required for using the information modeler in the SAP HANA studio.
CONTENT_ADMIN This role contains the same privileges as the MODELING role, but with the extension that this role is allowedto grant these privileges to other users. In addition, it contains the repository privileges to work withimported objects.
MONITORING This role contains privileges for full read-only access to all meta data, the current system status in system andmonitoring views, and the data of the statistics server.
System and Monitoring Views
ROLES: shows all roles, their creator and creation date. GRANTED_ROLES: shows which roles are granted to which user or role. GRANTED_PRIVILEGES: shows which privileges are granted to which user or role.
Example
A role with the name role_for_work_on_my_schema is created.
CREATE ROLE role_for_work_on_my_schema;
CREATE SAML PROVIDER
Syntax
CREATE SAML PROVIDER <saml_provider_name> WITH SUBJECT <subject_distinguished_name> ISSUER <issuer_distinguished_name>
Syntax Elements
<saml_provider_name> ::= <simple_identifier>
<subject_distinguished_name> ::= <string_literal> <issuer_distinguished_name> ::= <string_literal>
SAP HANA Database - SQL Reference Manual
132 2012-08-21
Description
The CREATE SAML PROVIDER statement defines a SAML provider known to the SAP HANA database.<saml_provider_name> has to be different to any existing SAML provider. Only database users having the system privilege USER ADMIN are allowed to create a SAML provider. Eachuser having this privilege is allowed to drop any SAML provider.
An existing SAML provider is needed to be able to specify SAML connection possibility for users. The <subject_distinguished_name> and the <issuer_distinguished_name> are the X.500 distinguished namescorresponding to the subject and issuer of the X.509 certificate used by the SAML identity provider to signassertions. The syntax of these names can be found in ISO/IEC 9594-1. A detailed description of the concepts of SAML can be found in Oasis SAML 2.0.
System and Monitoring Views
SAML_PROVIDERS: shows all SAML providers with their subject name and issuer name.
Example
A SAML provider with the name gm_saml_provider is created in the database specifying the subject andissuer to belong to some company.
CREATE SAML PROVIDER gm_saml_provider WITH SUBJECT 'CN = wiki.detroit.generalmotors.corp,OU = GMNet,O = GeneralMotors,C = EN' ISSUER 'E = [email protected],CN = GMNetCA,OU = GMNet,O = GeneralMotors,C = EN';
CREATE USER
Syntax
CREATE USER <user_name> [PASSWORD <password>] [IDENTIFIED EXTERNALLY AS <external_identity>] [WITH IDENTITY <provider_identity>...] [<set_user_parameters>]
Syntax Elements
<user_name> ::= <identifier>
<password> ::= <letter_or_digit>...
<external_identity> ::= <simple_identifier> | <string_literal>
<provider_identity> ::= <mapped_user_name> FOR SAML PROVIDER <saml_provider_name> | <external_identity> FOR KERBEROS
<mapped_user_name> ::= ANY | <string_literal>
<saml_provider_name> ::= <simple_identifier>
<set_user_parameters> ::= SET PARAMETER CLIENT = <string_literal>
Description
The CREATE USER statement creates a new database user. Only database users having the system privilege USER ADMIN are allowed to create another database user. The specified user name must not be identical to the name of an existing user, role, or schema. There are some users, which are delivered with the SAP HANA database: SYS, SYSTEM, _SYS_REPO,_SYS_STATISTICS.
SAP HANA Database - SQL Reference Manual
133 2012-08-21
Users in the database can be authenticated by different mechanism, the internal authentication mechanismusing password and by external mechanism, like Kerberos or SAML. One user can be authenticated by morethan one mechanism at one time, but only one password and one external_identity can be valid at one time.In opposite to this, more than one <provider_identity> can exist for one user at one time. At least oneauthentication mechanism has to be specified to allow the user to connect and work with the databaseinstance.For compatibility reasons the syntax IDENTIFIED EXTERNALLY AS <external_identity> will stay alive and dothe same as the syntax <external_identity> FOR KERBEROS.
Password must follow the rules defined for the current database. The password rules include the minimalpassword length and the definition which of the character types ( lower, upper, digit, special characters )have to be part of the password. The password for a user has to be changed regularly according to thepassword policy specified for the database instance.The password provided during CREATE USER command will be taken as provided, whereas the <user_name>will be changed to upper_case as every <simple_identifier>.
External users are authenticated using an external system, e.g. a Kerberos system. Such users do not have apassword, but , e.g. a Kerberos principal name. For detailed information about external identities, contactyour domain administrator.
If ANY is given as mapped user name, the SAML assertion will contain the name of the database user, theassertion is valid for. <saml_provider_name> must specify an existing SAML provider.
<set_user_parameters> can be used to set the user parameter CLIENT when a user is created in thedatabase. When using reports this user parameter CLIENT can be used to restrict the access rights of user<user_name> to info concerning the specified client.
For each database user a schema with the user's name is created implicitly. This can not be droppedexplicitly. It will be dropped when the user is dropped. The database user owns that schema and uses it as hisdefault schema, when he does not specify a schema name explicitly.
Configuration Parameter
Conguration parameters concerning the password can be checked with the monitoring viewM_PASSWORD_POLICY. These parameter are stored in indexserver.ini, section 'password policy'. The description of the parameters concerned can be found in SAP HANA Security Guide, Appendix, PasswordPolicy Parameters.
System and Monitoring Views
USERS: shows all users, their creator, creation date and some info about their current states. USER_PARAMETERS: shows the defined user_parameters; currently only CLIENT is available. INVALID_CONNECT_ATTEMPTS: shows how many invalid connect attempts were made for each user. LAST_USED_PASSWORDS: shows info about dates of last password-changes per user. M_PASSWORD_POLICY: shows configuration parameters describing the allowed layout of the password andits lifetimes. SAML_PROVIDERS: shows the existing SAML provider SAML_USER_MAPPING: shows the user's mappingnames for each SAML provider
Example
A user with user_name NEW_USER shall be created with the possibility to connect using the given passwordand with an assertion of the existing SAML provider OUR_PROVIDER. The <mapped_user_name> is set toANY as the assertion will provide the database user name.
CREATE USER new_user PASSWORD Password1 WITH IDENTITY ANY FOR SAML PROVIDER OUR_PROVIDER;
DROP ROLE
Syntax
DROP ROLE <role_name>
Syntax Elements
<role_name> ::= <identifier>
SAP HANA Database - SQL Reference Manual
134 2012-08-21
Description
The DROP ROLE statement drops a role. <drop_name> must specify an existing role. Only database users having the system privilege ROLE ADMIN are allowed to drop a role. Each user havingthis privilege is allowed to drop any role. Only those roles which are delivered with the SAP HANA databasecan not be dropped: PUBLIC, CONTENT_ADMIN, MODELING and MONITORING.
If a role was granted to a user or role, it is revoked when the role is dropped. Revoking a role may lead tomaking some views inaccessible or making procedures not executable any more. This will occur if a view orprocedures depends on any privilege that the role had.
System and Monitoring Views
ROLES: shows all roles, their creator and creation date. GRANTED_ROLES: shows which roles are granted to which user or role. GRANTED_PRIVILEGES: shows which privileges are granted to which user or role.
Example
A role with the name role_for_work_on_my_schema is created and dropped directly afterwards;
CREATE ROLE role_for_work_on_my_schema;
DROP ROLE role_for_work_on_my_schema;
DROP SAML PROVIDER
DROP SAML PROVIDER <saml_provider_name>
Syntax Elements
<saml_provider_name> ::= <simple_identifier>
Description
The DROP SAML PROVIDER statement drops the specified SAML provider. <saml_provider_name> has to bean existing SAML provider. If the SAML provider specified is used by a SAP HANA database user, the SAMLprovider cannot be dropped. Only database users having the system privilege USER ADMIN are allowed to drop a SAML provider.
System and Monitoring Views
SAML_PROVIDERS: shows all SAML providers with their subject name and issuer_name.
Syntax
DROP USER
Syntax
DROP USER <user_name> [<drop_option>]
Syntax Elements
<user_name> ::= <identifier>
<drop_option> ::= CASCADE | RESTRICT
Default = RESTRICT
Description
The DROP USER statement deletes a database user. <user_name> must specify an existing database user.
SAP HANA Database - SQL Reference Manual
135 2012-08-21
Only database users having the system privilege USER ADMIN are allowed to drop a database user. Each userhaving this privilege is allowed to drop any user. Only those users which are delivered with the SAP HANAdatabase can not be dropped: SYS, SYSTEM, _SYS_REPO, _SYS_STATISTICS.
If the <drop_option> RESTRICT is specified implicitly or explicitly then the user will not be dropped in case heis the owner of any other object than the schema with his name and other schemas created by him or in casethere is an object stored in one of his schemas which was not created by him. If the <drop_option> CASCADE is specified, the schema with the user's name and the schemas belonging tothe user, together with all objects stored in them (even if they are created by other users), are deleted.Objects owned by the user, even if they are part of another schema, are deleted. Objects that are dependenton deleted objects are deleted. Even public synonyms owned by the deleted user are deleted.Privileges on deleted objects are revoked. Privileges granted by the deleted user are revoked. Revokeprivileges may cause further revokes if they had been granted further.
Users created by the deleted user and roles created by him are not deleted. Audit policies created by the deleted user are not deleted.
It is possible to delete a user even if an open session of this user exists.
System and Monitoring Views
The deleted user will be deleted in any of these views:USERS: shows all users, their creator, creation date and some info about their current states. USER_PARAMETERS: shows the defined user_parameters; currently only CLIENT is available. INVALID_CONNECT_ATTEMPTS: shows how many invalid connect attempts were made for each user. LAST_USED_PASSWORDS: shows info about dates of last password-changes per user.
* The deletion of objects may influence all of the system views describing objects, like TABLES, VIEWS,PROCEDURES, ... .The deletion of objects may influence the view describing privileges like GRANTED_PRIVILEGES and all of themonitoring views like M_RS_TABLES, M_TABLE_LOCATIONS, ...
Example
A user with user_name NEW_USER was created before with, for example, this statemant:
CREATE USER new_user PASSWORD Password1;
The existing user new_user will now be dropped, together with all of his objects;
DROP USER new_user CASCADE;
GRANT
Syntax
GRANT <system_privilege>,... TO <grantee> [WITH ADMIN OPTION] | GRANT <schema_privilege>,... ON SCHEMA <schema_name> TO <grantee> [WITH GRANT OPTION] | GRANT <object_privilege>,... ON <object_name> TO <grantee> [WITH GRANT OPTION] | GRANT <role_name>,... TO <grantee> [WITH ADMIN OPTION] | GRANT STRUCTURED PRIVILEGE <privilege_name> TO <grantee>
Syntax Elements
<system_privilege> ::= AUDIT ADMIN | BACKUP ADMIN | CATALOG READ | CREATE SCENARIO | CREATE SCHEMA | CREATE STRUCTURED PRIVILEGE | DATA ADMIN | EXPORT | IMPORT | INIFILE ADMIN | LICENSE ADMIN | LOG ADMIN | MONITOR ADMIN | OPTIMIZER ADMIN | RESOURCE ADMIN | ROLE ADMIN | SAVEPOINT ADMIN | SCENARIO ADMIN | SERVICE ADMIN | SESSION ADMIN | STRUCTUREDPRIVILEGE ADMIN | TRACE ADMIN | USER ADMIN | VERSION ADMIN | <identifier>.<identifier>
System privileges are used to restrict administrative tasks. The following system privileges are defined:
SAP HANA Database - SQL Reference Manual
136 2012-08-21
AUDIT ADMIN This privilege controls the execution of the following auditing-related commands: CREATE AUDIT POLICY,DROP AUDIT POLICY and ALTER AUDIT POLICY.
BACKUP ADMIN This privilege authorizes the ALTER SYSTEM BACKUP command to define and initiate a backup process or toperform a recovery process.
CATALOG READ This privilege authorizes all users to have unfiltered read-only access to all system and monitoring views.Normally, the content of those views is filtered based on the privileges of the accessing user. The CATALOGREAD privilege enables users to have read-only access to the full content of all system and monitoring views.
CREATE SCENARIO This privilege controls the creation of calculation scenarios and cubes (calculation database).
CREATE SCHEMA This privilege authorizes the creation of database schemas using the CREATE SCHEMA command. Each userowns one schema. With this privilege he is allowed to create further ones.
CREATE STRUCTURED PRIVILEGE This privilege authorizes the creation of Structured Privileges (Analytical Privileges). Note that only the ownerof an Analytical Privilege can further grant it to other users or roles and revoke it again.
DATA ADMIN This powerful privilege authorizes to read all data in the system and monitoring views as well as execute allDDL (Data Definition Language) � and only DDL � commands in the SAP HANA database. This means, thata user having this privilege can not select or change data stored in other user's tables, but can modify thetable definition or even drop the table.
EXPORT This privilege authorizes the export activity in the database via the EXPORT TABLE commands. Note that,beside this privilege, the user still needs the SELECT privilege on the source tables to be exported.
IMPORT This privilege authorizes the import activity in the database using the IMPORT commands. Note that, besidethis privilege, the user still needs the INSERT privilege on the target tables to be imported.
INIFILE ADMIN This privilege authorizes different methods to change system settings.
LICENSE ADMIN This privilege authorizes the SET SYSTEM LICENSE command install a new license.
LOG ADMIN This privilege authorizes the ALTER SYSTEM LOGGING [ON|OFF] commands to enable or disable the log flushmechanism.
MONITOR ADMIN This privilege authorizes the ALTER SYSTEM commands concerning EVENTs.
OPTIMIZER ADMIN This privilege authorizes the ALTER SYSTEM commands concerning SQL PLAN CACHE and ALTER SYSTEMUPDATE STATISTICS commands, which influence the behavior of the query optimizer.
RESOURCE ADMIN This privilege authorizes different commands concerning resources, like ALTER SYSTEM RECLAIMDATAVOLUME and ALTER SYSTEM RESET MONITORING VIEW and it authorizes many of the commands inthe Management Console.
ROLE ADMIN This privilege authorizes the creation and deletion of roles using the CREATE ROLE and DROP ROLEcommands. It also authorizes the granting and revocation of roles using the GRANT and REVOKE commands.
SAVEPOINT ADMIN This privilege authorizes the execution of a savepoint process using the ALTER SYSTEM SAVEPOINTcommand.
SCENARIO ADMIN
SAP HANA Database - SQL Reference Manual
137 2012-08-21
This privilege authorizes all calculation scenario-related activities (including creation).
SERVICE ADMIN This privilege authorizes the ALTER SYSTEM [START|CANCEL|RECONFIGURE] commands, intended foradministering system services of the database.
SESSION ADMIN This privilege authorizes the ALTER SYSTEM commands concerning sessions to stop or disconnect a usersession or to change session variables.
STRUCTUREDPRIVILEGE ADMIN This privilege authorizes the creation, reactivation, and dropping of structured privileges.
TRACE ADMIN This privilege authorizes the ALTER SYSTEM [CLEAR|REMOVE] TRACES commands for operations on databasetrace files.
USER ADMIN This privilege authorizes the creation and changing of users using the CREATE USER, ALTER USER, and DROPUSER commands.
VERSION ADMIN This privilege authorizes the ALTER SYSTEM RECLAIM VERSION SPACE command of the multi-versionconcurrency control (MVCC) mechanism.
<identifier>.<identifier> Components of the SAP HANA database may create privileges for their own needs. Those use the component-name as first identifier of the system privilege and the component-privilege-name as the second identifier.Currently, the repository uses this feature. For description of the privileges named REPO.<identifier>, pleasesee the manual of the repository.
<schema_privilege> ::= CREATE ANY | DEBUG | DELETE | DROP | EXECUTE | INDEX | INSERT | SELECT | TRIGGER | UPDATE
Schema privileges are used to restrict the access and modifications on a schema and the objects stored inthis schema. The following schema privileges are defined:
CREATE ANY This privilege allows the creation of all kinds of objects, in particular, tables, views, sequences, synonyms, SQLScript functions, or database procedures in a schema.
DELETE, DROP, EXECUTE, INDEX, INSERT, SELECT, UPDATE The specified privilege is granted on every object stored in the specified schema currently and in future. Fordetailed description of the privileges please see the part describing object privileges below and please checkbelow, which privileges are applicable for which kind of object.
<object_privilege> ::= ALL PRIVILEGES | ALTER | DEBUG | DELETE | DROP | EXECUTE | INDEX | INSERT | SELECT | TRIGGER | UPDATE | <identifier>.<identifier>
SAP HANA Database - SQL Reference Manual
138 2012-08-21
Object privileges are used to restrict the access and modifications on database objects like tables, views,sequences, procedures and the like. Not all of these privileges are applicable to all kinds of database objects.For object types allowing which privilege, see table below. The following object privileges are defined:
ALL PRIVILEGES This privilege is a collection of all DDL (Data Definition Language) and DML (Data Manipulation Language)privileges that on the one hand, the grantor currently has and is allowed to grant further and on the otherhand, can be granted on this particular object. This collection is dynamically evaluated for the given grantorand object. ALL PRIVILEGES is applicable to a table or view.
ALTER This DDL privilege authorizes the ALTER command for that object.
DEBUG This DML privilege authorizes the debug-functionality for that procedure or calculation view or for theprocedures or calculation views in that schema.
DELETE This DML privilege authorizes the DELETE and TRUNCATE commands for that object.
DROP This DDL privilege authorizes the DROP commands for that object.
EXECUTE This DML privilege authorizes the execution of a SQL Script function or a database procedure using the CALLSor CALL command, respectively.
INDEX This DDL privilege authorizes the creation, changing, or dropping of indexes for that object.
INSERT This DML privilege authorizes the INSERT command for that object. The INSERT and the UPDATE privilegetogether are needed for one object to allow the REPLACE and UPSERT command for that object.
SELECT This DML privilege authorizes the SELECT command for that object or the usage of the sequence,respectively.
TRIGGER This DDL privilege authorizes the CREATE TRIGGER / DROP TRIGGER command for the specified table or thetables in the specified schema.
UPDATE This DML privilege authorizes the UPDATE command for that object. The INSERT and the UPDATE privilegetogether are needed for one object to allow the REPLACE and UPSERT command for that object.
<identifier>.<identifier> Components of the SAP HANA database may create privileges for their own needs. Those use the component-name as first identifier of the privilege name and the component-privilege-name as the second identifier.Currently, the repository uses this feature. For description of the privileges named REPO.<identifier>, pleasesee the manual of the repository.
SAP HANA Database - SQL Reference Manual
139 2012-08-21
Privilege Schema Table View Sequence Function/Procedure
ALL PRIVILEGES --- YES YES --- ---
ALTER YES YES --- --- YES
CREATE ANY YES --- --- --- ---
DEBUG YES --- YES --- YES
DELETE YES YES YES --- ---
DROP YES YES YES YES YES
EXECUTE YES --- --- --- YES
INDEX YES YES --- --- ---
INSERT YES YES YES --- ---
SELECT YES YES YES YES ---
TRIGGER YES YES --- --- ---
UPDATE YES YES YES --- ---
DELETE, INSERT and UPDATE on views are valid for updatable views only, meaning such views complying tosome restrictions as there are: no join included, no UNION included, no aggregation and some furtherrestrictions.
DEBUG is only valid for calculation views, not for other kinds of views. For synonyms those restrictions are valid, which are valid for the object this synonym stands for.
<object_name> ::= <table_name> | <view_name> | <sequence_name> | <procedure_name> | <synonym_name>
Object privileges are used to restrict the access and modifications on database objects like tables, views,sequences, procedures and synonyms.
<grantee> :: = <user_name> | <role_name>
The grantee can be a user or a role. In case a privilege or role is granted to a role, then all user being grantedthat role, will have the specified privilege or role.
A role is a named collection of privileges and can be granted to either a user or a role. If you want to allow several database users to perform the same actions, you can create a role, grant theneeded privileges to this role, and grant the role to the different database users. When granting roles to roles, a tree of roles can be build. When granting one role (R) to a role or user (G), Gwill have all privileges directly granted to R and all privileges granted to roles which had been granted to R.
<user_name> ::= <identifier> <role_name> ::= <identifier> <schema_name> ::= <identifier> <table_name> ::= <identifier> <view_name> ::= <identifier> <sequence_name> ::= <identifier> <procedure_name> ::= <identifier> <synonym_name> ::= <identifier> <privilege_name> ::= <identifier>
Description
GRANT is used to grant privileges and structured privileges to users and roles. GRANT is also used to grantroles to users and other roles.
The specified users, roles, objects, and structured privileges have to exist before they can be used in theGRANT command. Only users having a privilege and being allowed to grant that privilege any further can grant a privilege. Eachuser having ROLE ADMIN system privilege is allowed to grant roles to other roles and users.
SAP HANA Database - SQL Reference Manual
140 2012-08-21
A user can not grant a privilege to himself. User SYSTEM has at least all system privileges and the role PUBLIC. All other users have the role PUBLIC.These privileges and roles can not be revoked from them.
Although user SYSTEM has many privileges, he is not able to select or change data in other user's tables if heis not granted the privilege to do so explicitly. User SYSTEM and all other users do have the privilege to create objects in their own default schema, whichhas the same name as the user itself.For tables created by themselves, users have all privileges and may grant all of them to users and roles.For other objects which are dependent on objects like views being dependent on tables, it may happen, thateven the owner of the dependent object does not have all privileges if he does not have them on theunderlying objects. Or it may happen, that he has privileges, but is not allowed to grant them any further.Then he cannot grant those privileges.
WITH ADMIN OPTION and WITH GRANT OPTION specifies that the granted privileges can be granted furtherby the specified user or by those user having the specified role.
With GRANT STRUCTURED PRIVILEGE <structured_privilege_name> a previously defined analytical privilege(based on a generic structured privilege) is granted to a user or role. This analytical privileges is used torestrict the access for read operations to certain data in Analytic, Attribute, and Calculation Views by filteringthe attribute values.
System and Monitoring Views
USERS: shows all users, their creator, creation date and some info about their current states. ROLES: shows all roles, their creator and creation date. GRANTED_ROLES: shows which roles are granted to which user or role. GRANTED_PRIVILEGES: shows which privileges are granted to which user or role.
Example
Assuming a user, who has the privileges to create schemas, roles and users, is connected. He creates aschema for some work.
CREATE SCHEMA myschema;
Additionally he creates a a table, named work_done, in this new schema.
CREATE TABLE myschema.work_done (t TIMESTAMP, user NVARCHAR (256), work_done VARCHAR (256);
He creates one new user, named worker, with the possibility to connect using a password and a new role,named role_for_work_on_my_schema.
CREATE USER worker PASSWORD His_Password_1; CREATE ROLE role_for_work_on_my_schema;
He grants the privilege to SELECT on any object in his schema to the role role_for_work_on_my_schema.
GRANT SELECT ON SCHEMA myschema TO role_for_work_on_my_schema;
Additionally he grants the privilege to INSERT into his table work_done to the rolerole_for_work_on_my_schema.
GRANT INSERT ON myschema.work_done TO role_for_work_on_my_schema;
Then he grants this role to that new user.
GRANT role_for_work_on_my_schema TO worker WITH GRANT OPTION;
Additionally the user worker is granted the privilege to DELETE from this table directly. This privilege isgranted with the option to grant this privilege further.
GRANT DELETE ON myschema.work_done TO worker;
Now he grants the privilege to create any kind of object in his schema myschema to user worker directly.
SAP HANA Database - SQL Reference Manual
141 2012-08-21
GRANT CREATE ANY ON SCHEMA myschema TO worker;
As a result, user worker has the privilege to SELECT all tables and views in schema myschema, to INSERT intoand DELETE from table myschema.work_done and to create objects in schema myschema. Additionally he isallowed to grant DELETE on myschema.work_done to other users and roles.
In the second example a user having the corresponding privileges inclusive the allowance to grant themfurther, grants the system privileges INIFILE ADMIN and TRACE ADMIN to the existing user worker. He doesthis with the allowance for worker to grant them further.
GRANT INIFILE ADMIN, TRACE ADMIN TO worker WITH ADMIN OPTION;
REVOKE
Syntax
REVOKE <system_privilege>,... FROM <grantee> | REVOKE <schema_privilege>,... ON SCHEMA <schema_name> FROM <grantee> | REVOKE <object_privilege>,... ON <object_name> FROM <grantee> | REVOKE <role_name>,... FROM <grantee> | REVOKE STRUCTURED PRIVILEGE <privilege_name> FROM <grantee>
Syntax Elements
For the definition of syntax elements, please refer to GRANT.
Description
The REVOKE statement revokes the specified roles or structured privileges or the privileges for the specifiedobjects from the specified users or roles. Only users having granted a privilege can revoke that privilege. This is true even for users having ROLEADMIN and the revoke of roles.User SYSTEM has at least all system privileges and the role PUBLIC. All other users have the role PUBLIC.These privileges and roles can not be revoked from them.
If a user was granted a role, it is not possible to revoke some of the privileges belonging to that role. In thiscase, the whole role has to be revoked and those privileges needed by that user granted to him. Revoking a privilege or role may lead to making some views inaccessible or making procedures notexecutable any more. This will occur if a view or procedures depends on the privilege revoked or on one ofthe privileges the role had. Revoking a privilege which had been granted with WITH GRANT OPTION or with WITH ADMIN OPTION willresult in revoking that privilege not only from the user specified in the command, but from all the users androles having been granted that privilege by this user directly and indirectly.
As privileges can be granted to one user or role by different users, revoking of this privilege by one user doesnot necessarily mean, that this user will loose that privilege. For the description of syntax elements andprivileges, please refer to GRANT.
System and Monitoring Views
USERS: shows all users, their creator, creation date and some info about their current states. ROLES: shows all roles, their creator and creation date. GRANTED_ROLES: shows which roles are granted to which user or role. GRANTED_PRIVILEGES: shows which privileges are granted to which user or role.
Example
Assuming that the following statements had been executed by the user currently connected.
CREATE USER worker PASSWORD His_Password_1; CREATE ROLE role_for_work_on_my_schema; CREATE TABLE myschema.work_done (t TIMESTAMP, user NVARCHAR (256), work_done VARCHAR (256); GRANT SELECT ON SCHEMA myschema TO role_for_work_on_my_schema; GRANT INSERT ON myschema.work_done TO role_for_work_on_my_schema; GRANT role_for_work_on_my_schema TO worker; GRANT TRACE ADMIN TO worker WITH ADMIN OPTION; GRANT DELETE ON myschema.work_done TO worker WITH GRANT OPTION;
SAP HANA Database - SQL Reference Manual
142 2012-08-21
The user having granted privileges is allowed to revoke those privileges. He revokes the privilege from therole and therefore implicitly revokes it from all users being granted that role. Additionally the user workershould not have the privilege TRACE ADMIN any more. It is revoked causing the revocation to occur for allthe users, worker had granted this privilege to.
REVOKE SELECT ON SCHEMA myschema FROM role_for_work_on_my_schema; REVOKE TRACE ADMIN FROM worker;
Data Import Export Statements
EXPORT
Syntax
EXPORT <object_name_list> AS <export_format> INTO <path> [WITH <export_option_list>]
Syntax Elements
WITH <export_option_list>:
EXPORT options can be passed in using "WITH" clause.
<object_name_list> ::= <OBJECT_NAME>,... | ALL <export_import_format> ::= BINARY | CSV <path> ::= 'FULL_PATH' <export_option_list> ::= <export_option> | <export_option_list> <export_option> <export_option> ::= REPLACE | CATALOG ONLY | NO DEPENDENCIES | SCRAMBLE [BY <password>] | THREADS <number_of_threads>
Description
The EXPORT command exports tables, views, column views, synonyms, sequences, or procedures in thespecified format as BINARY or CSV. Data for temporary tables and "no logging" tables cannot be exportedusing EXPORT.
OBJECT_NAMESQL name of the object (table, view, etc) to export. To export all objects from all schemas you should use thekeyword ALL. If you want to export objects of a specific schema, you should use the schema name with theasterisk, e.g. "SYSTEM"."*"
BINARYTable data will be exported in internal binary format. Exporting in this format is orders of magnitude fasterthen exporting the same table in CSV format. Only column tables can be exported in binary format. The rowtables are always exported in CSV format, even if BINARY format is specified.
CSVTable data will be exported in CSV format. The exported data can be imported only in any other database.Additionaly, the exported data can be scramled. Both column and row tables can be exported in CSV format.
FULL_PATHThe server path to export to.
Note:When using a distributed system, the FULL_PATH must point to a shared disk! For security reasons,the path may not contain symbolic links and may not point inside the database instance folder,except its 'backup' and 'work' subfolders. Examples for valid export path (assuming the databaseinstance is located at /usr/sap/HDB/HDB00):
'/tmp'<br> '/usr/sap/HDB/HDB00/backup'<br> '/usr/sap/HDB/HDB00/work'<br>
REPLACEWith REPLACE option, previously exported data will be removed and newly exported data will be saved. IfREPLACE option is not specified, an error will be thrown if there exists a previously exported data already inthe specified directory.
SAP HANA Database - SQL Reference Manual
143 2012-08-21
CATALOG ONLYWith CATALOG ONLY option, only database catalog will be exported without data.
NO DEPENDENCIESWith NO DEPENDENCIES option, it will not export underlying objects of an object to be exported.
SCRAMBLEExport in CSV format has an additional option to scramble sensitive customer data using SCRAMBLE [BY'<password>']. When the optional password is not specified, a default scramble password is used. Onlycharacter string data can be scrambled. When imported, scrambled data will be imported as scrambled sothat end users cannot read the data and it is not possible to unscramble the data.
THREADSIndicates the number of threads that can be used for concurrent export.
Number of threads to use
The given number of THREADS specifies how many objects will be exported in parallel (default is 1).Increasing number of threads may reduce export time, but also can negatively affect the systemperformance.
Following should be considered:
For a single table THREADS has no effect.For a view or procedure, 2 or more threads should be used (up to number of objects it depends on)For a whole schema consider using more that 10 threads (up to number of cores in the system)For a whole BW / ERP system (ALL keyword) with tens of thousands of tables, a large number ofthreads can be reasonable (up to 256)
Number of threads to use
You can monitor the progress of the export using M_EXPORT_BINARY_STATUS system views.
You can abort the export session using the session ID from the corresponding view in the following command:
ALTER SYSTEM CANCEL [WORK IN] SESSION 'sessionId'
The detailed result of the export is stored in session-local temporary tables. #EXPORT_RESULT.
Number of threads to use
EXPORT "SCHEMA"."*" AS CSV INTO '/tmp' WITH REPLACE SCRAMBLE THREADS 10
IMPORT
Syntax
IMPORT <object_name_list> [AS <import_format>] FROM <path> [WITH <import_option_list>]
Syntax Elements
WITH <import_option_list>:
IMPORT options can be passed in using "WITH" clause.
<object_name_list> ::= <object_name>,... | ALL <import_format> ::= BINARY | CSV <path> ::= 'FULL_PATH' <import_option_list> ::= <import_option> | <import_option_list> <import_option> <import_option> ::= REPLACE | CATALOG ONLY | NO DEPENDENCIES | THREADS <number_of_threads>
Description
The IMPORT statement imports tables, views, column views, synonyms, sequences, or procedures. Data fortemporary tables and "no logging" tables cannot be imported using IMPORT command.
SAP HANA Database - SQL Reference Manual
144 2012-08-21
OBJECT_NAMESQL name of the object (table, view, etc) to import. To import all objects from the import path you should usethe keyword ALL. If you want to import objects of a specific schema, you should use the schema name withthe asterisk, e.g. "SYSTEM"."*"
BINARY | CSVFormat specification may be ommited during the import, since the format will be auto-detected duringimport. The data will be imported in the same format in which it was exported.
FULL_PATHThe server path to import from.
Note:When using a distributed system, the FULL_PATH must point to a shared disk! Examples for validimport path (assuming the database instance is located at /usr/sap/HDB/HDB00):
'/tmp'<br> '/usr/sap/HDB/HDB00/backup'<br> '/usr/sap/HDB/HDB00/work'<br>
REPLACEWith REPLACE option, the specified table will be dropped and created and data will be imported. If REPLACEoption is not specified, an error will be thrown if there exists a table with the same name in the sameschema.
CATALOG ONLYWith CATALOG ONLY option, only database catalog will be imported without data.
NO DEPENDENCIESWith NO DEPENDENCIES option, it will not import underlying objects of an object to be imported.
THREADSIndicates the number of threads that can be used for concurrent import.
Number of threads to use
The given number of THREADS specifies how many objects will be imported in parallel (default is 1).Increasing number of threads may reduce import time, but also can negatively affect the systemperformance.
Following should be considered:
For a single table THREADS has no effect.For a view or procedure, 2 or more threads should be used (up to number of objects it depends on)For a whole schema consider using more that 10 threads (up to number of cores in the system)For a whole BW / ERP system (ALL keyword) with tens of thousands of tables, a large number ofthreads can be reasonable (up to 256)
Number of threads to use
You can monitor the progress of the import using M_IMPORT_BINARY_STATUS system views.
Also, you can abort the import session using the connection ID from the corresponding view in the followingcommand:
ALTER SYSTEM CANCEL [WORK IN] SESSION 'sessionId'
The detailed result of the import is stored in session-local temporary tables. #IMPORT_RESULT.
Example
IMPORT "SCHEMA"."*" AS CSV FROM '/tmp' WITH REPLACE THREADS 10
IMPORT FROM
Syntax
IMPORT FROM [<file_type>] <file_path> [INTO <table_name>] [WITH <import_from_option_list>]
Syntax Elements
SAP HANA Database - SQL Reference Manual
145 2012-08-21
WITH <import_from_option_list>:
IMPORT FROM options can be passed in using "WITH" clause.
<file_type> ::= CSV FILE | CONTROL FILE <file_path> ::= '<character>...' <table_name> ::= [<schema_name>.]<identifier> <import_from_option_list> ::= <import_from_option> | <import_from_option_list> <import_from_option> <import_from_option> :: = THREADS <number_of_threads> | BATCH <number_of_records_of_each_commit> | TABLE LOCK | NO TYPE CHECK | SKIP FIRST <number_of_rows_to_skip> ROW | COLUMN LIST IN FIRST ROW | COLUMN LIST ( <column_name_list> ) | RECORD DELIMITED BY '<string_for_record_delimiter>' | FIELD DELIMITED BY '<string_for_field_delimiter>' | OPTIONALLY ENCLOSED BY '<character_for_optional_enclosure>' | DATE FORMAT '<string_for_date_format>' | TIME FORMAT '<string_for_time_format>' | TIMESTAMP FORMAT '<string_for_timestamp_format>' |
Description
The IMPORT FROM statements imports external data from a csv file into an existing table.
THREADS Indicates the number of threads that can be used for concurrent import. Default value is 1 andmaximum allowed value is 256.
BATCH Indicates the number of records to be inserted in each commit.
THREADS and BATCH can be used to achieve high loading performance by enabling parallel loading andcommitting many records at once. In general, for column tables, a good setting is to use 10 parallel loadingthreads, with a commit frequency of 10.000 records or greater.
TABLE LOCK Locks table for fast import into column store tables. If NO TYPE CHECK option is specified, thenthe record is inserted without checking the type of each field.
SKIP FIRST <int> ROW Skips to insert first n rows.
COLUMN LIST IN FIRST ROW Indicates the column list that is in the first row of CSV file.
COLUMN LIST ( <column_name_list> ) Indicates the column list to be inserted
RECORD DELIMITED BY '<string>' Indicates the record delimiter of the CSV file
FIELD DELIMITED BY '<string>' Indicates the field delimiter of the CSV file
OPTIONALLY ENCLOSED BY '<character>' Indicates the optional enclosure of field data
DATE FORMAT '<string>' Indicates the string of date format. If there is date type in CSV file, it will use thespecified format for date type field.
TIME FORMAT '<string>' Indicates the string of time format. If there is time type in CSV file, it will use thespecified format for time type field.
TIMESTAMP FORMAT '<string>' Indicates the string of timestamp format. If there is timestamp type in CSVfile, it will use the specified format for timestamp type field.
Example
IMPORT FROM CSV FILE '/data/data.csv' INTO "MYSCHEMA"."MYTABLE" WITH RECORD DELIMITED BY '\n' FIELD DELIMITED BY ','
SAP HANA Database - SQL Reference Manual
146 2012-08-21
Restrictions for SQL Statements
The table below shows the maximum allowable limit for each entry.
SAP HANA Database - SQL Reference Manual
147 2012-08-21
Database
Database size limit Limited by storage size RS: 1TB
Number of locks Unlimited for record locks,16384 for table locks
Number of sessions 8192
Schemas
Number of tables in a schema 131072
Identifier length 127 characters
Length of an alias name 128 characters
Table name length Please see "Identifier length" above
Column name length Please see "Identifier length" above
Length of a constant string literal 32767 bytes
Number of hex characters in a binary literal 8192
Tables and Views
Number of columns in a table 1000
Number of columns in a view 1000
Number of partitions of a column table 1000
Number of rows in each table
Limited by storage size RS:1TB/sizeof(row),
CS: 2^31 * number of partitions
Length of a row Limited by RS storage size ( 1TB )
Size of a non-partitioned table Limited by RS storage size ( 1TB )
Indexes and Constraints
Number of indexes for each table 1023
Number of primary key columns in each table 16
Number of columns in an index 16
Number of columns in a UNIQUE constraint 16
Size of sum of primary key, index, UNIQUE
constraint16384
SQL
SAP HANA Database - SQL Reference Manual
148 2012-08-21
Length of an SQL statement 2GB
Depth of SQL view nesting 128
Depth of SQL parse tree 255
Number of joined tables in an SQL statement or view 255
Number of columns in an ORDER BY, GROUP BY or SELECTclause
65535
Number of elements in predicates 65535
Number of elements in SELECT clause 65535
SQLScript
Size of all stored procedures Limited by RS s torage s i ze ( 1TB )
Note:You can obtain the current system limits from your SAP HANA Database instance by using
select * from m_system_limits
See Also
M_SYSTEM_LIMITS in the System Tables and Monitor Views Reference
SAP HANA Database - SQL Reference Manual
149 2012-08-21
SQL Error Codes
The following table lists error codes displayed by SAP HANA database and their descriptions.
SAP HANA Database - SQL Reference Manual
150 2012-08-21
ErrorCode
Description
1 Genera l warning
2 Genera l error
3 Fata l error
4 Cannot a l locate enough memory
5 Ini tia l i zation error
6 Inva l id data
7 Feature not supported
8 Inva l id argument
9 Index out of bounds
10 Inva l id username or password
11 Inva l id s tate
12 Cannot open fi le
13 Cannot create/wri te fi le
14 Cannot a l locate enough disk space
15 Cannot find fi le
16 Statement retry
17 Metadata schema vers ion incompatible between database and executable fi le
18 Service shutting down
19 Inva l id l i cense
128 Trans action error
129 Trans action rol led back by an interna l error
130 Trans action rol led back by integri ty constra int violation
131 Trans action rol led back by lock wai t timeout
132 Trans action rol led back due to unava i lable resource
133 Trans action rol led back by detected deadlock
134 Fa i lure in access ing checkpoint fi le
135 Fa i lure in access ing anchor fi le
136 Fa i lure in access ing log fi le
137 Fa i lure in access ing archive fi le
138 Trans action seria l i zation fa i lure
139 Current operation cancel led by request and transaction rol led back
140 Inva l id wri te-transaction identi fier
141 Fa i lure in access ing invis ible log fi le
142 Exceed max num of concurrent transactions
143 Trans action seria l i zation fa i lure unti l timeout expi res
144 Trans action rol lback, unique constra int violated
145 Trans action dis tribution work fa i lure
146 Res ource busy and acquire with NOWAIT speci fied
147 Incons is tency between data and log
148 Trans action s tart i s blocked unti l Master_Restart fini shes
149 Dis tributed transaction commit fa i lure
150 Statement cancel led due to old snapshot
256 SQL process ing error
257 SQL syntax error
258 Ins ufficient privi lege
259 Inva l id table name
260 Inva l id column name
261 Inva l id index name
262 Inva l id query name
263 Inva l id a l ias name
264 Inva l id datatype
265 Expres s ion miss ing
266 Incons is tent datatype
267 Speci fied length too long for i ts datatype
268 Column ambiguous ly defined
SAP HANA Database - SQL Reference Manual
151 2012-08-21
269 Too many va lues
270 Not enough va lues
271 Dupl icate a l ias
272 Dupl icate column name
273 Not a s ingle character s tring
274 Ins erted va lue too large for column
275 Aggregate function not a l lowed
276 Mis s ing aggregation or grouping
277 Not a GROUP BY express ion
278 Nested group function without GROUP BY
279 Group function i s nested
280 ORDER BY i tem must be the number of a SELECT-l i s t
281 Outer join not a l lowed in operand of OR or IN
282 Two tables cannot be outer-joined to each other
283 A table may be outer joined to at most one other table
284 Join field does not match
285 Inva l id join condi tion
286 Identi fier i s too long
287 Cannot insert NULL or update to NULL
288 Cannot use dupl icate table name
289 Cannot use dupl icate index name
290 Cannot use dupl icate query name
291 Argument identi fier must be pos i tive
292 wrong number of arguments
293 Argument type mismatch
294 Cannot have more than one primary key
295 Too long multi key length
296 Repl icated table must have a primary key
297 Cannot update primary key field in repl icated table
298 Cannot s tore DDL
299 Cannot drop index used for enforcement of unique/primary key
300 Argument index i s out of range
301 Unique constra int violated
302 Inva l id CHAR or VARCHAR va lue
303 Inva l id DATE, TIME or TIMESTAMP va lue
304 Divis ion by zero undefined
305 Single-row query returns more than one row
306 Inva l id cursor
307 Numeric va lue out of range
308 Column name a l ready exis ts
309 Correlated subquery cannot have TOP or ORDER BY
310 SQL error in procedure
311 Cannot drop a l l columns in a table
312 Sequence i s exhausted
313 Inva l id sequence
314 Numeric overflow
315 Inva l id synonym
316 wrong number of arguments in function invocation
317 P_QUERYPLANS not exis ts nor va l id format
318 Decimal precis ion speci fier i s out of range
319 Decimal sca le speci fier i s out of range
320 Cannot create index on express ion with datatype LOB
321 Inva l id view name
322 Cannot use dupl icate view name
323 Dupl icate repl ication ID
324 Cannot use dupl icate sequence name
325 Inva l id escape sequence
SAP HANA Database - SQL Reference Manual
152 2012-08-21
326 CURRVAL of given sequence i s not yet defined in this sess ion
327 Cannot expla in plan of given s tatement
328 Inva l id name of function or procedure
329 Cannot use dupl icate name of function or procedure
330 Cannot use dupl icate synonym name
331 User name a l ready exis ts
332 Inva l id user name
333 Column not a l lowed
334 Inva l id user privi lege
335 Field a l ias name a l ready exis ts
336 Inva l id defaul t va lue
337 INTO clause not a l lowed for this SELECT s tatement
338 Zero-length col lumns are not a l lowed
339 Inva l id number
340 Not a l l variables bound
341 Numeric underflow
342 Col la tion confl i ct
343 Inva l id col la te name
344 Parse error in data loader
345 Not a repl ication table
346 Inva l id repl ication ID
347 Inva l id option in monitor
348 Inva l id datetime format
349 Cannot CREATE UNIQUE INDEX
350 Cannot drop columns in the primary-key column l i s t
351 Column i s referenced in a multi -column constra int
352 Cannot create unique index on CDX table
353 Update log group name a l ready exis ts
354 Inva l id update log group name
355 The base table of the update log table must have a primary key
356 Exceed maximum number of update log group
357 The base table a l ready has a update log table
358 Update log table can not have a update log table
359 Concatenated s tring i s too long
360 View WITH CHECK OPTION where-clause violation
361 Data manipulation operation not lega l on this view
362 Inva l id schema name
363 Number of index columns exceeds i ts maximum
364 Inva l id partia l key s i ze
365 No matching unique or primary key for this column l i s t
366 Referenced table does not have a primary key
367 Number of referencing columns must match referenced columns
368 Unique constra int not a l lowed on temporary table
369 Exceed maximum view depth l imit
370 Cannot perform DIRECT INSERT operation on table with unique indexes
371 Inva l id XML document
372 Inva l id XPATH
373 Inva l id XML duration va lue
374 Inva l id XML function usage
375 Inva l id XML index operation
376 Python s tored procedure error
377 JIT operation error
378 Inva l id column view
379 Table s chema mismatch
380 Fa i l to change run level
381 Fa i l to res tart
382 Fa i l to col lect a l l vers ion garbage
SAP HANA Database - SQL Reference Manual
153 2012-08-21
383 Inva l id identi fier
384 Constant s tring i s too long
385 Could not res tore sess ion
386 Cannot use dupl icate schema name
387 Table ambiguous ly defined
388 Role a l ready exis ts
389 Inva l id role name
390 Inva l id user type
391 Inva l idated view
392 Can't ass ign cycl i c role
393 Roles must not receive a privi lege with grant option
394 Error revoking role
395 Inva l id user-defined type name
396 Cannot use dupl icate user-defined type name
397 Inva l id object name
398 Cannot have more than one order by
399 Role tree too deep
400 Primary key not a l lowed on insert-only table
401 Unique constra int not a l lowed on insert-only table
402 The user was a l ready dropped before query execution
403 Interna l error
404 Inva l id (non-exis tent) s tructured privi lege name
405 Cannot use dupl icate s tructured privi lege name
406 INSERT, UPDATE and UPSERT are disa l lowed on the generated field
407 Inva l id date format
408 Pass word or parameter required for user
409 Multiple va lues for a parameter not supported
410 Inva l id privi lege namespace
411 Inva l id table type
412 Inva l id password layout
413 Last n passwords can not be reused
414 User i s forced to change password
415 User i s deactivated
416 User i s locked
417 Can't drop without CASCADE speci fi cation
418 Inva l id view query for creation
419 Can't drop with RESTRICT speci fi cation.
420 Pass word change currently not a l lowed
421 Cannot create ful l text index
422 Privi leges must be ei ther a l l SQL or a l l from one namespace
423 LiveCache error
424 Inva l id name of package
425 Dupl icate package name
426 Number of columns mismatch
427 Cannot reserve index ID any more
428 Inva l id query plan ID
429 Integri ty check fa i led
430 Inva l idated procedure
431 User's password wi l l expi re within few days
432 This s yntax has been deprecated and wi l l be removed in next release
433 Nul l va lue found
434 Inva l id object ID
435 Inva l id express ion
436 Could not set sys tem l i cense
437 Only commands for l i cense handl ing are a l lowed in current s tate
438 Inva l id user parameter va lue
439 Compos i te error
SAP HANA Database - SQL Reference Manual
154 2012-08-21
440 Table type convers ion error
441 This feature has been deprecated and wi l l be removed in next release
442 Number of columns exceeds i ts maximum
443 Inva l id ca lculation scenario name
444 Package manager error
512 Repl ication error
513 Cannot execute DDL s tatement on repl ication table whi le repl icating
514 Fa i lure in access ing anchor fi le
515 Fa i lure in access ing log fi le
516 Repl ication table has not confl i ct report table
517 Confl i ct report table a l ready enabled
518 Confl i ct report table a l ready disabled
576 API error
577 Cursor type of forward i s not a l lowed
578 Inva l id s tatement
579 Exceed maximum batch s i ze
580 Server rejected the connection(protocol vers ion mismatch)
581 This function can be ca l led only in the case of s ingle s tatement
582 This query does not have resul t set
583 Connection does not exis t
584 No more lob data
585 Operation i s not permitted
586 Inva l id parameter i s received from server
587 Res ul t set i s currently inva l id
588 Next() i s not ca l led for this resul t set
589 Too many parameters are set
590 Some paramters are miss ing
591 Interna l error
592 Not supported type convers ion
593 Remote-only function
594 No more resul t row in resul t set
595 Speci fied parameter i s not output parameter
596 LOB s treaming i s not permitted in auto-commit mode
597 Sess ion context error
598 Fa i led to execute the externa l s tatement
599 Sess ion layer i s not ini tia l i zed yet
600 Fa i led routed execution
601 Too many sess ion variables are set
602 Cannot set readonly sess ion variable
603 Inva l id LOB
604 Remote temp table access fa i lure
605 Inva l id XA join request
606 Exceed maximum LOB s i ze
607 Fa i led to cleanup resources
608 Exceed maximum number of prepared s tatements
1024 Sess ion error
1025 Communication error
1026 Cannot bind a communication port
1027 Communication ini tia l i zation error
1028 I/O control error
1029 Connection fa i lure
1030 Send error
1031 Receive error
1032 Cannot create a thread
1033 Error whi le pars ing protocol
1034 Exceed maximum number of sess ions
1035 Not supported vers ion
SAP HANA Database - SQL Reference Manual
155 2012-08-21
1036 Inva l id sess ion ID
1037 Unknown hostname
1280 SqlScript error
1281 Wrong number or types of parameters in ca l l
1282 Output parameter not avariable
1283 OUT and IN OUT parameters may not have defaul t expres s ions
1284 Dupl icate parameters are not permitted
1285 At mos t one declaration i s permitted in the declaration section
1286 Cursor must be declared by SELECT s tatement
1287 Identi fier must be declared
1288 Expres s ion cannot be used as an ass ignment target
1289 Expres s ion cannot be used as an INTO-target of SELECT/FETCH s tatement
1290 Expres s ion i s inappropriate as the left hand s ide of an ass ignment s tatement
1291 Expres s ion i s of wrong type
1292 Il lega l EXIT s tatement, i t must appear ins ide a loop
1293 Identi fier name must be an exception name
1294 An INTO clause i s expected in SELECT s tatement
1295 EXPLAIN PLAN and CALL s tatement are not a l lowed
1296 Identi fier i s not a cursor
1297 Wrong number of va lues in the INTO l i s t of a FETCH s tatement
1298 Unhandled user-defined exception
1299 No data found
1300 Fetch returns more than requested number of rows
1301 Numeric or va lue error
1302 Para l lel i zable function cannot have OUT or IN OUT parameter
1303 User-defined exception
1304 Cursor i s a l ready opened
1305 Return type i s inva l id
1306 Return type mismatch
1307 Unsupported datatype i s used
1308 Il lega l s ingle ass ignment
1309 Inva l id use of table variable
1310 Sca lar type i s not a l lowed
1311 Out parameter i s not speci fied
1312 At mos t one output parameter i s a l lowed
1313 Output parameter should be a table or a table variable
1314 Inappropriate variable name: do not a l low "" for the name of variable or parameter
1315 Return resul t set from select s tmt exis t when resul t view i s defined
1316 Some out table var i s not ass igned
1317 Function name exceedes max. l imit
1318 Bui l t-in function not defined
1319 Parameter must be a table name
1320 Parameter must be an attribute name without a table name upfront
1321 Parameter must be an attribute name without an a l ias
1322 CE_CALC not a l lowed
1323 Parameter must be a vector of columns or aggregations
1324 Join attribute must be ava i lable in projection l i s t
1325 Parameter must be a vector of SQL identi fiers
1326 Dupl icate attribute name
1327 Parameter has a non supported type
1328 Attribute not found in column table
1329 Dupl icate column name
1330 Syntax Error for ca lculated Attribute
1331 Syntax Error in fi l ter express ion
1332 Parameter must be a va l id column table name
1333 Join attributes not found in variable
1334 Input parameters do not have the same table type
SAP HANA Database - SQL Reference Manual
156 2012-08-21
1335 Cycl ic dependency found in a runtime procedure
1336 Unexpected interna l exception caught in a runtime procedure
1337 Variable depends on an unass igned variable
1338 CE_CONVERSION: customizing table miss ing
1339 Too many parameters
1340 The depth of the nested ca l l i s too deep
1536 Swapx error
1537 This table has no swap space
1538 Swap a l ready activated
1539 Swap not yet activated
1540 Swap s pace i s not created
1541 Fa i lure in unpinning a swap page
1542 Fa i lure in swap fi le
1543 Fa i lure in access ing swap data fi le
1544 Fa i lure in access ing swap log fi le
1545 Swap buffer overflow
1546 Swap buffer reservation fa i lure
1792 Shared memory error
1793 Inva l id key or inva l id s i ze
1794 The segment a l ready exis ts
1795 Exceed the sys tem-wide l imit on shared memory
1796 No segment exis ts for the given key, and IPC_CREAT was not speci fied
1797 The user does not have permiss ion to access the shared memory s egment
1798 No memory could be a l located for segment overhead
1799 Inva l id shmid
1800 Al low read access for shmid
1801 Shmid points to a removed identi fier
1802 The effective user ID of the ca l l ing process i s not the creator
1803 The GID or UID va lue i s too large to be s tored in the s tructure
1804 The user does not have permiss ion to access the shared memory s egment
1805 Inva l id shmid
1806 No memory could be a l located for the descriptor or for the page tables
1807 Unknown shared memory error
2048 Column s tore error
2049 Primary key i s not speci fied for column table
2050 Not supported ddl type for column table
2051 Not supported data type for column table
2052 Not supported dml type for column table
2053 Inva l id returned va lue from attribute engine
2304 Python DBAPI error
2305 Interface fa i lure
2306 Programming mis take
2307 Inva l id query parameter
2308 Not supported encoding for s tring
2560 Dis tributed metadata error
2561 DDL redi rect error
2562 DDL noti fi cation error
2563 DDL inva l id conta iner ID
2564 DDL inva l id index ID
2565 Dis tributed envi ronment error
2566 Network error
2567 Metadata update not supported in s lave
2568 Metadata update of master indexserver i s fa i led
2816 SqlScript Error
2817 SqlScript Bui l tin Function
2818 -2889
SqlScript
3584 Dis tributed SQL error
SAP HANA Database - SQL Reference Manual
157 2012-08-21
3585 Expres s ion shipping fa i lure
3586 Operator shipping fa i lure
3587 Inva l id protocol or indexserver (s tati s ti csserver) shutdown during dis tributed query execution
3588 Sequence shipping fa i lure
3589 Remote query exectuion fa i lure
3840 genera l audi ting error
3841 Inva l id privi lege
3842 Audit tra i l wri ter i s blocked
3843 Audit pol icy wi th current name a l ready exis ts
3844 Inva l id combination of audi t actions
3845 Inva l id action s tatus for audi ting
3846 Inva l id audi ting level
3847 Inva l id pol icy name
4096 Genera l error in the process of s tored plan
4097 Inva l id operation in generating plans
4098 Inva l id operation in execution the chosen plan
4099 Inva l id operation in s toring the pinned plan
4100 Inva l id operation in loading the s tored plan
4101 Inva l id operation in deleting the chosen plan
4103 Fa i led to prepare for runtime reorganization
4104 Trans action blocked s ince runtime reorganization i s in progres s
4105ERR_REORG_TRANS_EXISTS_GENERAL. Cannot s tart reorganization due to the transactions inexecution
SAP HANA Database - SQL Reference Manual
158 2012-08-21