Hana sql

3,509 views
3,272 views

Published on

Sap Hana

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,509
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
146
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Hana sql

  1. 1. SAP HANA Database - SQL Reference Manual SAP HANA Appliance Software SPS 04 Target Audience Consultants Administrators SAP Hardware Partner Others1 2012-05-09
  2. 2. Copyright © Copyright 2012 SAP AG. All rights reserved SAP Library document classification: PUBLIC No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP AG. The information contained herein may be changed without prior notice. Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors. Microsoft, Windows, Excel, Outlook, PowerPoint, Silverlight, and Visual Studio are registered trademarks of Microsoft Corporation. IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x, System z, System z10, z10, z/VM, z/OS, OS/390, zEnterprise, PowerVM, Power Architecture, Power Systems, POWER7, POWER6+, POWER6, POWER, PowerHA, pureScale, PowerPC, BladeCenter, System Storage, Storwize, XIV, GPFS, HACMP, RETAIN, DB2 Connect, RACF, Redbooks, OS/2, AIX, Intelligent Miner, WebSphere, Tivoli, Informix, and Smarter Planet are trademarks or registered trademarks of IBM Corporation. Linux is the registered trademark of Linus Torvalds in the United States and other countries. Adobe, the Adobe logo, Acrobat, PostScript, and Reader are trademarks or registered trademarks of Adobe Systems Incorporated in the United States and other countries. Oracle and Java are registered trademarks of Oracle and its affiliates. UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group. Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, and MultiWin are trademarks or registered trademarks of Citrix Systems Inc. HTML, XML, XHTML, and W3C are trademarks or registered trademarks of W3C®, World Wide Web Consortium, Massachusetts Institute of Technology. Apple, App Store, iBooks, iPad, iPhone, iPhoto, iPod, iTunes, Multi-Touch, Objective-C, Retina, Safari, Siri, and Xcode are trademarks or registered trademarks of Apple Inc. IOS is a registered trademark of Cisco Systems Inc. RIM, BlackBerry, BBM, BlackBerry Curve, BlackBerry Bold, BlackBerry Pearl, BlackBerry Torch, BlackBerry Storm, BlackBerry Storm2, BlackBerry PlayBook, and BlackBerry App World are trademarks or registered trademarks of Research2 2012-05-09
  3. 3. in Motion Limited. Google App Engine, Google Apps, Google Checkout, Google Data API, Google Maps, Google Mobile Ads, Google Mobile Updater, Google Mobile, Google Store, Google Sync, Google Updater, Google Voice, Google Mail, Gmail, YouTube, Dalvik and Android are trademarks or registered trademarks of Google Inc. INTERMEC is a registered trademark of Intermec Technologies Corporation. Wi-Fi is a registered trademark of Wi-Fi Alliance. Bluetooth is a registered trademark of Bluetooth SIG Inc. Motorola is a registered trademark of Motorola Trademark Holdings LLC. Computop is a registered trademark of Computop Wirtschaftsinformatik GmbH. SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP BusinessObjects Explorer, StreamWork, SAP HANA, and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP AG in Germany and other countries. Business Objects and the Business Objects logo, BusinessObjects, Crystal Reports, Crystal Decisions, Web Intelligence, Xcelsius, and other Business Objects products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of Business Objects Software Ltd. Business Objects is an SAP company. Sybase and Adaptive Server, iAnywhere, Sybase 365, SQL Anywhere, and other Sybase products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of Sybase Inc. Sybase is an SAP company. Crossgate, m@gic EDDY, B2B 360°, and B2B 360° Services are registered trademarks of Crossgate AG in Germany and other countries. Crossgate is an SAP company. All other product and service names mentioned are the trademarks of their respective companies. Data contained in this document serves informational purposes only. National product specifications may vary. These materials are subject to change without notice. These materials are provided by SAP AG and its affiliated companies ("SAP Group") for informational purposes only, without representation or warranty of any kind, and SAP Group shall not be liable for errors or omissions with respect to the materials. The only warranties for SAP Group products and services are those that are set forth in the express warranty statements accompanying such products and services, if any. Nothing herein should be construed as constituting an additional warranty.3 2012-05-09
  4. 4. Table of ContentTable of ContentTable of Content 4SAP HANA Database - SQL Reference Manual 8 SQL Reference Ma nua l 9 Nota ti on 10 Introducti on 11 SQL 11 Supported Languages and Code Pages 11 Comment 11 Identifiers 11 Single Quotation Mark 11 Double Quotation Mark 11 SQL Reserved Words 12 Da ta Types 13 Classification of Data Types 13 Datetime Types 13 Date Formats 13 Time Formats 14 Timestamp Formats 14 Additional Formats 14 Supported Functions for Date/Time types 15 Numeric Types 15 Character String Types 16 Binary Types 17 Large Object (LOB) Types 17 Mapping between SQL Data Type and Column Store Data Type 18 Data Type Conversion 18 Typed Constant 20 Predi ca tes 22 Comparison Predicates 22 Range Predicate 22 In Predicate 22 Exists Predicate 22 LIKE Predicate 22 NULL Predicate 22 CONTAINS Predicate 23 Opera tors 25 Unary and Binary Operators 25 Operator Precedence 25 Arithmetic Operators 25 String Operators 26 Comparsion Operators 26 Logical Operators 26 Set Operators 26 Expres s i ons 28 Case Expressions 28 Function Expressions 28 Aggregate Expressions 28 Subqueries in Expressions 28 SQL Functi ons 30 Introduction 30 Data Type Conversion Functions 30 CAST 30 TO_ALPHANUM 30 TO_BIGINT 30 TO_BINARY 31 TO_BLOB 31 TO_CHAR 31 TO_CLOB 31 TO_DATE 32 TO_DATS 324 2012-05-09
  5. 5. Table of Content TO_DECIMAL 32 TO_DOUBLE 33 TO_INT 33 TO_INTEGER 33 TO_NCHAR 33 TO_NCLOB 34 TO_NVARCHAR 34 TO_REAL 34 TO_SECONDDATE 34 TO_SMALLDECIMAL 35 TO_SMALLINT 35 TO_TIME 35 TO_TIMESTAMP 35 TO_TINYINT 36 TO_VARCHAR 36 DateTime Functions 36 ADD_DAYS 36 ADD_MONTHS 37 ADD_SECONDS 37 ADD_YEARS 37 CURRENT_DATE 37 CURRENT_TIME 38 CURRENT_TIMESTAMP 38 CURRENT_UTCDATE 38 CURRENT_UTCTIME 38 CURRENT_UTCTIMESTAMP 39 DAYNAME 39 DAYOFMONTH 39 DAYOFYEAR 39 DAYS_BETWEEN 40 EXTRACT 40 HOUR 40 ISOWEEK 40 LAST_DAY 41 LOCALTOUTC 41 MINUTE 41 MONTH 42 MONTHNAME 42 NEXT_DAY 42 NOW 42 QUARTER 43 SECOND 43 SECONDS_BETWEEN 43 UTCTOLOCAL 43 WEEK 44 WEEKDAY 44 YEAR 44 Number Functions 44 ABS 44 ACOS 45 ASIN 45 ATAN 45 ATAN2 46 BINTOHEX 46 BITAND 46 CEIL 46 COS 47 COSH 47 COT 47 EXP 47 FLOOR 48 GREATEST 48 HEXTOBIN 48 LEAST 48 LN 49 LOG 49 MOD 49 POWER 50 ROUND 50 SIGN 50 SIN 50 SINH 51 SQRT 51 TAN 51 TANH 51 UMINUS 525 2012-05-09
  6. 6. Table of Content String Functions 52 ASCII 52 CHAR 52 CONCAT 53 LCASE 53 LEFT 53 LENGTH 53 LOCATE 54 LOWER 54 LPAD 54 LTRIM 55 NCHAR 55 REPLACE 55 RIGHT 55 RPAD 56 RTRIM 56 SUBSTR_AFTER 56 SUBSTR_BEFORE 57 SUBSTRING 57 TRIM 57 UCASE 58 UNICODE 58 UPPER 58 Miscellaneous Functions 59 COALESCE 59 CURRENT_CONNECTION 59 CURRENT_SCHEMA 59 CURRENT_USER 59 GROUPING_ID 60 IFNULL 61 MAP 61 NULLIF 62 SESSION_CONTEXT 62 SESSION_USER 63 SYSUUID 63 SQL Sta tements 64 Schema Definition and Manipulation Statements 64 ALTER AUDIT POLICY 64 ALTER FULLTEXT INDEX 65 ALTER INDEX 65 ALTER SEQUENCE 66 ALTER TABLE 67 CREATE AUDIT POLICY 70 CREATE CALCULATION SCENARIO 72 CREATE FULLTEXT INDEX 73 CREATE INDEX 73 CREATE SCHEMA 74 CREATE SEQUENCE 74 CREATE SYNONYM 75 CREATE TABLE 76 CREATE TRIGGER 80 CREATE VIEW 82 DROP AUDIT POLICY 82 DROP CALCULATION SCENARIO 83 DROP FULLTEXT INDEX 83 DROP INDEX 84 DROP SCHEMA 84 DROP SEQUENCE 84 DROP SYNONYM 85 DROP TABLE 85 DROP TRIGGER 86 DROP TYPE 86 DROP VIEW 86 RENAME COLUMN 87 RENAME INDEX 87 RENAME TABLE 87 ALTER TABLE ALTER TYPE 88 TRUNCATE TABLE 88 Data Manipulation Statements 89 DELETE 89 EXPLAIN PLAN 89 INSERT 92 LOAD 93 MERGE DELTA 93 REPLACE | UPSERT 936 2012-05-09
  7. 7. Table of Content SELECT 94 UNLOAD 101 UPDATE 101 System Management Statements 102 SET SYSTEM LICENSE 102 ALTER SYSTEM ALTER CONFIGURATION 102 ALTER SYSTEM ALTER SESSION SET 103 ALTER SYSTEM CANCEL [WORK IN] SESSION 104 ALTER SYSTEM CLEAR SQL PLAN CACHE 104 ALTER SYSTEM CLEAR TRACES 104 ALTER SYSTEM DELETE ALL HANDLED EVENTS 105 ALTER SYSTEM DELETE HANDLED EVENT 105 ALTER SYSTEM DISCONNECT SESSION 105 ALTER SYSTEM LOGGING 105 ALTER SYSTEM RECLAIM DATAVOLUME 106 ALTER SYSTEM RECLAIM LOG 106 ALTER SYSTEM RECLAIM VERSION SPACE 106 ALTER SYSTEM RECONFIGURE SERVICE 107 ALTER SYSTEM REMOVE TRACES 107 ALTER SYSTEM RESET MONITORING VIEW 107 ALTER SYSTEM SAVE PERFTRACE 107 ALTER SYSTEM SAVEPOINT 108 ALTER SYSTEM SET EVENT HANDLED 108 ALTER SYSTEM START PERFTRACE 108 ALTER SYSTEM STOP PERFTRACE 108 ALTER SYSTEM STOP SERVICE 108 UNSET SYSTEM LICENSE ALL 109 Session Management Statements 109 CONNECT 109 SET HISTORY SESSION 109 SET SCHEMA 110 SET [SESSION] 110 UNSET [SESSION] 110 Transaction Management Statements 111 COMMIT 111 LOCK TABLE 111 ROLLBACK 111 SET TRANSACTION 112 Access Control Statements 112 ALTER SAML PROVIDER 112 ALTER USER 113 CREATE ROLE 115 CREATE SAML PROVIDER 115 CREATE USER 116 DROP ROLE 117 DROP SAML PROVIDER 117 DROP USER 118 GRANT 118 REVOKE 123 Data Import Export Statements 124 EXPORT 124 IMPORT 125 IMPORT FROM 1267 2012-05-09
  8. 8. SAP HANA Database - SQL Reference ManualSAP HANA Database - SQL Reference ManualThis guide describes SQL language supported by SAP HANA DB.8 2012-05-09
  9. 9. SAP HANA Database - SQL Reference ManualSQL Reference Manual9 2012-05-09
  10. 10. SAP HANA Database - SQL Reference ManualNotationThis 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 Angl e bra ckets a re us ed to s urround the na me of a s ynta cti c el ement (BNF nontermi na l ) of the SQL <> l a ngua ge. The defi ni ti on opera tor i s us ed to provi de defi ni ti ons of the el ement a ppea red on the l eft s i de of ::= the opera tor i n a producti on rul e. Squa re bra ckets a re us ed to i ndi ca te opti ona l el ements i n a formul a . Opti ona l el ements ma y be [] s peci fi ed or omi tted. Bra ces group el ements i n a formul a . Repeti ti ve el ements (zero or more el ements ) ca n be s peci fi ed {} wi thi n bra ce s ymbol s . The a l terna ti ve opera tor i ndi ca tes tha t the porti on of the formul a fol l owi ng the ba r i s a n | a l terna ti ve to the porti on precedi ng the ba r. The el l i ps i s i ndi ca tes tha t the el ement ma y be repea ted a ny number of ti mes . If el l i ps i s a ppea rs ... a fter grouped el ements s peci fyi ng tha t the grouped el ements encl os ed wi th bra ces a re repea ted. If el l i ps i s a ppea rs a fter a s i ngl e el ement, onl y tha t el ement i s repea ted. Introduces norma l Engl i s h text. Thi s i s us ed when the defi ni ti on of a s ynta cti c el ement i s not !! expres s ed i n BNF.10 2012-05-09
  11. 11. SAP HANA Database - SQL Reference ManualIntroductionThis 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.SQLSQL 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 manipulation Data manipulation System management Session management Transaction managementSupported Languages and Code PagesThe SAP HANA Database supports Unicode to allow the use of all languages in the Unicode Standard and 7 BitASCII code page without restriction.CommentYou 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 the SQL parser to be a comment "/*" and "*/". This style of commenting is used to place comments on multiple lines. All text between the opening "/*" and closing "*/" is ignored by the SQL parser.IdentifiersSyntax: <identifier> ::= <simple_identifier> | <double_quotes><special_identifier><double_qu otes> <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 other than digits or an underscore "_". Delimited identifiers are enclosed in the delimiter, double quotes, then the identifier can contain any character including special characters. For example, "AB$%CD" is a valid identifier name. Limitations: "_SYS_" is reserved exclusively for database engine, hence not allowed at the beginning of schema object names. Role name and user name must be specified as undelimited identifiers. Maximum length for the identifiers is 127 characters.Single Quotation MarkSingle quotation marks are used to delimit string literals and single quotation mark itself can be representedusing two single quotation marks.Double Quotation Mark11 2012-05-09
  12. 12. SAP HANA Database - SQL Reference ManualDouble quotation marks are used to delimit identifiers and double quotation mark itself can be representedusing two double quotation marks.SQL Reserved WordsReserved 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. 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 WITHTable 1. Reserved Words12 2012-05-09
  13. 13. SAP HANA Database - SQL Reference ManualData TypesThis 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 TypesIn the SAP HANA Database each data type can be classified by its characteristic as follows: Classification Data Type Da teti me types DATE, TIME, SECONDDATE, TIMESTAMP Numeri c types TINYINT, SMALLINT, INTEGER, BIGINT, SMALLDECIMAL, DECIMAL, REAL, DOUBLE Cha ra cter s tri ng types VARCHAR, NVARCHAR, ALPHANUM, SHORTTEXT Bi na ry types VARBINARY La rge Object types BLOB, CLOB, NCLOB, TEXTTable 2: Classification of data typesDatetime Types DATE The DATE data type consists of year, month, and day information to represent a date value. The default format for the DATE data type is YYYY-MM-DD. YYYY represents the year, MM represents the month, and DD represents the day. The range of date value is 0001-01-01 through 9999-12-31. TIME The TIME data type consists of hour, minute, and second to represent a time value. The default format for the TIME data type is HH24:MI:SS. HH24 represents the hour from 0 to 24, MI represents the minute from 0 to 59, SS represents the second from 0 to 59. SECONDDATE The SECONDDATE data type consists of year, month, day, hour, minute and second information to represent a date with time value. The default format for the SECONDDATE data type is YYYY-MM-DD HH24:MI:SS. YYYY represents the year, MM represents the month, DD represents the day, HH24 represents hour, MI represents minute, and SS represents seconds. The range of date value is 0001- 01-01 00:00:01 through 9999-12-31 24:00:00. TIMESTAMP The TIMESTAMP data type consists of date and time information. Its default format is YYYY-MM-DD HH24:MI:SS.FF7. FFn represents the fractional seconds where n indicates the number of digits in fractional part. . The range of the timestamp value is 0001-01-01 00:00:00.0000000 through 9999-12- 31 23:59:59.9999999.For details on supported formats for datetime types, refer to Table 4, Table 5, Table 6 and Table 7 below.Date FormatsThe 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.13 2012-05-09
  14. 14. SAP HANA Database - SQL Reference Manual Format Description Examples YYYY-MM-DD Defa ul t forma t INSERT INTO TBL VALUES (1957-06-13); YYYY from 0001 to 9999, MM from 1 to 12, DD from 1 to 31. If yea r ha s l es s tha n four di gi ts , month ha s l es s tha n two di gi ts , or INSERT INTO TBL VALUES (1957-06-13); YYYY/MM/DD da y ha s l es s tha n two di gi ts , then va l ues INSERT INTO TBL VALUES (1957/06/13); YYYY/MM-DD wi l l be pa dded by one or more zeros . For INSERT INTO TBL VALUES (1957/06-13); YYYY-MM/DD exa mpl e, a two di gi t yea r 45 wi l l be s a ved INSERT INTO TBL VALUES (1957-06/13); a s yea r 0045, a one di gi t month 9 wi l l be s a ved a s 09, a nd a one di gi t da y 2 wi l l be s a ved a s 02. YYYYMMDD ABAP Da ta Type, DATS forma t. INSERT INTO TBL VALUES (19570613); INSERT INTO TBL VALUES (TO_DATE(2040- Ja n-10, YYYY-MON-DD)); MON Abbrevi a ted na me of month. (JAN. ~ DEC.) INSERT INTO TBL VALUES (TO_DATE(Ja n- 10, MON-DD)); INSERT INTO TBL VALUES (TO_DATE(2040- Ja nua ry-10, YYYY-MONTH-DD)); MONTH Na me of month. (JANUARY - DECEMBER). INSERT INTO TBL VALUES (TO_DATE(Ja nua ry-10, MONTH-DD)); INSERT INTO TBL VALUES (TO_DATE(2040-I- 10, YYYY-RM-DD)); RM Roma n numera l month (I-XII; JAN = I). INSERT INTO TBL VALUES (TO_DATE(I-10, RM-DD)); INSERT INTO TBL VALUES (TO_DATE(204, DDD)); DDD Da y of yea r (1-366). INSERT INTO TBL VALUES (TO_DATE(2001- 204,YYYY-DDD));Table 4: Supported formats for DateTime Formats Format Description Examples HH24:MI:SS Defa ul t forma t HH from 0 to 23. MI from 0 to 59. SS from 0 to 59. FFF from 0 to 999. If one di gi t hour, mi nute, s econd i s s peci fi ed, then 0 wi l l be i ns erted i nto INSERT INTO TBL VALUES (23:59:59); HH:MI[:SS][AM|PM] the va l ue. For exa mpl e, 9:9:9 wi l l be INSERT INTO TBL VALUES (3:47:39 AM); HH12:MI[:SS][AM|PM] s a ved a s 09:09:09. INSERT INTO TBL VALUES (9:9:9 AM); HH24:MI[:SS] HH12 i ndi ca tes 12 hour cl ock a nd HH24 INSERT INTO TBL VALUES i ndi ca tes 24 hour cl ock. (TO_TIME(11:59:59,HH12:MI:SS); AM or PM ca n be s peci fi ed a s a s uffi x to i ndi ca te the ti me va l ue i s before or a fter noon. INSERT INTO TBL VALUES (TO_TIME(12345, SSSSS Seconds pa s t mi dni ght (0-86399). SSSSS));Table 5: Supported formats for TimeTimestamp Formats Format Description Examples YYYY-MM-DD Defa ul t forma t HH24:MI:SS.FF7 Fra cti ona l s econds ha s the ra nge 1 to 7 a fter the FF pa ra meter to s peci fy the INSERT INTO TBL VALUES number of di gi ts i n the fra cti ona l s econd FF [1..7] (TO_TIMESTAMP(2011-05-11 porti on of the da te ti me va l ue returned. If 12:59.999,YYYY-MM-DD HH:SS.FF3)); a di gi t i s not s peci fi ed, the defa ul t va l ue i s us ed.Table 6: Supported formats for TimestampAdditional Formats14 2012-05-09
  15. 15. SAP HANA Database - SQL Reference Manual Format Description Example D Da y of week (1-7). TO_CHAR(CURRENT_TIMESTAMP,D) DAY Na me of da y (MONDAY - SUNDAY). TO_CHAR(CURRENT_TIMESTAMP,DAY) DY Abbrevi a ted na me of da y (MON - SUN). TO_CHAR(CURRENT_TIMESTAMP,DY) MON Abbrevi a ted month na me (JAN - DEC) TO_CHAR(CURRENT_TIMESTAMP,MON) MONTH Ful l month na me (JANUARY - DECEMBER) TO_CHAR(CURRENT_TIMESTAMP,MONTH) Roma n numera l month (I - XII; I i s for RM TO_CHAR(CURRENT_TIMESTAMP,RM) Ja nua ry) Q Qua rter of yea r (1, 2, 3, 4) TO_CHAR(CURRENT_TIMESTAMP,Q) W Week of month (1-5). TO_CHAR(CURRENT_TIMESTAMP,W) WW Week of yea r (1-53). TO_CHAR(CURRENT_TIMESTAMP,WW)Table 7: Additional formats for DatetimeSupported Functions for Date/Time types ADD_DAYS ADD_MONTHS ADD_SECONDS ADD_YEARS COALESCE CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP CURRENT_UTCDATE CURRENT_UTCTIME CURRENT_UTCTIMESTAMP DAYNAME DAYOFMONTH DAYOFYEAR DAYS_BETWEEN EXTRACT GREATEST GREATEST HOUR IFNULL ISOWEEK LAST_DAY LEAST LOCALTOUTC MINUTE MONTH MONTHNAME NEXT_DAY NULLIF QUARTER SECOND SECONDS_BETWEEN TO_CHAR TO_DATE TO_DATS TO_NCHAR TO_TIME TO_TIMESTAMP UTCTOLOCAL WEEK WEEKDAY YEARNumeric Types TINYINT The TINYINT data type stores an 8-bit unsigned integer. The minimum value is 0 and the maximum value is 255 for TINYINT. SMALLINT The SMALLINT data type stores a 16-bit signed integer. The minimum value is -32,768 and the maximum value is 32,767 for SMALLINT.15 2012-05-09
  16. 16. SAP HANA Database - SQL Reference Manual INTEGER The INTEGER data type stores a 32-bit signed integer. The minimum value is -2,147,483,648 and the maximum value is 2,147,483,647 for INTEGER. BIGINT The BIGINT data type stores a 64-bit signed integer. The minimum value is - 9,223,372,036,854,775,808 and the maximum value is 9,223,372,036,854,775,807 for BIGINT. DECIMAL(precision, scale) or DEC(p,s) The DECIMAL(p, s) data type specifies a fixed-point decimal number with precision p and scale s. The precision is the total number of significant digits and can range from 1 to 34. The scale is the number of digits from the decimal point to the least significant digit and can range from -6,111 to 6,176, which means scale specifies the range of the exponent in the decimal number from 10-6111 to 106176. If scale is not specified, it defaults to 0. Scale is positive when the number has significant digits to the right of the decimal point and negative when the number has significant digits to the left of the decimal point. Examples: 0.0000001234 (1234 x 10-10) has the precision 4 and the scale 10. 1.0000001234 (10000001234 x 10-10) has the precision 11 and scale 10. 1234000000 (1234x106) has the precision 4 and scale -6. When precision and scale are not specified, DECIMAL becomes a floating-point decimal number. In this case, precision and scale can vary within the range described above, 1~34 for precision and - 6,111~6,176 for scale depending on the stored value. SMALLDECIMAL The SMALLDECIMAL is a floating-point decimal number. The precision and scale can vary within the range, 1~16 for precision and -369~368 for scale depending on the stored value. SMALLDECIMAL is supported only on column store. DECIMAL and SMALLDECIMAL are floating-point types. For instance, a decimal column can store any of 3.14, 3.1415, 3.141592 whilst maintaining their precision. DECIMAL(p, s) is the SQL standard notation for fixed-point decimal. For instance, 3.14, 3.1415, 3.141592 are stored in a decimal(5, 4) column as 3.1400, 3.1415, 3.1416, respectively keeping the specified precision(5) and scale(4). REAL The REAL data type specifies a single-precision 32-bit floating-point number. DOUBLE The DOUBLE data type specifies a single-precision 64-bit floating-point number. The minimum value is -1.79769 x 10308 and the maximum value is 1.79769x10308 . The smallest positive DOUBLE value is 2.2207x10-308 and the largest negative DOUBLE value is -2.2207x10-308. FLOAT(n) The FLOAT(n) data type specifies a 32-bit or 64-bit real number, where n specifies the number of significant bits and can range between 1 and 53. When you use the FLOAT(n) data type, if n is smaller than 25, it becomes a 32-bit REAL data type. If n is greater than or equal to 25, it then becomes a 64-bit DOUBLE data type. If n is not declared, it becomes a 64-bit double data type by default.Character String TypesThe 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 the maximum length and is an integer between 1 and 5000. NVARCHAR The NVARCHAR(n) data type specifies a variable-length Unicode character set string, where n indicates the maximum length and is an integer between 1 and 5000. ALPHANUM The ALPHANUM(n) data type specifies a variable-length character string which contains alpha- numeric characters, where n indicates the maximum length and is an integer between 1 and 127. SHORTTEXT The SHORTTEXT(n) data type specifies veriable-length character string which supports textsearch-16 2012-05-09
  17. 17. SAP HANA Database - SQL Reference Manual features and stringsearch-features. This is not a standalone sql-type. Selecting a SHORTTEXT(n)- column yields a column of type NVARCHAR(n). <shorttext_type> ::= SHORTTEXT ( int_const ) <elem_list_shorttext> <elem_list_shorttext> ::= <elem_shorttext> [... , <elem_shorttext>] <elem_shorttext> ::= <fulltext_elem> | SYNC[HRONOUS]Binary TypesBinary 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) TypesLOB (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.17 2012-05-09
  18. 18. SAP HANA Database - SQL Reference ManualMapping 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) Approxi ma te Types REAL CS_FLOAT DOUBLE CS_DOUBLE FLOAT CS_DOUBLE FLOAT(p) CS_FLOAT, CS_DOUBLE Deci ma l Types DECIMAL CS_DECIMAL_FLOAT DECIMAL(p,s ) CS_FIXED(p-s ,s ) SMALLDECIMAL CS_SDFLOAT Cha ra cter 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 Bi na ry Types BLOB CS_RAW VARBINARY CS_RAW Da te/Ti me Types DATE CS_DAYDATE,CS_DATE TIME CS_SECONDTIME,CS_TIME TIMESTAMP CS_LONGDATE,CS_DATE,CS_SECONDDATE SECONDDATE CS_SECONDDATEData Type ConversionThis section describes the data type conversion allowed in SAP HANA Database. Explicit type conversion The type of an expression result, for example a field reference, a function on fields, or literals can be converted using the following functions: CAST, TO_ALPHANUM, TO_BIGINT, TO_VARBINARY, TO_BLOB, TO_CLOB, TO_DATE, TO_DATS, TO_DECIMAL, TO_DOUBLE, TO_INTEGER, TO_INT, TO_NCLOB, TO_NVARCHAR, TO_REAL, TO_SECONDDATE, TO_SMALLINT, TO_TINYINT, TO_TIME, TO_TIMESTAMP, TO_VARCHAR. Implicit type conversion When a given set of operand/argument types does not match what an operator/function expects, a type conversion is carried out by the SAP HANA Database. This conversion only occurs if a relevant conversion is available and if it makes the operation/function executable. For instance, a comparison of BIGINT and VARCHAR is performed by implicitly converting VARCHAR to BIGINT. The entire explicit conversions can be used for implicit conversion except for the TIME and TIMESTAMP data types. TIME and TIMESTAMP can be converted to each other using TO_TIME(TIMESTAMP) and TO_TIMESTAMP(TIME). Examples 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 beca us e there i s no convers i on a va i l a bl e between DATE a nd TIME Table 8: Implicit Type conversion ExamplesIn 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.18 2012-05-09
  19. 19. SAP HANA Database - SQL Reference Manual smalldecimal decimal(p,s) Target/ nvarchar smallint decimal varchar double integer tinyint Source bigint real tinyint - OK OK OK OK OK OK OK OK OK OK smallint CHK - OK OK OK OK OK OK OK OK OK 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 9a: Data type conversion table Target/ time date seconddate timestamp varchar nvarchar Source time - - - - OK OK date - - OK OK OK OK seconddate ti me da te - ti mes ta mp OK OK timestamp ti me da te s econdda te - OK OK varchar CHK CHK CHK CHK - OK nvarchar CHK CHK CHK CHK CHK -Table 9b: Data type conversion table Target/ varbinary alphanum varchar nvarchar Source varbinary - - - - alphanum - - OK OK varchar OK OK - OK nvarchar OK OK CHK -Table 9c: Data type conversion tableData Type PrecedenceThis 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.19 2012-05-09
  20. 20. SAP HANA Database - SQL Reference Manual Highest TIMESTAMP SECONDDATE DATE TIME DOUBLE REAL DECIMAL SMALLDECIMAL BIGINT INTEGER SMALLINT TINYINT NCLOB NVARCHAR CLOB VARCHAR BLOB Lowest VARBINARYTyped ConstantA constant is a symbol that represents a specific fixed data value. Character string contant A character string constant is enclosed in single quotation marks. Brian 100 Unicode string has a similar format to character string but is preceded by an N identifier (N stands for National Language in the SQL-92 standard). The N prefix must be uppercase. Nabc SELECT Brian "character string 1", 100 "character string 2", Nabc "unicode st ring" FROM DUMMY; character string 1, character string 2, unicode string Brian, 100, abc Number constant A number constant is represented by a string of numbers that are not enclosed in quotation marks. Numbers may contain a decimal point or scientific notation. 123 123.4 1.234e2 A hexadecimal number constant is a string of hexadecimal numbers and has the prefix 0x. 0x0abc SELECT 123 "integer", 123.4 "decimal1", 1.234e2 "decimal2", 0x0abc "hexadecimal" FR OM DUMMY; integer, decimal1, decimal2, hexadecimal 123, 123.4, 123.4, 2748 Binary string constant A binary string has the prefix X and is a string of hexadecimal numbers that are enclosed in quotation marks. X00abcd xdcba00 SELECT X00abcd "binary string 1", xdcba00 "binary string 2" FROM DUMMY; binary string 1, binary string 220 2012-05-09
  21. 21. SAP HANA Database - SQL Reference Manual 00ABCD, DCBA00 Date/Time/Timestamp constant Date, Time and Timestamp each have the following prefixes. date2010-01-01 time11:00:00.001 timestamp2011-12-31 23:59:59 SELECT date2010-01-01 "date", time11:00:00.001 "time", timestamp2011-12-31 23: 59:59 "timestamp" FROM DUMMY; date, time, timestamp 2010-01-01, 11:00:00, 2011-12-31 23:59:59.021 2012-05-09
  22. 22. SAP HANA Database - SQL Reference ManualPredicatesA 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 PredicatesTwo values are compared using comparison predicates and the comparison returns true, false, or unknown.Syntax: <comparison_predicate> ::= <expression> { = | != | <> | > | < | >= | <= } [ ANY | SOME| ALL ] { <expression_li st> | <subquery> } <expression_list> ::= <expression>, ...Expressions can be a simple expression such as a character, date, or number. An expression can also be 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 PredicateA 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 PredicateA 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 PredicateReturns 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 PredicateThe 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 Predicate22 2012-05-09
  23. 23. SAP HANA Database - SQL Reference ManualWhen 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] NULLCONTAINS PredicateThe CONTAINS predicate is used to search for text-matches to a search string in subqueries.Syntax: <contains_function> ::= CONTAINS ( <contains_columns> , <search_string>) | CONTAINS ( <contains_columns> , <search_string> , <se arch_specifier> ) <contains_columns> ::= * | <column_name> | ( <columnlist> ) <search_string> ::= <string_const> <search_specifier> ::= <search_type> <opt_search_specifier2_list> | <search_specifier2_list> <opt_search_specifier2_list> ::= empty | <search_specifier2_list> <search_type> ::= <exact_search> | <fuzzy_search> | <linguistic_search> <search_specifier2_list> ::= <search_specifier2> | <search_specifier2_list> , <search_specifier2> <search_specifier2> := <weights> | <language> <exact_search> ::= EXACT <fuzzy_search> ::= FUZZY | FUZZY ( <float_const> ) | FUZZY ( <float_const> , <additional_params> ) <linguistic_search> ::= LINGUISTIC <weights> ::= WEIGHT ( <float_const_list> ) <language> :: LANGUAGE ( <string_const> ) <additional_params> ::= <string_const>search_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 defaultEXACTEXACT returns true for those records where exact matches of the searchterms are found in the search-attributesFUZZYFUZZY 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-viewsWEIGHTIf a weights list is specified, it must be the same size as the number of (expanded) columns in<contains_columns>LANGUAGE23 2012-05-09
  24. 24. SAP HANA Database - SQL Reference ManualLANGUAGE 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> listThe 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 searchFuzzy search select * from T where contains(column1, catz, FUZZY(0.8))Linguistic search: select * from T where contains(column1, catz, LINGUISTIC)Freestyle search:The freestyle-search is a search mulitple columns. select * from T where CONTAINS( (column1,column2,column3), cats OR dogz, FUZZY(0. 7)) select * from T where CONTAINS( (column1,column2,column3), cats OR dogz, FUZZY(0. 7))24 2012-05-09
  25. 25. SAP HANA Database - SQL Reference ManualOperatorsYou can perform arithmetic operations in expressions by using operators. Operators can be used forcalculation, value comparison or to assign values.Unary and Binary Operators Operator Operation Format Description una ry pl us opera tor(+) una ry nega ti on A una ry opera tor a ppl i es to one opera nd or a Una ry opera tor opera nd opera tor(-) s i ngl e va l ue expres s i on. l ogi ca l nega ti on(NOT) mul ti pl i ca ti ve opera tors ( *, / ) a ddi ti ve opera tors ( +,- ) Bi na ry A bi na ry opera tor a ppl i es to two opera nds opera nd1 opera tor Bi na ry compa ri s on or two va l ue expres s i ons . opera nd2 opera tors ( =,!=,<,>,<=,>=) l ogi ca l opera tors ( AND, OR )Table 10. Unary and binary operatorsOperator PrecedenceAn 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. Precedence Operator Operation Hi ghes t () pa renthes es +, - una ry pos i ti ve a nd nega ti ve opera ti on *, / mul ti pl i ca ti on, di vi s i on +, - a ddi ti on, s ubtra cti on || conca tena ti on =, !=, <, >, <=, >=, IS NULL, LIKE, BETWEEN compa rs i on NOT l ogi ca l nega ti on AND conjuncti on Lowes t OR di s juncti onTable 11. SQL operator precedenceArithmetic OperatorsYou use arithmetic operators to perform mathematical operations such as adding, subtracting, multiplying,dividing and negation of numeric values.25 2012-05-09
  26. 26. SAP HANA Database - SQL Reference Manual Operator Description -<expres s i on> Nega ti on. If the expres s i on i s the NULL va l ue, the res ul t i s NULL. <expres s i on> + Addi ti on. If ei ther expres s i on i s the NULL va l ue, the res ul t i s NULL. <expres s i on> <expres s i on> - Subtra cti on. If ei ther expres s i on i s the NULL va l ue, the res ul t i s NULL. <expres s i on> <expres s i on> * Mul ti pl i ca ti on. If ei ther expres s i on i s NULL, the res ul t i s NULL. <expres s i on> <expres s i on> / Di vi s i on. If ei ther expres s i on i s NULL, or i f the s econd expres s i on i s 0, a n error i s <expres s i on> returned.Table 12. Arithmetic operatorsString OperatorsA concatenation operator combines two items such as strings, expressions or constants into one. Operator Description Stri ng conca tena ti on (two verti ca l ba rs ). <expres s i on> || <expres s i on> If ei ther s tri ng i s NULL, i t returns NULL.Table 13. Concatenation operatorsFor 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 OperatorsSyntax: <comparison_operation> ::= <expression1> <comparison_operator> <expression2> Operator Description Example = Equa l to SELECT * FROM s tudents WHERE i d = 25; > Grea ter tha n SELECT * FROM s tudents WHERE i d > 25; < Les s tha n SELECT * FROM s tudents WHERE i d < 25; >= Grea ter tha n or equa l to SELECT * FROM s tudents WHERE i d >= 25; <= Les s tha n or equa l to SELECT * FROM s tudents WHERE i d <= 25; SELECT * FROM s tudents WHERE i d != 25; !=, <> Not equa l SELECT * FROM s tudents WHERE i d <> 25;Table 14. Comparison operatorsLogical OperatorsSearch conditions can be combined using AND or OR operators. You can also negate them using the NOToperator. Operator Syntax Description WHERE condi ti on1 When us i ng AND, the combi ned condi ti on i s TRUE i f both condi ti ons a re TRUE, AND AND FALSE i f ei ther condi ti on i s FALSE, a nd UNKNOWN otherwi s e. condi ti on2 WHERE condi ti on1 When us i ng OR, the combi ned condi ti on i s TRUE i f ei ther condi ti on i s TRUE, OR OR FALSE i f both condi ti ons a re FALSE, a nd UNKNOWN otherwi s e. condi ti on2 The NOT opera tor i s pl a ced before a condi ti on to nega te the condi ti on. The NOT WHERE NOT NOT condi ti on i s TRUE i f condi ti on i s FALSE, FALSE i f condi ti on i s TRUE, a nd UNKNOWN condi ti on i f condi ti on i s UNKNOWN.Table 15. Logical operatorsSet OperatorsThe operators described in this section perform set operations on the results of two or more queries.26 2012-05-09
  27. 27. SAP HANA Database - SQL Reference Manual Operator Returned Value UNION Combi nes the res ul ts of two or more s el ect s ta tements or query expres s i ons UNION Combi nes the res ul ts of two or more s el ect s ta tements or query expres s i ons , i ncl udi ng a l l ALL dupl i ca te rows . Combi nes the res ul ts of two or more s el ect s ta tements or query expres s i ons , a nd returns a l l INTERSECT common rows . EXCEPT Ta kes output from the fi rs t query a nd then removes rows s el ected by the s econd query.Table 16. Set operators27 2012-05-09
  28. 28. SAP HANA Database - SQL Reference ManualExpressionsAn 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 ExpressionsA 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 ExpressionsSQL built-in functions can be used as an expression.Syntax: <function_expression> ::= <function_name> ( <expression>, ... )Aggregate ExpressionsAn 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 Aggregate Description name Counts the number of rows returned by a query. COUNT(*) returns the number of rows , rega rdl es s COUNT of the va l ue of thos e rows a nd i ncl udi ng dupl i ca te va l ues . COUNT(<expres s i on>) returns the number of non-NULL va l ues for tha t expres s i on returned by the query. MIN Returns the mi ni mum va l ue of expres s i on. MAX Returns the ma xi mum va l ue of expres s i on. SUM Returns the s um of expres s i on. AVG Returns the a ri thmeti ca l mea n of expres s i on. STDDEV Returns the s ta nda rd devi a ti on of gi ven expres s i on a s the s qua re root of VARIANCE functi on. VAR Returns the va ri a nce of expres s i on a s the s qua re of s ta nda rd devi a ti on.Subqueries in Expressions28 2012-05-09
  29. 29. SAP HANA Database - SQL Reference ManualA 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;29 2012-05-09
  30. 30. SAP HANA Database - SQL Reference ManualSQL FunctionsIntroductionThis chapter describes SQL Functions that are provided by SAP HANA Database. Data Type Conversion Functions DateTime Functions Number Functions String Functions Miscellaneous FunctionsData Type Conversion FunctionsData type conversion functions are used to convert arguments from one data type to another, or to testwhether a conversion is possible.CASTSyntax CAST (expression AS data_type)Syntax Elementsexpression - 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 | TIMESTAMPDescriptionReturns the value of an expression converted to a supplied data type.Example SELECT CAST (7 AS VARCHAR) "cast" FROM DUMMY; cast 7TO_ALPHANUMSyntax TO_ALPHANUM (value)DescriptionConverts a given value to an ALPHANUM data type.Example SELECT TO_ALPHANUM (10) "to alphanum" FROM DUMMY; to alphanum 10TO_BIGINTSyntax TO_BIGINT (value)DescriptionConverts a value to a BIGINT data type.30 2012-05-09
  31. 31. SAP HANA Database - SQL Reference ManualExample SELECT TO_BIGINT (10) "to bigint" FROM DUMMY; to bigint 10TO_BINARYSyntax TO_BINARY (value)DescriptionConverts a value to a BINARY data type.Example SELECT TO_BINARY (abc) "to binary" FROM DUMMY; to binary 616263TO_BLOBSyntax TO_BLOB (value)DescriptionConverts 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 abcdeTO_CHARSyntax TO_CHAR (value [, format])DescriptionConverts 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 FormatsExample SELECT TO_CHAR (TO_DATE(2009-12-31), YYYY/MM/DD) "to char" FROM DUMMY; to char 2009/12/31TO_CLOBSyntax TO_CLOB (value)Description31 2012-05-09
  32. 32. SAP HANA Database - SQL Reference ManualConverts a value to a CLOB data type.Example SELECT TO_CLOB (TO_CLOB converts the value to a CLOB data type) "to clob" FROM DU MMY; to clob TO_CLOB converts the value to a CLOB data typeTO_DATESyntax TO_DATE (d [, format])DescriptionConverts 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-12TO_DATSSyntax TO_DATS (d)DescriptionConverts 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 20100112TO_DECIMALSyntax TO_DECIMAL (value [, precision, scale])DescriptionConverts 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.32 2012-05-09
  33. 33. SAP HANA Database - SQL Reference ManualExample SELECT TO_DECIMAL(7654321.888888, 10, 3) "to decimal" FROM DUMMY to decimal 7654321.889TO_DOUBLESyntax TO_DOUBLE (value)DescriptionConverts a value to a DOUBLE (double precision) data type.Example SELECT 3*TO_DOUBLE (15.12) "to double" FROM DUMMY; to double 45.36TO_INTSyntax TO_INT (value)DescriptionConverts the value to an INTEGER data type.Example SELECT TO_INT(10) "to int" FROM DUMMY; to int 10TO_INTEGERSyntax TO_INTEGER (value)DescriptionConverts the value to an INTEGER data type.Example SELECT TO_INTEGER (10) "to int" FROM DUMMY; to int 10TO_NCHARSyntax TO_NCHAR (value [, format])DescriptionConverts the value to a NCHAR unicode character data type. If the format specifier is omitted, the conversion33 2012-05-09
  34. 34. SAP HANA Database - SQL Reference Manualis 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/31TO_NCLOBSyntax TO_NCLOB (value)DescriptionConverts a value to a NCLOB data type.Example SELECT TO_NCLOB (TO_NCLOB converts the value to a NCLOB data type) "to nclob" FRO M DUMMY; to nclob TO_NCLOB converts the value to a NCLOB data typeTO_NVARCHARSyntax TO_NVARCHAR (value [,format])DescriptionConverts 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-31TO_REALSyntax TO_REAL (value)DescriptionConverts a value to a REAL (single precision) data type.Example SELECT 3*TO_REAL (15.12) "to real" FROM DUMMY; to real 45.36000061035156TO_SECONDDATESyntax TO_SECONDDATE (d [, format])34 2012-05-09
  35. 35. SAP HANA Database - SQL Reference ManualDescriptionConverts 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 seconddat e" FROM DUMMY; to seconddate 2010-01-11 13:30:00.0TO_SMALLDECIMALSyntax TO_SMALLDECIMAL (value)DescriptionConverts the value to a SMALLDECIMAL data type.Example SELECT TO_SMALLDECIMAL(7654321.89) "to smalldecimal" FROM DUMMY; to smalldecimal 7654321.89TO_SMALLINTSyntax TO_SMALLINT (value)DescriptionConverts the value to a SMALLINT data type.Example SELECT TO_SMALLINT (10) "to smallint" FROM DUMMY; to smallint 10TO_TIMESyntax TO_TIME (t [, format])DescriptionConverts 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:00TO_TIMESTAMP35 2012-05-09
  36. 36. SAP HANA Database - SQL Reference ManualSyntax TO_TIMESTAMP (d [, format])DescriptionConverts 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.0TO_TINYINTSyntax TO_TINYINT (value)DescriptionConverts the value to a TINYINT data type.Example SELECT TO_TINYINT (10) "to tinyint" FROM DUMMY; to tinyint 10TO_VARCHARSyntax TO_VARCHAR (value [, format])DescriptionConverts 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/31DateTime FunctionsADD_DAYSSyntax ADD_DAYS (d, n)DescriptionComputes the date d plus n days.Example36 2012-05-09
  37. 37. SAP HANA Database - SQL Reference Manual SELECT ADD_DAYS (TO_DATE (2009-12-05, YYYY-MM-DD), 30) "add days" FROM DUMMY; add days 2010-01-04ADD_MONTHSSyntax ADD_MONTHS (d, n)DescriptionComputes 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-05ADD_SECONDSSyntax ADD_SECONDS (t, n)DescriptionComputes 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.0ADD_YEARSSyntax ADD_YEARS (d, n)DescriptionComputes 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-05CURRENT_DATESyntax CURRENT_DATEDescriptionReturns the current local system date.37 2012-05-09
  38. 38. SAP HANA Database - SQL Reference ManualExample SELECT CURRENT_DATE "current date" FROM DUMMY; current date 2010-01-11CURRENT_TIMESyntax CURRENT_TIMEDescriptionReturns the current local system time.Example SELECT CURRENT_TIME "current time" FROM DUMMY; current time 17:37:37CURRENT_TIMESTAMPSyntax CURRENT_TIMESTAMPDescriptionReturns the current local system timestamp information.Example SELECT CURRENT_TIMESTAMP "current timestamp" FROM DUMMY; current timestamp 2010-01-11 17:38:48.802CURRENT_UTCDATESyntax CURRENT_UTCDATEDescriptionReturns 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-11CURRENT_UTCTIMESyntax CURRENT_UTCTIMEDescription38 2012-05-09
  39. 39. SAP HANA Database - SQL Reference ManualReturns the current UTC time.Example SELECT CURRENT_UTCTIME "Coordinated Universal Time" FROM DUMMY; Coordinated Universal Time 08:41:19CURRENT_UTCTIMESTAMPSyntax CURRENT_UTCTIMESTAMPDescriptionReturns the current UTC timestamp.Example SELECT CURRENT_UTCTIMESTAMP "Coordinated Universal Timestamp" FROM DUMMY; Coordinated Universal Timestamp 2010-01-11 08:41:42.484DAYNAMESyntax DAYNAME (d)DescriptionReturns the weekday in English for date d.Example SELECT DAYNAME (2011-05-30) "dayname" FROM DUMMY; dayname MONDAYDAYOFMONTHSyntax DAYOFMONTH (d)DescriptionReturns an integer the day of the month for date d.Example SELECT DAYOFMONTH (2011-05-30) "dayofmonth" FROM DUMMY; dayofmonth 30DAYOFYEARSyntax DAYOFYEAR (d)39 2012-05-09
  40. 40. SAP HANA Database - SQL Reference ManualDescriptionReturns an integer representation of the day of the year for date d.Example SELECT DAYOFYEAR (2011-05-30) "dayofyear" FROM DUMMY; dayofyear 150DAYS_BETWEENSyntax DAYS_BETWEEN (d1, d2)DescriptionComputes the number of days between d1 and d2.Example SELECT DAYS_BETWEEN (TO_DATE (2009-12-05, YYYY-MM-DD), TO_DATE(2010-01-05, Y YYY-MM-DD)) "days between" FROM DUMMY; days between 31EXTRACTSyntax EXTRACT ({YEAR | MONTH | DAY | HOUR | MINUTE | SECOND} FROM d)DescriptionFinds and returns the value of a specified datetime field from date d.Example SELECT EXTRACT (YEAR FROM TO_DATE (2010-01-04, YYYY-MM-DD)) "extract" FROM DUM MY; extract 2010HOURSyntax HOUR (t)DescriptionReturns an integer representation of the hour for time t.Example SELECT HOUR (12:34:56) "hour" FROM DUMMY; hour 12ISOWEEKSyntax40 2012-05-09
  41. 41. SAP HANA Database - SQL Reference Manual ISOWEEK (d)DescriptionReturns the ISO year and week numbers of date d. The week number is prefixed by the letter W.Please also see WEEKExample SELECT ISOWEEK (TO_DATE(2011-05-30, YYYY-MM-DD)) "isoweek" FROM DUMMY; isoweek 2011-W22LAST_DAYSyntax LAST_DAY (d)DescriptionReturns 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-31LOCALTOUTCSyntax LOCALTOUTC (t, timezone)DescriptionConvert the local time t from a timezone to the UTC(GMT) timeExample 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.0MINUTESyntax MINUTE (t)DescriptionReturns an integer representation of the minute for time t.Example SELECT MINUTE (12:34:56) "minute" FROM DUMMY; minute 3441 2012-05-09
  42. 42. SAP HANA Database - SQL Reference ManualMONTHSyntax MONTH(d)DescriptionReturns the number of the month from date d.Example SELECT MONTH (2011-05-30) "month" FROM DUMMY; month 5MONTHNAMESyntax MONTHNAME(d)DescriptionReturns the name of the month in English for date d.Example SELECT MONTHNAME (2011-05-30) "monthname" FROM DUMMY; monthname MAYNEXT_DAYSyntax NEXT_DAY (d)DescriptionReturns 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-01NOWSyntax NOW ()DescriptionReturns the current timestamp.Example SELECT NOW () "now" FROM DUMMY; now42 2012-05-09
  43. 43. SAP HANA Database - SQL Reference Manual 2010-01-01 16:34:19.894QUARTERSyntax QUARTER (d, [, start_month ])DescriptionReturns 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-Q4SECONDSyntax SECOND (t)DescriptionReturns an integer representation of the second for time t.Example SELECT SECOND (12:34:56) "second" FROM DUMMY; second 56SECONDS_BETWEENSyntax SECONDS_BETWEEN (d1, d2)DescriptionComputes 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 2678400UTCTOLOCALSyntax UTCTOLOCAL (t, timezone)DescriptionConvert the UTC(GMT) time t to the local time in a timezoneExample43 2012-05-09

×