0% found this document useful (0 votes)
26 views2,016 pages

SQL Reference en

Uploaded by

liazunusova
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views2,016 pages

SQL Reference en

Uploaded by

liazunusova
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2016

SQL Anywhere Server

Document Version: 17 – 2016-05-11

SQL Anywhere - SQL Reference


Content

1 SQL Anywhere Server - SQL Reference. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4


1.1 SQL language elements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Keywords. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Identifiers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Constants. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14
Expressions in SQL statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Search conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55
Special values. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
%TYPE and %ROWTYPE attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .112
SQL variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Comments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Named parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
1.2 SQL data types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
Character data types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Numeric data types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Money data types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Bit array data types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Date and time data types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Binary data types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
ROW and ARRAY composite data types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
TABLE REF data type. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .182
Spatial data types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Domains. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Data type comparisons. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
Data type conversions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
1.3 SQL functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
Function types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
1.4 SQL statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
Common elements in SQL syntax. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
Syntax conventions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 613
Statement applicability indicators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .615
Alphabetical list of SQL statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .615
1.5 Tables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1417

SQL Anywhere - SQL Reference


2 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content
System tables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1417
1.6 System procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1434
Viewing details about system procedures and functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1435
Web services system procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1435
Roles and privileges system procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1436
MAPI and SMTP system procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1436
Directory and file system procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1439
Secured feature system procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1440
Adaptive Server Enterprise system and catalog procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . 1440
Alphabetical list of system procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1442
1.7 Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1791
System views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1792
Consolidated views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1872
Compatibility views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1898
Views for Transact-SQL compatibility. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1910
1.8 Printing, reproducing, and redistributing this documentation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1911

SQL Anywhere - SQL Reference


Content © 2016 SAP SE or an SAP affiliate company. All rights reserved. 3
1 SQL Anywhere Server - SQL Reference

This book describes the system procedures and the catalog (system tables and views) included in SQL Anywhere.
It also provides an explanation of the SQL Anywhere implementation of the SQL language (search conditions,
syntax, data types, and functions).

In this section:

SQL language elements [page 4]


There are several SQL language elements you can use.

SQL data types [page 126]


There are many SQL data types supported by the software.

SQL functions [page 200]


Functions are used to return information from the database. They can be called anywhere an expression is
allowed.

SQL statements [page 611]


There are several conventions used in the SQL statement documentation.

Tables [page 1417]


There are several types of tables supported by the software.

System procedures [page 1434]


There are hundreds of system in the software, many of which are for internal use only. The documentation
explains the system procedures that are for external use.

Views [page 1791]


There are several types of views supported by the software.

Printing, reproducing, and redistributing this documentation [page 1911]


You may use, print, reproduce, and distribute this documentation (in whole or in part) subject to the
following conditions:

1.1 SQL language elements

There are several SQL language elements you can use.

In this section:

Keywords [page 5]
Each SQL statement contains one or more keywords. SQL is case insensitive to keywords, but throughout
the documentation, keywords are indicated in uppercase.

Identifiers [page 6]
Identifiers are the names of objects in the database, such as user IDs, tables, and columns.

Strings [page 11]

SQL Anywhere - SQL Reference


4 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
A string is a sequence of characters up to 2 GB in size.

Constants [page 11]


Binary literals and string literals can be used as constants.

Operators [page 14]


There are several arithmetic, string, array, and bitwise operators.

Expressions in SQL statements [page 32]


An expression is a statement that can be evaluated to return values.

Search conditions [page 55]


A search condition is the criteria specified for a WHERE clause, a HAVING clause, a CHECK clause, an ON
phrase in a join, or an IF expression. A search condition is also called a predicate.

Special values [page 84]


Special values can be used in expressions, and as column defaults when creating tables.

%TYPE and %ROWTYPE attributes [page 112]


In addition to explicitly setting the data type for an object, you can also set the data type by specifying the
%TYPE and %ROWTYPE attributes.

SQL variables [page 120]


The supported variables can be grouped by scope: connection, database, and global.

Comments [page 123]


Comments are used to attach explanatory text to SQL statements or statement blocks. The database
server does not execute comments.

Named parameters [page 124]


Functions and procedures that are referenced from the CALL statement, the EXECUTE statement
(Transact-SQL), the FROM clause of a DML statement, and the TRIGGER EVENT statement support
positional parameters and named parameters. Named parameters support specifying any subset of the
available parameters in any order.

1.1.1 Keywords

Each SQL statement contains one or more keywords. SQL is case insensitive to keywords, but throughout the
documentation, keywords are indicated in uppercase.

For example, in the following statement, SELECT and FROM are keywords:

SELECT *
FROM Employees;

The following statements are equivalent to the one above:

Select *
From Employees;
select * from Employees;
sELECT * FRoM Employees;

Some keywords cannot be used as identifiers without surrounding them in double quotes, square brackets, or
back quotes (`...`). These are called reserved words. Other keywords, such as DBA, do not require quotation
marks, and are not reserved words.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 5
In this section:

Reserved words [page 6]


Some keywords in SQL are considered reserved words.

1.1.1.1 Reserved words

Some keywords in SQL are considered reserved words.

Reserved words are words that must be treated specially when used in SQL syntax. Many of the keywords that
appear in SQL statements are reserved words (for example, the word select. To use a reserved word in a SQL
statement as an identifier, enclose it in double quotes, square brackets or back quotes .For example, you use the
following syntax to retrieve the contents of a table named SELECT.

SELECT *
FROM "SELECT"

To obtain the list of reserved words, use the sa_reserved_words system procedure. For example:

SELECT * FROM sa_reserved_words() ORDER BY reserved_word;

Other notes regarding reserved words:

● SQL keywords are not case sensitive and the following words may appear in uppercase, lowercase, or any
combination of the two. All strings that differ only in capitalization from one of the following words are
reserved words.
● You can turn off keyword restrictions using the non_keywords option.
● The reserved_keywords option turns on individual keywords that are disabled by default.
● If you are using Embedded SQL, you can use the sql_needs_quotes database library function to determine
whether a string requires quotation marks. A string requires quotes if it is a reserved word or if it contains a
character not ordinarily allowed in an identifier.

Related Information

sa_reserved_words system procedure [page 1603]

1.1.2 Identifiers

Identifiers are the names of objects in the database, such as user IDs, tables, and columns.

Identifiers have a maximum length of 128 bytes and are composed from alphabetic characters and digits, as well
as the underscore character (_), at sign (@), number sign (#), and dollar sign ($). Leading digits are allowed but
the identifier must be quoted. Other special characters are allowed but the identifier must be quoted. The
database collation sequence dictates which characters are considered alphabetic or digit characters.

SQL Anywhere - SQL Reference


6 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
The following characters are not permitted in identifiers:

● Double quotes
● Control characters (characters with an ordinal value of less than 32, or the character value 127)
● Backslashes
● Square brackets
● Back quotes

Note
If you are reloading a database that is of an earlier version than 16.0, then remove any square brackets or back
quotes in identifiers; otherwise, the reload fails.

The following characters are not permitted in identifiers used as user or role names:

● Leading or trailing whitespace


● Leading single quote
● Semicolons

If the quoted_identifier database option is set to Off, then double quotes delimit SQL strings and cannot be used
to delimit identifiers. However, you can use square brackets or back quotes to delimit identifiers, regardless of the
setting of quoted_identifier. The default setting for the quoted_identifier option is Off for Open Client and jConnect
connections; otherwise, the default is On.

An indirect identifier can also be substituted for an identifier in a statement. Indirect identifiers allow you to
specify the name of a variable that stores an identifier, instead of specifying the identifier directly. However,
indirect identifiers are only supported for a selection of objects and there are restrictions on how they can be
used.

Quoting identifiers

If any of the following conditions are true, then always enclose an identifier in double quotes, square brackets, or
back quotes (`...`):

● The identifier contains leading, trailing, or embedded spaces.


● The first character of the identifier is not an alphabetic character, the underscore character (_), at sign (@),
number sign (#), or dollar sign ($). For example, the first character is a digit.
● The identifier contains characters other than the alphabetic characters, digits, underscore character (_), at
sign (@), number sign (#), and dollar sign ($).
● The identifier is a reserved word.

For compatibility with other database management systems, it is recommended that you avoid the use of special
characters in identifier names, including but not limited to any of the following:

● Leading or trailing whitespace


● Leading single quote
● Semicolons

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 7
Standards

ANSI/ISO SQL Standard

The ability to create identifiers of up to 128 characters is optional ANSI/ISO SQL Language Feature F391.

Example
The following strings are all valid identifiers:

● Surname
● "Client Name"
● `Client Name`
● [Surname]
● SomeBigName
● '[@myVar]'

In this section:

Indirect identifiers [page 8]


Use indirect identifiers when the name of an object must be determined at statement run time, or to avoid
exposing the names of underlying objects in a statement.

Related Information

Reserved words [page 6]


Indirect identifiers [page 8]
TABLE REF data type [page 182]

1.1.2.1 Indirect identifiers

Use indirect identifiers when the name of an object must be determined at statement run time, or to avoid
exposing the names of underlying objects in a statement.

Syntax

Specify indirect identifiers in statements by enclosing them in square brackets and back quotes (for example,
'[@myVariable]'), where @myVariable is the name of an existing variable that stores the name of the actual
object you are operating on.

SQL Anywhere - SQL Reference


8 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Remarks

When an identifier, A, in a statement specifies a variable that contains another identifier, B, identifier A is called an
indirect identifier. If you use EXECUTE IMMEDIATE to dynamically construct statements inside procedures
(specifically, if you are substituting identifiers in your DML EXECUTE IMMEDIATE statements), then consider
using indirect identifiers instead. Indirect identifiers are a safer practice than using EXECUTE IMMEDIATE in your
application logic.

Building indirect identifiers into your application logic improves the dynamic capability of your product. For
example, suppose your application periodically creates a table using the table creation time stamp information as
part of the identifier for the table (for example, CurrentOrders023003032015, where 023003032015 is the time
stamp when the table was created). Now suppose that your application has a procedure that needs to query this
dynamically named table. You could declare a variable called @currentOrders to store the table name, and then
update the variable each time the table is created. Then, you could modify your procedure to include an indirect
identifier for the table ('[@currentOrders]'). When the procedure is called, the indirect identifier is replaced
with the value of the variable and the procedure runs as though the actual table name was specified.

Indirect identifiers are supported in SELECT statements, procedure and function calls, and DML statements as a
substitute for an explicit identifier for the following objects:

● tables
● columns
● mutexes
● semaphores
● user IDs when specified as object owners (for example owner.object-name)

Indirect identifiers are also supported in statements that change the status of mutexes and semaphores (for
example, WAITFOR SEMAPHORE statement).

Before a statement is executed, an indirect identifier is replaced by the value stored in the variable being
referenced, and privilege checking is performed.

Indirect identifier values have a maximum length of 128 bytes and can be of type CHAR, VARCHAR, or LONG
VARCHAR.

For statements where an identifier is required, if the indirect identifier used to specify the name of a column or
table is NULL, an empty string, or another invalid name, then the result is in an error. However, an indirect
identifier may be NULL if it is used as an optional part of a qualified name, such as the owner of a table. A NULL for
an optional part of the identifier is treated as though it is absent.

An indirect identifier replaces one portion of an identifier; it cannot replace the full identifier specification. For
example, if you have a variable @var set to 'GROUPO.Employees', then an error is returned if you attempt to
perform a SELECT operation on the GROUPO.Employees table by using an indirect identifier (for example,
SELECT * FROM '[@var]'). Instead, you must create a variable to store the user portion of the name, and then
reference both objects using indirect references (for example, '[@owner]'.'[@var]')

Use of indirect identifiers overlaps with the use of table reference variables; both are ways of indirectly referring to
a table. However, a table reference variable can provide access to a table that is not accessible in the current
context, whereas an indirect identifier cannot. Additionally, table reference values are resolved at creation time,
while indirect identifiers are resolved at run time.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 9
Privileges and permissions

Privileges on the objects being indirectly referenced in a statement are checked at the time that the indirect
identifiers are evaluated and are enforced prior to the statement execution.

Examples

Many of the examples below show the variables being created using the CREATE VARIABLE statement; this was
done to make the examples easy to try in Interactive SQL. However, a more likely scenario is that you would
declare a variable (DECLARE statement) within the scope of a procedure or function, and then reference the
variable as part of an indirect identifier in a subsequent statement within that procedure, or pass variables in as
parameters.

The following example creates a variable called @col to hold the name of a column (Surname) in the
GROUPO.Employees table. The SELECT statement queries the contents of the Employees.Surname column by
specifying an indirect identifier ('[@col]'):

CREATE OR REPLACE VARIABLE @col LONG VARCHAR = 'Surname';


SELECT E.'[@col]' FROM GROUPO.Employees E;

The following example shows how to use indirect identifiers to query a table:

CREATE OR REPLACE VARIABLE t_owner LONG VARCHAR = 'GROUPO';


CREATE OR REPLACE VARIABLE t_name LONG VARCHAR = 'Employees';
SELECT * FROM '[t_owner]'.'[t_name]';

The following example creates a procedure with an IN parameter (@tableref) that takes a table reference, an IN
parameter (@columnname) that takes the name of a column, and an IN parameter (@value) that takes an integer
value reflecting the ID of the user to delete. The body of the procedure defines how the parameters will be used to
delete the required record from the table.

CREATE PROCEDURE mydelete( IN @tableref TABLE REF,


IN @columnname LONG VARCHAR,
IN @value INT )
SQL SECURITY INVOKER
NO RESULT SET
BEGIN
DELETE FROM TABLE REF (@tableref) AS T WHERE T.'[@columnname]' = @value;
END;
CALL mydelete( TABLE REF ( FTEmployee ), 'employee_id', @employee_to_delete);
CALL mydelete( TABLE REF ( FTStudent ), 'student_id', @student_to_delete);

In the first CALL statement, the database server searches the FTEmployee.employee_id column for a row that
matches the value stored in the @employee_to_delete variable, and then deletes the row. In the second CALL
statement, the database server searches the FTStudent.student_id column for a row that matches the value
stored in the @student_to_delete variable, and then deletes the row.

Related Information

SQL variables [page 120]

SQL Anywhere - SQL Reference


10 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
TABLE REF data type [page 182]
Identifiers [page 6]

1.1.3 Strings

A string is a sequence of characters up to 2 GB in size.

A string can occur in SQL:

● as a string literal. A string literal is a sequence of characters enclosed in single quotes (apostrophes). A string
literal represents a particular, constant value, and it may contain escape sequences for special characters
that cannot be easily typed as characters.
● as the value of a column or variable with a CHAR or NCHAR data type.
● as the result of evaluating an expression.

The length of a string can be measured in two ways:

Byte length

The byte length is the number of bytes in the string.


Character length

The character length is the number of characters in the string, and is based on the character set being used.

For single-byte character sets, such as cp1252, the byte-length and character-length are the same. For multibyte
character sets, a string's byte-length is greater than or equal to its character-length.

Related Information

String literals [page 13]

1.1.4 Constants

Binary literals and string literals can be used as constants.

In this section:

Binary literals [page 12]


A binary literal is a sequence of hexadecimal characters consisting of digits 0-9 and uppercase and
lowercase letters A-F.

String literals [page 13]


A string literal is a sequence of characters enclosed in single quotes.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 11
1.1.4.1 Binary literals

A binary literal is a sequence of hexadecimal characters consisting of digits 0-9 and uppercase and lowercase
letters A-F.

When you enter binary data as literals, you must precede the data by 0x (a zero, followed by an x), and there
should be an even number of digits to the right of this prefix. For example, the hexadecimal equivalent of 39 is
0027, and is expressed as 0x0027.

Hexadecimal constants in the form of 0x12345678 are treated as binary strings. An unlimited number of digits can
be added after the 0x.

A binary literal is sometimes referred to as a binary constant. The preferred term is binary literal.

In this section:

Converting to and from hexadecimal values [page 12]


You can use the CAST, CONVERT, HEXTOINT, and INTTOHEX functions to convert a binary string to an
integer.

1.1.4.1.1 Converting to and from hexadecimal values

You can use the CAST, CONVERT, HEXTOINT, and INTTOHEX functions to convert a binary string to an integer.

The CAST and CONVERT functions convert hexadecimal constants to TINYINT, signed and unsigned 32-bit
integer, signed and unsigned 64-bit integer, NUMERIC, and so on. The HEXTOINT function only converts a
hexadecimal constant to a signed 32-bit-integer.

The value returned by the CAST function cannot exceed 8 digits. Values exceeding 8 digits return an error. Zeros
are added to the left of values less than 8 digits. For example, the following argument returns the value
-2,147,483,647:

SELECT CAST ( 0x0080000001 AS INT );

The following argument returns an error because the 10-digit value cannot be represented as a signed 32-bit
integer:

SELECT CAST ( 0xff80000001 AS INT );

The value returned by the HEXTOINT function can exceed 8 digits if the value can be represented as a signed 32-
bit integer. The HEXTOINT function accepts string literals or variables consisting only of digits and the uppercase
or lowercase letters A-F, with or without a 0x prefix. The hexadecimal value represents a negative integer when
the 8th digit from the right is one of the digits 8-9, the uppercase or lowercase letters A-F, or the previous leading
digits are all uppercase or lowercase letter F.

The following arguments return the value -2,147,483,647:

SELECT HEXTOINT( '0xFF80000001' );

SELECT HEXTOINT( '0x80000001' );

SQL Anywhere - SQL Reference


12 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
SELECT HEXTOINT ( '0xFFFFFFFFFFFFFFFF80000001' );

The following argument returns an error because the argument represents a positive integer value that cannot be
represented as a signed 32-bit integer:

SELECT HEXTOINT( '0x0080000001' );

Related Information

CAST function [Data type conversion] [page 265]


CONVERT function [Data type conversion] [page 285]
HEXTOINT function [Data type conversion] [page 385]
INTTOHEX function [Data type conversion] [page 408]

1.1.4.2 String literals

A string literal is a sequence of characters enclosed in single quotes.

For example, 'Hello world' is a string literal of type CHAR. Its byte length is 11, and its character length is also
11.

A string literal is sometimes referred to as a string constant, literal string, or just as a string. The preferred term is
string literal.

You can specify an NCHAR string literal by prefixing the quoted value with N. For example, N'Hello world' is a
string literal of type NCHAR. Its byte length is 11, and its character length is 11. The bytes within an NCHAR string
literal are interpreted using the database's CHAR character set, and then converted to NCHAR. The syntax
N'string' is a shortened form for CAST( 'string' AS NCHAR ).

In this section:

Escape sequences [page 13]


Sometimes you must put characters into string literals that cannot be typed or entered normally.
Examples include control characters (such as a new line character), single quotes (which would otherwise
mark the end of the string literal), and hexadecimal byte values. For this purpose, you use an escape
sequence.

1.1.4.2.1 Escape sequences

Sometimes you must put characters into string literals that cannot be typed or entered normally. Examples
include control characters (such as a new line character), single quotes (which would otherwise mark the end of
the string literal), and hexadecimal byte values. For this purpose, you use an escape sequence.

The following examples show how to use escape sequences in string literals.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 13
● A single quote is used to mark the beginning and end of a string literal, so a single quote in a string must be
escaped using an additional single quote, as follows: 'John''s database'
● A backslash followed by any character other than n, x, X, or \ is interpreted as two separate characters. For
example, \q inserts a backslash and the letter q.
Hexadecimal escape sequences can be used for any character or binary value. A hexadecimal escape
sequence is a backslash followed by an x followed by two hexadecimal digits. The hexadecimal value is
interpreted as a character in the CHAR character set for both CHAR and NCHAR string literals. The value
\x09 must be coded as \\x09 if you don't want the value stored as a single tab character, but \xyy would be
stored as \xyy. The following example, in code page 1252, represents the digits 1, 2, and 3, followed by the
euro currency symbol: '123\x80'.
● Escape a backslash character by using an additional backslash, as follows: 'c:\\november'. For paths, you
can also use the forward slash (/) instead of a backslash: 'c:/november'.
● Represent a new line character by using a backslash followed by n (\n), specify: 'First line:\nSecond
line:'

You can use the same characters and escape sequences with NCHAR string literals as with CHAR string literals.

To use Unicode characters that cannot be typed directly into the string literal, use the UNISTR function.

Related Information

UNISTR function [String] [page 582]

1.1.5 Operators
There are several arithmetic, string, array, and bitwise operators.

The normal precedence of operations applies. Expressions in parentheses are evaluated first, then multiplication
and division before addition and subtraction. String concatenation happens after addition and subtraction.

In this section:

Comparison operators [page 15]


You can use comparison operators to compare values.

Logical operators [page 16]


Expressions can be combined, negated, or tested using logical operators.

Arithmetic operators [page 17]


You can use arithmetic operators to perform arithmetic operations on expressions.

String operators [page 18]


You can use string operators to concatenate strings.

Array operators [page 25]


You can use array operators to concatenate arrays.

Bitwise operators [page 31]


Several operators can be used on bit data types, integer data types (including all variants such as bit,
tinyint, smallint and so on), binary values, and bit array data types.

SQL Anywhere - SQL Reference


14 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Join operators [page 31]
SQL Anywhere supports two additional comparison operators, *= and =*, which are the Transact-SQL
outer join operators.

Operator precedence [page 32]


The precedence of operators in expressions is significant.

Related Information

Search conditions [page 55]

1.1.5.1 Comparison operators

You can use comparison operators to compare values.

The syntax for comparison is as follows:

expression comparison-operator expression

where comparison-operator is one of the following:

Operator Description

= Equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

!= Not equal to

<> Not equal to

!> Not greater than

!< Not less than

Case sensitivity

By default, databases are created as case insensitive. Comparisons are carried out with the same attention to
case as the database they are operating on. You can control the case sensitivity of databases with the -c option
when you create the database.

Case sensitivity is set at database creation.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 15
Note
All string comparisons are case insensitive unless the database was created as case sensitive.

Trailing blanks

The behavior of the database server when comparing strings is set at database creation.

1.1.5.2 Logical operators

Expressions can be combined, negated, or tested using logical operators.

For example, search conditions can be combined using the AND or OR operators. You can also negate them using
the NOT operator, or test whether an expression would evaluate to true, false, or unknown, using the IS operator.

AND operator

The AND operator is placed between search conditions as follows:

...WHERE condition1 AND condition2

When using AND, the combined condition is TRUE if both conditions are TRUE, FALSE if either condition is
FALSE, and UNKNOWN otherwise.
OR operator

The OR operator is placed between search conditions as follows:

...WHERE condition1 OR condition2

When using OR, the combined condition is TRUE if either condition is TRUE, FALSE if both conditions are
FALSE, and UNKNOWN otherwise.
NOT operator

The NOT operator is placed before a condition to negate the condition, as follows:

...WHERE NOT condition

The NOT condition is TRUE if condition is FALSE, FALSE if condition is TRUE, and UNKNOWN if
condition is UNKNOWN.
IS operator

The IS operator is placed between an expression and the truth value you are testing for. The syntax for the IS
operator is as follows:

expression IS [ NOT ] truth-value

The IS condition is TRUE if the expression evaluates to the supplied truth-value, which must be one of
TRUE, FALSE, UNKNOWN, or NULL. Otherwise, the value is FALSE.

SQL Anywhere - SQL Reference


16 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
For example, 5*3=15 IS TRUE tests whether the expression 5*3=15 evaluates to TRUE.

Related Information

Three-valued logic [page 82]

1.1.5.3 Arithmetic operators

You can use arithmetic operators to perform arithmetic operations on expressions.

The software supports the following arithmetic operators:

expression + expression

Addition. If either expression is the NULL value, the result is NULL.


expression - expression

Subtraction. If either expression is the NULL value, the result is NULL.


-expression

Negation. If the expression is the NULL value, the result is NULL.


expression * expression

Multiplication. If either expression is NULL, the result is NULL.


expression / expression

Division. If either expression is NULL or if the second expression is 0, the result is NULL.
expression % expression

Modulo finds the integer remainder after a division involving two whole numbers. For example, 21 % 11 = 10
because 21 divided by 11 equals 1 with a remainder of 10.

Support for arithmetic operators on date and time data types

The support of arithmetic operators on date and time data types is limited to + and -. There are some constraints
on how these operators can be used.

For an operation, expression1 + expression2, one of the expressions must be a date, and the other
expression must be a time. The result is a TIMESTAMP formed by combining the date and time expressions.

For an operation, expression1 - expression2, the restrictions and behavior are as follows:

expression1 is a subtype of TIMESTAMP, and expression2 is a subtype of SIGNED LONG

The result is a TIMESTAMP with expression2 days subtracted.


expression1 is a subtype of TIMESTAMP, and so is expression2

The result is the number of days between expression1 and expression2, which could also be expressed as
( DATEDIFF ( day, expression1,expression2 ) ).

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 17
expression1 is a subtype of TIMESTAMP, and expression2 is a subtype of NUMERIC or VARCHAR

expression2 is first converted to a NUMERIC and is then interpreted as a number of days. The result is the
number of days between expression1 and expression2, which could also be expressed as ( DATEDIFF
( day, expression1 , expression2 ) ).

Standards

ANSI/ISO SQL Standard

The use of % as a modulus operator is not in the standard.

1.1.5.4 String operators

You can use string operators to concatenate strings.

The software supports the following string operators:

expression || expression

String concatenation (two vertical bars). If either string is NULL, it is treated as the empty string for
concatenation.
expression + expression

Alternative string concatenation. When using the + concatenation operator, you must ensure the operands
are explicitly set to character data types rather than relying on implicit data conversion.

For example, the following query returns the integer value 579:

SELECT 123 + 456;

whereas the following query returns the character string 123456:

SELECT '123' + '456';

Standards

ANSI/ISO SQL Standard

The || operator is the ANSI/ISO SQL Standard string concatenation operator. However, in the SQL standard,
if either operand of || is the NULL value, then the result of the concatenation is also NULL. In the software, the
|| operator treats NULL as an empty string.

In this section:

OPENXML operator [page 19]


Generates a result set from an XML document.

SQL Anywhere - SQL Reference


18 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.1.5.4.1 OPENXML operator

Generates a result set from an XML document.

Syntax - Specify the XML

OPENXML(
xml-data
, xpath
[, flags
[, namespaces ] ]
)
WITH ( column-name column-type
[ xpath ] [ , ... ]
)

Syntax - Specify a file containing the XML

OPENXML( { USING FILE | USING VALUE }


xml-data
, xpath
[, flags
[, namespaces ] ]
)
WITH ( column-name column-type
[ xpath ] [ , ... ]
)
[ OPTION ( scan-option ) ]
[ AS ] correlation-name

scan-option :
ENCODING encoding
| BYTE ORDER MARK { ON | OFF }

Parameters

WITH clause

Specifies the schema of the result set and how the value is found for each column in the result set. WITH
clause xpath arguments are matched relative to the matches for the xpath in the second argument. If a
WITH clause expression matches more than one node, then only the first node in the document order is used.
If the node is not a text node, then the result is found by appending all the text node descendants. If a WITH
clause expression does not match any nodes, then the column for that row is NULL.

The xpath arguments in the WITH clause can be literal strings or variables. See http://www.w3.org/TR/
xpath .

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 19
The OPENXML WITH clause syntax is similar to the syntax for selecting from a stored procedure.
USING FILE | USING VALUE

Use the USING FILE clause to load data from a file.

Use the USING VALUE clause to load data from any expression of CHAR, NCHAR, BINARY, or LONG BINARY
type, or BLOB string.

xml-data

The XML on which the result set is based. This can be any string expression, such as a constant, variable,
or column.

The xml-data is parsed directly in the NCHAR encoding if there are any NCHAR columns in the output.
The xpath and namespaces arguments are also converted and parsed in the NCHAR encoding.
xpath

A string containing an XPath query. XPath allows you to specify patterns that describe the structure of
the XML document you are querying. The XPath pattern included in this argument selects the nodes from
the XML document. Each node that matches the XPath query in the second xpath argument generates
one row in the table.

Metaproperties can only be specified in WITH clause xpath arguments. A metaproperty is accessed
within an XPath query as if it was an attribute. If a namespaces is not specified, then by default the prefix
mp is bound to the Uniform Resource Identifier (URI) urn:sap-com:sa-xpath-metaprop. If a namespaces
is specified, this URI must be bound to mp or some other prefix to access metaproperties in the query.
Metaproperty names are case sensitive. The OPENXML statement supports the following
metaproperties:

@mp:id

returns an ID for a node that is unique within the XML document. The ID for a given node in a given
document may change if the database server is restarted. The value of this metaproperty increases
with document order.
@mp:localname

returns the local part of the node name, or NULL if the node does not have a name.
@mp:prefix

returns the prefix part of the node name, or NULL if the node does not have a name or if the name is
not prefixed.
@mp:namespaceuri

returns the URI of the namespace that the node belongs to, or NULL if the node is not in a
namespace.
@mp:xmltext

returns a subtree of the XML document in XML form. For example, when you match an internal node,
you can use this metaproperty to return an XML string, rather than the concatenated values of the
descendant text nodes.
flags

SQL Anywhere - SQL Reference


20 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Indicates the mapping that should be used between the XML data and the result set when an XPath query
is not specified in the WITH clause. If the flags parameter is not specified, the default behavior is to map
attributes to columns in the result set. The flags parameter can have one of the following values:

Value Description

1 XML attributes are mapped to columns in the result set


(the default).

2 XML elements are mapped to columns in the result set.

namespace-declaration

An XML document. The in-scope namespaces for the query are taken from the root element of the
document. If namespaces are specified, then you must include a flags argument, even if all the xpath
arguments are specified.

column-name

The name of the column in the result set.


column-type

The data type of the column in the result set. The data type must be compatible with the values selected from
the XML document.
OPTION clause

Use the OPTION clause to specify parsing options to use for the input file, such as escape characters,
delimiters, encoding, and so on.

ENCODING clause

The ENCODING clause allows you to specify the encoding that is used to read the file.

If the ENCODING clause is not specified, then encoding for values is assumed to be in the database
character set (db_charset) if the values are of type CHAR or BINARY, and NCHAR database character set
(nchar_charset) if the values are of type NCHAR.
BYTE ORDER MARK clause

Use the BYTE ORDER MARK clause to specify whether a byte order mark (BOM) is present in the
encoding. By default, this option is ON, which enables the server to search for and interpret a byte order
mark (BOM) at the beginning of the data. If BYTE ORDER MARK is OFF, the server does not search for a
BOM.

You must specify the BYTE ORDER MARK clause if the input data is encoded.

If the ENCODING clause is specified:

● If the BYTE ORDER MARK option is ON and you specify a UTF-16 encoding with an endian such as
UTF-16BE or UTF-16LE, the database server searches for a BOM at the beginning of the data. If a
BOM is present, it is used to verify the endianness of the data. If you specify the wrong endian, an
error is returned.
● If the BYTE ORDER MARK option is ON and you specify a UTF-16 encoding without an explicit endian,
the database server searches for a BOM at the beginning of the data. If a BOM is present, it is used to
determine the endianness of the data. Otherwise, the operating system endianness is assumed.
● If the BYTE ORDER MARK option is ON and you specify a UTF-8 encoding, the database server
searches for a BOM at the beginning of the data. If a BOM is present it is ignored.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 21
If the ENCODING clause is not specified:

● If you do not specify an ENCODING clause and the BYTE ORDER MARK option is ON, the server looks
for a BOM at the beginning of the input data. If a BOM is located, the source encoding is automatically
selected based on the encoding of the BOM (UTF-16BE, UTF-16LE, or UTF-8) and the BOM is not
considered to be part of the data to be loaded.
● If you do not specify an ENCODING clause and the BYTE ORDER MARK option is OFF, or a BOM is not
found at the beginning of the input data, the database CHAR encoding is used.

Remarks

The OPENXML operator parses the xml-data and models the result as a tree. The tree contains a separate node
for each element, attribute, and text node, or other XML construct. The XPath queries supplied to the OPENXML
operator are used to select nodes from the tree, and the selected nodes are then mapped to the result set.

The XML parser used by the OPENXML operator is non-validating, and does not read the external DTD subset or
external parameter entities.

If disk sandboxing is enabled, then database operations are limited to the directory where the main database file is
located.

When there are multiple matches for a column expression, the first match in the document order (the order of the
original XML document before it was parsed) is used. NULL is returned if there are no matching nodes. When an
internal node is selected, the result is all the descendant text nodes of the internal node concatenated together.

Columns of type BINARY, LONG BINARY, IMAGE, and VARBINARY are assumed to be in base64-encoded format
and are decoded automatically. If you generate XML using the FOR XML clause, these types are base64-encoded,
and can be decoded using the OPENXML operator.

The OPENXML operator supports a subset of the XPath syntax, as follows:

● The child, self, attribute, descendant, descendant-or-self, and parent axes are fully supported.
● Both abbreviated and unabbreviated syntax can be used for all supported features. For example, 'a' is
equivalent to 'child::a' and '..' is equivalent to 'parent::node()'.
● Name tests can use wildcards. For example, 'a/*/b'.
● The following kind tests are supported: node(), text(), processing-instruction(), and comment().
● Qualifiers of the form expr1[expr2] and expr1[expr2="string" ] can be used, where expr2 is any
supported XPath expression. A qualifier evaluates TRUE if expr2 matches one or more nodes. For example,
'a[b]' finds a nodes that have at least one b child, and a[b="I"] finds a nodes that have at least one b child
with a text value of I.

Privileges

If the USING FILE clause is specified, you must have the READ FILE system privilege. Otherwise, no privileges are
required.

SQL Anywhere - SQL Reference


22 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Example
The following query generates a result set from the XML document supplied as the first argument to the
OPENXML operator:

SELECT * FROM OPENXML( '<products>


<ProductType ID="301">Tee Shirt</ProductType>
<ProductType ID="401">Baseball Cap</ProductType>
</products>',
'/products/ProductType' )
WITH ( ProductName LONG VARCHAR 'text()', ProductID CHAR(3) '@ID');

This query generates the following result:

ProductName ProductID

Tee Shirt 301

Baseball Cap 401

In the following example, the first <ProductType> element contains an entity. When you execute the query, this
node is parsed as an element with four children: Tee, &amp;, Sweater, and Set. You can use a period (.) to
concatenate the children together in the result set.

SELECT * FROM OPENXML( '<products>


<ProductType ID="301">Tee &amp; Sweater Set</ProductType>
<ProductType ID="401">Baseball Cap</ProductType>
</products>',
'/products/ProductType' )
WITH ( ProductName LONG VARCHAR '.', ProductID CHAR(3) '@ID');

This query generates the following result:

ProductName ProductID

Tee & Sweater Set 301

Baseball Cap 401

The following query uses an equality predicate to generate a result set from the supplied XML document.

SELECT * FROM OPENXML('<EmployeeDirectory>


<Employee>
<column name="EmployeeID">105</column>
<column name="GivenName">Matthew</column>
<column name="Surname">Cobb</column>
<column name="Street">7 Pleasant Street</column>
<column name="City">Grimsby</column>
<column name="State">UT</column>
<column name="PostalCode">02154</column>
<column name="Phone">6175553840</column>
</Employee>
<Employee>
<column name="EmployeeID">148</column>
<column name="GivenName">Julie</column>
<column name="Surname">Jordan</column>
<column name="Street">1244 Great Plain Avenue</column>
<column name="City">Woodbridge</column>
<column name="State">AZ</column>
<column name="PostalCode">01890</column>
<column name="Phone">6175557835</column>
</Employee>

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 23
<Employee>
<column name="EmployeeID">160</column>
<column name="GivenName">Robert</column>
<column name="Surname">Breault</column>
<column name="Street">358 Cherry Street</column>
<column name="City">Milton</column>
<column name="State">PA</column>
<column name="PostalCode">02186</column>
<column name="Phone">6175553099</column>
</Employee>
<Employee>
<column name="EmployeeID">243</column>
<column name="GivenName">Natasha</column>
<column name="Surname">Shishov</column>
<column name="Street">151 Milk Street</column>
<column name="City">Grimsby</column>
<column name="State">UT</column>
<column name="PostalCode">02154</column>
<column name="Phone">6175552755</column>
</Employee>
</EmployeeDirectory>', '/EmployeeDirectory/Employee')
WITH ( EmployeeID INT 'column[@name="EmployeeID"]',
GivenName CHAR(20) 'column[@name="GivenName"]',
Surname CHAR(20) 'column[@name="Surname"]',
PhoneNumber CHAR(10) 'column[@name="Phone"]');

This query generates the following result set:

EmployeeID GivenName Surname PhoneNumber

105 Matthew Cobb 6175553840

148 Julie Jordan 6175557835

160 Robert Breault 6175553099

243 Natasha Shishov 6175552755

The following query uses the XPath @attribute expression to generate a result set:

SELECT * FROM OPENXML( '<Employee


EmployeeID="105"
GivenName="Matthew"
Surname="Cobb"
Street="7 Pleasant Street"
City="Grimsby"
State="UT"
PostalCode="02154"
Phone="6175553840"
/>', '/Employee' )
WITH ( EmployeeID INT '@EmployeeID',
GivenName CHAR(20) '@GivenName',
Surname CHAR(20) '@Surname',
PhoneNumber CHAR(10) '@Phone');

The following query operates on an XML document like the one used in the above query, except that an XML
namespace has been introduced. It demonstrates the use of wildcards in the name test for the XPath query,
and generates the same result set as the above query.

SELECT * FROM OPENXML( '<Employee xmlns="http://www.sap.com/EmployeeDemo"


EmployeeID="105"
GivenName="Matthew"
Surname="Cobb"
Street="7 Pleasant Street"
City="Grimsby"

SQL Anywhere - SQL Reference


24 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
State="UT"
PostalCode="02154"
Phone="6175553840"
/>', '/*:Employee' )
WITH ( EmployeeID INT '@EmployeeID',
GivenName CHAR(20) '@GivenName',
Surname CHAR(20) '@Surname',
PhoneNumber CHAR(10) '@Phone');

Alternatively, you could specify a namespace declaration:

SELECT * FROM OPENXML( '<Employee xmlns="http://www.sap.com/EmployeeDemo"


EmployeeID="105"
GivenName="Matthew"
Surname="Cobb"
Street="7 Pleasant Street"
City="Grimsby"
State="UT"
PostalCode="02154"
Phone="6175553840"
/>', '/prefix:Employee', 1, '<r xmlns:prefix="http://www.sap.com/EmployeeDemo"/
>' )
WITH ( EmployeeID INT '@EmployeeID',
GivenName CHAR(20) '@GivenName',
Surname CHAR(20) '@Surname',
PhoneNumber CHAR(10) '@Phone');

Related Information

SQL data types [page 126]


FROM clause [page 1116]

1.1.5.5 Array operators

You can use array operators to concatenate arrays.

The software supports the following string operator:

expression || expression

Array concatenation (two vertical bars). If either array is NULL, it is treated as a zero-length array for
concatenation.

Standards

ANSI/ISO SQL Standard

The || operator is the ANSI/ISO SQL Standard concatenation operator. However, in the SQL standard, if
either operand of || is the NULL value, then the result of the concatenation is also NULL. In the software, the ||
operator treats NULL as a zero-length array.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 25
In this section:

UNNEST array operator [page 26]


Creates a derived table from the given array expressions that results in one row per array element.

1.1.5.5.1 UNNEST array operator

Creates a derived table from the given array expressions that results in one row per array element.

Syntax

UNNEST ( array-expression [, ...] )


[ WITH ORDINALITY ]

Parameters

array-expression

An array to derive a table column from.


WITH ORDINALITY

The WITH ORDINALITY clause permits the application to recall the original array element from which each
value was obtained. Valid UNNEST derived tables must have names specified (by using the AS clause) for
each of the resulting expressions. The order of the resulting rows from unnest is not guaranteed. Users can
achieve a desired ordering with an ORDER BY clause.

Remarks

If the array expressions have different cardinalities, the missing output expressions from the shorter array(s) are
set to NULL. If the WITH ORDINALITY clause is specified, the result set contains an integer column that identifies
the array element's cardinal number that the row represents. The new column is appended to the unnest derived
table as its last column.

Privileges

None

SQL Anywhere - SQL Reference


26 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Example
The following example illustrates how to use of the unnest operator with two arrays that have different
cardinalities:

SELECT * FROM UNNEST( ARRAY(2,3,4), ARRAY(4,5,6) ) WITH ORDINALITY AS DT(X,Y,Z);

The SQL statement returns the following result:

X Y Z

2 4 1

3 5 2

4 6 3

Examples

The following statements create a simple array and populate it with data:

CREATE OR REPLACE VARIABLE x1 ARRAY (10) OF INT;


SELECT ARRAY_AGG(id) INTO x1 FROM GROUPO.Products;

The following statement returns the data in the array, unnested:

SELECT * FROM UNNEST(x1) AS DT(X);

300

301

302

400

401

500

501

600

601

700

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 27
The following statement returns the same data, but adds ordinality (Y column):

SELECT * FROM UNNEST(x1) WITH ORDINALITY AS DT(X,Y);

X Y

300 1

301 2

302 3

400 4

401 5

500 6

501 7

600 8

601 9

700 10

The following statement returns the data from cell 1 of the array:

SELECT x1[[1]];

x1[[1]]

300

The following statements create a two dimensional array and populate it with data:

CREATE OR REPLACE VARIABLE x1 ARRAY(2) OF ARRAY (10) OF INT;


SELECT ARRAY_AGG( "id" ) INTO x1[[1]] FROM GROUPO.Products;
SELECT ARRAY_AGG( GROUPO.Products.Quantity ) INTO x1[[2]] FROM GROUPO.Products;

The following statement returns the data in the array, unnested:

SELECT * FROM UNNEST( x1[[1]], x1[[2]] ) WITH ORDINALITY AS DT( X, Y, Z);

X Y Z

300 28 1

301 54 2

302 75 3

400 112 4

SQL Anywhere - SQL Reference


28 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
X Y Z

401 12 5

500 36 6

501 28 7

600 39 8

601 32 9

700 80 10

The following statement returns the data found in the second column first row of the array::

SELECT (x1[[2]])[[1]];

(x1[[2]])[[1]]

28

The following statements create an array and a row, and populates them with data:

CREATE OR REPLACE VARIABLE x1 ARRAY (10) OF INT;


CREATE OR REPLACE VARIABLE x2 ROW( a1 INT, b1 ARRAY(10) OF INT );
SELECT ARRAY_AGG( "id" ) INTO x1 FROM GROUPO.Products;
SET x2.a1 = 10;
SET x2.b1 = x1;

The following statement returns the data in the array and row together:

SELECT x2.a1 AS a1, X, Z FROM UNNEST( x2.b1 ) WITH ORDINALITY AS DT(X,Z);

a1 X Z

10 300 1

10 301 2

10 302 3

10 400 4

10 401 5

10 500 6

10 501 7

10 600 8

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 29
a1 X Z

10 601 9

10 700 10

The following statement returns the first values in the array and row:

SELECT x2.a1, x2.b1[[1]];

a1 x2.b1[[1]]

10 300

The following statements create an array of ROW and populate it with data

CREATE OR REPLACE VARIABLE x4 ARRAY(10) OF ROW( a1 INT, b1 INT, c1 VARCHAR(120) );


SELECT ARRAY_AGG( ROW( ID, Quantity, Name ) ) INTO x4 FROM GROUPO.Products;

The following statement returns an unnested row from the array:

SELECT (x).a1 FROM UNNEST( x4 ) AS dt(x);

expression

300

301

302

400

401

500

501

600

601

700

Related Information

ROW and ARRAY composite data types [page 180]


Comparisons of composite types [page 192]

SQL Anywhere - SQL Reference


30 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
ARRAY constructor [Composite] [page 235]
FROM clause [page 1116]

1.1.5.6 Bitwise operators

Several operators can be used on bit data types, integer data types (including all variants such as bit, tinyint,
smallint and so on), binary values, and bit array data types.

Operator Description

& bitwise AND

| bitwise OR

^ bitwise exclusive OR

~ bitwise NOT

The bitwise operators &, | and ~ are not interchangeable with the logical operators AND, OR, and NOT.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement selects rows in which the correct bits are set. For example, if the value of Options is
0x1001 then the row would be included.

SELECT *
FROM tableA
WHERE ( Options & 0x0101 ) <> 0;

1.1.5.7 Join operators

SQL Anywhere supports two additional comparison operators, *= and =*, which are the Transact-SQL outer join
operators.

When one of these operators is used in a comparison predicate, an implicit LEFT or RIGHT OUTER JOIN is
specified.

Note
Support for Transact-SQL outer join operators *= and =* is deprecated. To use Transact-SQL outer joins, the
tsql_outer_joins database option must be set to On.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 31
1.1.5.8 Operator precedence

The precedence of operators in expressions is significant.

The operators at the top of the following list are evaluated before those at the bottom of the list.

1. unary operators (operators that require a single operand)


2. &, |, ^, ~
3. *, /, %
4. +, -
5. ||
6. not
7. and
8. or

When you use more than one operator in an expression, make the order of operation explicit using parentheses.

1.1.6 Expressions in SQL statements

An expression is a statement that can be evaluated to return values.

Syntax

expression:
case-expression
| constant
| [correlation-name.]column-name
| - expression
| expression operator expression
| ( expression )
| function-name ( expression, ... )
| if-expression
| special value
| ( subquery )
| variable-name
| sequence-expression

case-expression :
CASE expression
WHEN expression
THEN expression,...
[ ELSE expression ]
END

alternative form of case-expression :


CASE
WHEN search-condition
THEN expression, ...
[ ELSE expression ]
END

constant :
integer | number | string | host-variable

SQL Anywhere - SQL Reference


32 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
special-value :
CURRENT { DATE | TIME | TIMESTAMP }
| NULL
| SQLCODE
| SQLSTATE
| USER

if-expression :
IF condition
THEN expression
[ ELSE expression ]
ENDIF

sequence-expression :
sequence-name.[ CURRVAL | NEXTVAL ]
FROM table-name

java-ref:
.field-name [ java-ref ]
| >> field-name [ java-ref ]
| .method-name ( [ expression,... ] ) [ java-ref ]
| >> method-name ( [ expression,...] ) [ java-ref ]

operator:
{ + | - | * | / | || | % }

Remarks

Expressions are used in many different places.

Expressions are formed from several different kinds of elements. These are discussed in the sections on functions
and variables.

You must be connected to the database to evaluate expressions.

Side effects

None.

In this section:

Constants in expressions [page 35]


Constants are numbers or string literals. String constants are enclosed in apostrophes ('single quotes').
An apostrophe is represented inside a string by two apostrophes in a row.

Column names in expressions [page 35]


A column name is an identifier preceded by an optional correlation name. A correlation name is usually a
table name.

Subqueries in expressions [page 35]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 33
A subquery is a SELECT statement that is nested inside another SELECT, INSERT, UPDATE, or DELETE
statement, or another subquery.

IF expressions [page 36]


An IF expression tests whether a condition is TRUE, FALSE, or UNKNOWN.

CASE expressions [page 37]


The CASE expression provides conditional SQL expressions. Case expressions can be used anywhere an
expression can be used.

Regular expressions overview [page 38]


A regular expression is a sequence of characters, wildcards, or operators that defines a pattern to search
for within a string.

Regular expressions syntax [page 39]


Regular expressions are supported with the SIMILAR TO, and REGEXP search conditions, and the
REGEXP_SUBSTR function.

Regular expressions examples [page 51]


There are many helpful examples of regular expressions you can refer to.

Compatibility of expressions [page 54]


SQL Anywhere uses the ANSI/ISO SQL Standard convention whereby strings enclosed in apostrophes are
constant expressions, and strings enclosed in quotation marks (double quotes) are delimited identifiers
(names for database objects).

Related Information

Special values [page 84]


SQL functions [page 200]
SQL variables [page 120]
Search conditions [page 55]
SQL data types [page 126]

SQL Anywhere - SQL Reference


34 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.1.6.1 Constants in expressions

Constants are numbers or string literals. String constants are enclosed in apostrophes ('single quotes'). An
apostrophe is represented inside a string by two apostrophes in a row.

1.1.6.2 Column names in expressions

A column name is an identifier preceded by an optional correlation name. A correlation name is usually a table
name.

If a column name has characters other than letters, digits and underscore, it must be surrounded by quotation
marks (""). For example, the following are valid column names:

● Employees.Name
● address
● "date hired"
● "salary"."date paid"

Related Information

Identifiers [page 6]
FROM clause [page 1116]

1.1.6.3 Subqueries in expressions

A subquery is a SELECT statement that is nested inside another SELECT, INSERT, UPDATE, or DELETE
statement, or another subquery.

If a subquery matches no rows, it evaluates to NULL.

The SELECT statement must be enclosed in parentheses, and must contain one and only one SELECT list item.
When used as an expression, a subquery is generally allowed to return only one value.

A subquery can be used anywhere that a column name can be used. For example, a subquery can be used in the
SELECT list of another SELECT statement.

Related Information

Subqueries in search conditions [page 58]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 35
1.1.6.4 IF expressions

An IF expression tests whether a condition is TRUE, FALSE, or UNKNOWN.

This is the syntax of the IF expression:

IF condition
THEN expression1
[ ELSE expression2 ]
{ ENDIF | END IF }

This expression returns the following:

● If condition evaluates to TRUE, the IF expression returns expression1.


● If condition evaluates to FALSE, the IF expression returns expression2.
● If condition evaluates to FALSE, and there is no expression2, the IF expression returns NULL.
● If condition evaluates to UNKNOWN, the IF expression returns NULL.

expression1 is evaluated only if condition is TRUE. Similarly, expression2 is evaluated only if condition is
FALSE. Both expression1 and expression2 are arbitrary expressions; condition is any valid search
condition.

Note
The IF expression is not the same as the IF statement.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

IF statement [page 1160]


Search conditions [page 55]
NULL special value [page 100]

SQL Anywhere - SQL Reference


36 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.1.6.5 CASE expressions

The CASE expression provides conditional SQL expressions. Case expressions can be used anywhere an
expression can be used.

The syntax of the CASE expression is as follows:

CASE expression-1
WHEN expression-2
THEN expression-3, ...
[ ELSE expression-4 ]
{ END | END CASE }

If the expression following the CASE clause is equal to the expression following the WHEN clause, then the
expression following the THEN statement is returned. Otherwise the expression following the ELSE statement is
returned, if it exists.

the CASE expression returns NULL if the ELSE clause doesn't exist and expression-1' doesn't match any of the
expression-2...expression-n values.

For example, the following code uses a case expression as the second clause in a SELECT statement.

SELECT ID,
( CASE Name
WHEN 'Tee Shirt' THEN 'Shirt'
WHEN 'Sweatshirt' THEN 'Shirt'
WHEN 'Baseball Cap' THEN 'Hat'
ELSE 'Unknown'
END ) AS Type
FROM GROUPO.Products;

An alternative syntax is as follows:

CASE
WHEN search-condition
THEN expression-1, ...
[ ELSE expression-2 ]
END [ CASE ]

If the search-condition following the WHEN clause is satisfied, the expression following the THEN statement is
returned. Otherwise the expression following the ELSE statement is returned, if it exists.

For example, the following statement uses a case expression as the third clause of a SELECT statement to
associate a string with a search-condition.

SELECT ID, Name,


( CASE
WHEN Name='Tee Shirt' THEN 'Sale'
WHEN Quantity >= 50 THEN 'Big Sale'
ELSE 'Regular price'
END ) AS Type
FROM GROUPO.Products;

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 37
NULLIF function for abbreviated CASE expressions

The NULLIF function provides a way to write some CASE clauses in short form. The syntax for NULLIF is as
follows:

NULLIF ( expression-1, expression-2 )

NULLIF compares the values of the two expressions. If the first expression equals the second expression, NULLIF
returns NULL. If the first expression does not equal the second expression, NULLIF returns the first expression.

Note
Do not confuse the syntax of the CASE expression with that of the CASE clause.

Standards

ANSI/ISO SQL Standard

Core Feature. The standard permits any expression referenced by the statement to be evaluated at any point
during execution. In the software, expression evaluation occurs when each WHEN clause is evaluated, in their
syntactic order, with the exception of constant values that can be determined at compile time.

Support for END CASE with CASE expressions, in addition to END, is not in the standard. The standard
defines END for use with CASE expressions and END CASE for use with CASE clauses.

Related Information

CASE statement [page 764]

1.1.6.6 Regular expressions overview

A regular expression is a sequence of characters, wildcards, or operators that defines a pattern to search for
within a string.

Regular expressions are supported as part of a REGEXP or SIMILAR TO search conditions in the WHERE clause of
a SELECT statement, or as an argument to the REGEXP_SUBSTR function. The LIKE search condition does not
support regular expressions, although some of the wildcards and operators you can specify with LIKE resemble
the regular expression wildcards and operators.

The following SELECT statement uses a regular expression ((K|C[^h])%) to search the Contacts table and
return contacts whose last name begins with K or C, but not Ch:

SELECT Surname, GivenName


FROM GROUPO.Contacts
WHERE Surname SIMILAR TO '(K|C[^h])%';

SQL Anywhere - SQL Reference


38 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
A regular expression can include additional syntax to specify grouping, quantification, assertions, and alternation.

Grouping

Grouping allows you to group parts of a regular expression to apply some additional matching criteria. For
example, '(abc){2}' matches abcabc.

You can also use grouping to control the order in which the parts of the expression are evaluated. For
example, 'ab(cdcd)' looks first for an incidence of cdcd, and then evaluates whether the instance of cdcd is
preceded by ab.
Quantification

Quantification allows you to control the number of times the preceding part of the expression can occur. For
example, a question mark (?) is a quantifier that matches zero or one instance of the previous character. So,
'honou?r' matches both honor and honour.
Assertions

Normally, searching for a pattern returns that pattern. Assertions allow you to test for the presence of a
pattern, without having that pattern become part of what is returned. For example, 'SQL(?= Anywhere)'
matches SQL only if it is followed by a space and then Anywhere.
Alternation

Alternation allows you to specify alternative patterns to search for if the preceding pattern cannot be found.
Alternate patterns are evaluated from left to right, and searching stops at the first match. For example,
'col(o|ou)r' looks for an instance of color. If no instance is found, colour is searched for instead.

Related Information

Regular expressions syntax [page 39]


LIKE, REGEXP, and SIMILAR TO search conditions [page 62]
Search conditions [page 55]
REGEXP search condition [page 69]
SIMILAR TO search condition [page 70]
REGEXP_SUBSTR function [String] [page 487]

1.1.6.7 Regular expressions syntax

Regular expressions are supported with the SIMILAR TO, and REGEXP search conditions, and the
REGEXP_SUBSTR function.

For SIMILAR TO, regular expression syntax is consistent with the ANSI/ISO SQL standard. For REGEXP and
REGEXP_SUBSTR, regular expression syntax and support is consistent with Perl 5.

Regular expressions are used by REGEXP and SIMILAR TO to match a string, whereas regular expressions are
used by REGEXP_SUBSTR to match a substring. To achieve substring matching behavior for REGEXP and
SIMILAR TO, you can specify wildcards on either side of the pattern you are trying to match. For example, REGEXP
'.*car.*' matches car, carwash, and vicar. Or, you can rewrite your query to use the REGEXP_SUBSTR
function.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 39
Regular expression matching with SIMILAR TO is case- and accent-insensitive. REGEXP and REGEXP_SUBSTR is
not affected by the database accent and case sensitivity.

In this section:

Regular expressions: Metacharacters [page 40]


Metacharacters are symbols or characters that have a special meaning within a regular expression.

Regular expressions: Special sub-character classes [page 44]


Sub-character classes are special character classes embedded within a larger character class.

Regular expressions: Other supported syntax conventions [page 46]


The following syntax conventions are supported by the REGEXP search condition and the
REGEXP_SUBSTR function, and they assume that the backslash is the escape character. These
conventions are not supported by the SIMILAR TO search expression.

Regular expressions: Assertions [page 49]


Assertions test whether a condition is true, and affect the position in the string where matching begins.
Assertions do not return characters; the assertion pattern is not included in the final match.

1.1.6.7.1 Regular expressions: Metacharacters

Metacharacters are symbols or characters that have a special meaning within a regular expression.

The treatment of metacharacters can vary depending on:

● whether the regular expression is being used with the SIMILAR TO or REGEXP search conditions, or the
REGEXP_SUBSTR function
● whether the metacharacter is inside of a character class in the regular expression

Before continuing, you should understand the definition of a character class. A character class is a set of
characters enclosed in square brackets, against which characters in a string are matched. For example, in the
syntax SIMILAR TO 'ab[1-9]', [1-9] is a character class and matches one digit in the range of 1 to 9, inclusive.
The treatment of metacharacters in a regular expression can vary depending on whether the metacharacter is
placed inside a character class. Specifically, most metacharacters are handled as regular characters when
positioned inside of a character class.

For SIMILAR TO (only), the metacharacters *, ?, +, _, |, (, ), { must be escaped within a character class.

To include a literal minus sign (-), caret (^), or right-angle bracket (]) character in a character class, it must be
escaped.

SQL Anywhere - SQL Reference


40 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
The list of supported regular expression metacharacters is provided below. Almost all metacharacters are treated
the same when used by SIMILAR TO, REGEXP, and REGEXP_SUBSTR:

Character Additional information

[] Left and right square brackets are used to specify a character


class. A character class is a set of characters to match
against.

With the exception of the hyphen (-) and the caret (^), meta­
characters and quantifiers (such as * and {m}, respectively)
specified within a character class have no special meaning
and are evaluated as actual characters.

Sub-character classes such as POSIX character classes are


also supported.

* The asterisk can be used to match a character 0 or more


times. For example, REGEXP '.*abc' matches a string
that ends with abc, and starts with any prefix. So, aabc, xy­
zabc, and abc match, but bc and abcc do not.

? The question mark can be used to match a character 0 or 1


times. For example, 'colou?r' matches color and colour.

+ The plus sign can be used to match a character 1 or more


times. For example, 'bre+' matches bre and bree, but not
br.

- A hyphen can be used within a character class to denote a


range. For example, REGEXP '[a-e]' matches a, b, c, d,
and e.

% The percent sign can be used with SIMILAR TO to match any


number of characters.

The percent sign is not considered a metacharacter for RE­


GEXP and REGEXP_SUBSTR. When specified, it matches a
percent sign (%).

_ The underscore can be used with SIMILAR TO to match a sin­


gle character.

The underscore is not considered a metacharacter for RE­


GEXP and REGEXP_SUBSTR. When specified, it matches an
underscore (_).

| The pipe symbol is used to specify alternative patterns to use


for matching the string. In a string of patterns separated by a
vertical bar, the vertical bar is interpreted as an OR and
matching stops at the first match made starting from the left­
most pattern. So, you should list the patterns in descending
order of preference. You can specify an unlimited number of
alternative patterns.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 41
Character Additional information

() Left and right parenthesis are metacharacters when used for


grouping parts of the regular expression. For example, (ab)*
matches zero or more repetitions of ab. As with mathematical
expressions, you use grouping to control the order in which
the parts of a regular expression are evaluated.

{} Left and right curly braces are metacharacters when used for
specifying quantifiers. Quantifiers specify the number of
times a pattern must repeat to constitute a match. For exam­
ple:

{m}

Matches a character exactly m times. For example,


'519-[0-9]{3}-[0-9]{4}' matches a phone num­
ber in the 519 area code (providing the data is formatted
in the manner defined in the syntax).
{m,}

Matches a character at least m times. For example,


'[0-9]{5,}' matches any string of five or more digits.
{m,n}

Matches a character at least m times, but not more than n


times. For example, SIMILAR TO '_{5,10}'
matches any string with between 5 and 10 (inclusive)
characters.

\ The backslash is used as an escape character for metachar­


acters. It can also be used to escape non-metacharacters.

SQL Anywhere - SQL Reference


42 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Character Additional information

^ For REGEXP and REGEXP_SUBSTR, when a caret is outside a


character class, the caret matches the start of a string. For ex­
ample, '^[hc]at' matches hat and cat, but only at the be­
ginning of the string.

When used inside a character class, the following behavior ap­


plies:

REGEXP and REGEXP_SUBSTR

When the caret is the first character in a character class,


it matches anything other than the characters in the
character set. For example, REGEXP '[^abc]'
matches any character other than a, b, or c.

If the caret is not the first character inside the square


brackets, it matches a caret. For example,
REGEXP_SUBSTR '[a-e^c]' matches a, b, c, d, e,
and ^.
SIMILAR TO

For SIMILAR TO, the caret is treated as a subtraction op­


erator. For example, SIMILAR TO '[a-e^c]'
matches a, b, d, and e.

$ When used with REGEXP and REGEXP_SUBSTR, matches the


end of a string. For example, REGEXP 'cat$' matches cat,
but not catfish.

. When used with REGEXP and REGEXP_SUBSTR, matches any


single character. For example, REGEXP 'a.cd' matches
any string of four characters that starts with a and ends with
cd.

When used with SIMILAR TO, matches a period (.).

: The colon is used within a character set to specify a subchar­


acter class. For example, '[[:alnum:]]'.

Related Information

LIKE, REGEXP, and SIMILAR TO search conditions [page 62]


Regular expressions examples [page 51]
REGEXP_SUBSTR function [String] [page 487]
Regular expressions: Special sub-character classes [page 44]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 43
1.1.6.7.2 Regular expressions: Special sub-character classes

Sub-character classes are special character classes embedded within a larger character class.

In addition to custom character classes where you define the set of characters to match (for example, [abxq4]
limits the set of matching characters to a, b, x, q, and 4), SQL Anywhere supports sub-character classes such as
most of the POSIX character classes. For example, [[:alpha:]] represents the set of all upper- and lowercase
letters.

The REGEXP search condition and the REGEXP_SUBSTR function support all the syntax conventions in the table
below, but the SIMILAR TO search expression does not. Conventions supported by SIMILAR TO have a Y in the
SIMILAR TO column.

In REGEXP and when using the REGEXP_SUBSTR function, sub-character classes can be negated using a caret.
For example, [[:^alpha:]] matches the set of all characters except alpha characters.

Sub-character class Additional information SIMILAR TO

[:alpha:] Matches upper- and lowercase alpha­ Y

betic characters in the current collation.


For example, '[0-9]{3}
[[:alpha:]]{2}' matches three
digits, followed by two letters.

[:alnum:] Match digits, and upper- and lowercase Y

alphabetic characters in the current col­


lation. For example, '[[:alnum:]]+'
matches a string of one or more letters
and numbers.

[:digit:] Match digits in the current collation. For Y

example, '[[:digit:]-]+'
matches a string of one or more digits or
dashes. Likewise, '[^[:digit:]-]
+' matches a string of one or more
characters that are not digits or dashes.

[:lower:] Match lowercase alphabetic characters Y

in the current collation. For example,


'[[:lower:]]' does not match A
because A is uppercase.

[:space:] Match a single blank (' '). For example, Y

the following statement searches Con­


tacts.City for any city with a two word
name:

SELECT City
FROM GROUPO.Contacts
WHERE City REGEXP
'.*[[:space:]].*';

SQL Anywhere - SQL Reference


44 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Sub-character class Additional information SIMILAR TO

[:upper:] Match uppercase alphabetic characters Y

in the current collation. For example,


'[[:upper:]ab]' matches one of:
any uppercase letter, a, or b.

[:whitespace:] Match a whitespace character such as Y

space, tab, form feed, and carriage re­


turn.

[:ascii:] Match any seven-bit ASCII character (or­


dinal value between 0 and 127).

[:blank:] Match a blank space, or a horizontal tab.

[[:blank:]] is equivalent to [ \t].

[:cntrl:] Match ASCII characters with an ordinal


value of less than 32, or character value
127 (control characters). Control charac­
ters include newline, form feed, back­
space, and so on.

[:graph:] Match printed characters.

[[:graph:]] is equivalent to
[[:alnum:][:punct:]].

[:print:] Match printed characters and spaces.

[[:print:]] is equivalent to
[[:graph:][:whitespace:]].

[:punct:] Match one of: !"#$%&'()*+,-./:;<=>?


@[\]^_`{|}~.

The [:punct:] sub-character class


may not include non-ASCII punctuation
characters available in the current colla­
tion.

[:word:] Match alphabetic, digit, or underscore


characters in the current collation.

[[:word:]] is equivalent to
[[:alnum:]_].

[:xdigit:] Match a character that is in the charac­


ter class [0-9A-Fa-f].

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 45
Related Information

LIKE, REGEXP, and SIMILAR TO search conditions [page 62]


Regular expressions examples [page 51]
REGEXP_SUBSTR function [String] [page 487]
Regular expressions: Metacharacters [page 40]

1.1.6.7.3 Regular expressions: Other supported syntax


conventions

The following syntax conventions are supported by the REGEXP search condition and the REGEXP_SUBSTR
function, and they assume that the backslash is the escape character. These conventions are not supported by the
SIMILAR TO search expression.

Regular expression syntax Name and meaning

\0 xxx Matches the character whose value is \0xxx, where xxx is


any sequence of octal digits, and 0 is a zero. For example,
\0134 matches a backslash.

\a Matches the bell character.

\A Used outside a character set to match the start of a string.

Equivalent to ^ used outside a character set.

\b Matches a backspace character.

\B Matches the backslash character (\).

\c X Matches a named control character. For example, \cZ for ctrl-


Z.

\d Matches a digit in the current collation. For example, the fol­


lowing statement searches Contacts.Phone for all phone
numbers that end with 00:

SELECT Surname, Surname, City, Phone


FROM GROUPO.Contacts
WHERE Phone REGEXP '\\d{8}00';

\d can be used both inside and outside character classes, and


is equivalent to [[:digit:]].

SQL Anywhere - SQL Reference


46 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Regular expression syntax Name and meaning

\D Matches anything that is not a digit. This is the opposite of \d.

\D can be used both inside and outside character classes, and


is equivalent to [^[:digit:]].

Be careful when using the negated shorthands inside square


brackets. [\D\S] is not the same as [^\d\s]. The latter
matches any character that is not a digit or whitespace. So it
matches x, but not 8. The former, however, matches any char­
acter that is either not a digit, or is not whitespace. Because a
digit is not whitespace, and whitespace is not a digit, [\D\S]
matches any character, digit, whitespace or otherwise.

\e Matches the escape character.

\E Ends the treatment of metacharacters as non-metacharact­


ers, initiated by a \Q.

\f Matches a form feed.

\n Matches a new line.

\Q Treat all metacharacters as non-metacharacters, until \E is


encountered. For example, \Q[$\E is equivalent to \[\$.

\r Matches a carriage return.

\s Matches a space or a character treated as whitespace. For ex­


ample, the following statement returns all product names
from Products.ProductName that have at least one space in
the name:

SELECT Name
FROM GROUPO.Products
WHERE Name REGEXP '.*\\s.*'

\s can be used both inside and outside character classes, and


is equivalent to [[:whitespace:]].

\S Matches a non-whitespace character. This is the opposite of


\s, and is equivalent to [^[:whitespace:]].

\S can be used both inside and outside character classes.

Be careful when using the negated shorthands inside square


brackets. [\D\S] is not the same as [^\d\s]. The latter
matches any character that is not a digit or whitespace. So it
matches x, but not 8. The former, however, matches any char­
acter that is either not a digit, or is not whitespace. Because a
digit is not whitespace, and whitespace is not a digit, [\D\S]
matches any character, digit, whitespace or otherwise.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 47
Regular expression syntax Name and meaning

\t Matches a horizontal tab.

\v Matches a vertical tab.

\w Matches an alphabetic character, digit, or underscore in the


current collation. For example, the following statement re­
turns all surnames from Contacts.Surname that are exactly
seven alpha-numeric characters in length:

SELECT Surname
FROM GROUPO.Contacts
WHERE Surname REGEXP '\\w{7}';

\w can be used both inside and outside character classes.

Equivalent to [[:alnum:]_]..

\W Matches anything that is not an alphabetic character, digit, or


underscore in the current collation. This is the opposite of \w,
and is equivalent to [^[:alnum:]_].

This regular expression can be used both inside and outside


character classes

\x hh Matches the character whose value is 0xhh, where hh is, at


most, two hex digits. For example, \x2D is equivalent to a hy­
phen.

Equivalent to \x{hh}.

\x{ hhh } Matches the character whose value is 0xhhh, where hhh is, at
most, eight hex digits.

\z Matches the position (not character) at the end of the string.

Equivalent to $.

\Z Matches the position (not character) at the end of the string.

Equivalent to $.

Related Information

LIKE, REGEXP, and SIMILAR TO search conditions [page 62]


Regular expressions examples [page 51]
REGEXP_SUBSTR function [String] [page 487]
Regular expressions: Metacharacters [page 40]
Regular expressions: Special sub-character classes [page 44]

SQL Anywhere - SQL Reference


48 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.1.6.7.4 Regular expressions: Assertions

Assertions test whether a condition is true, and affect the position in the string where matching begins. Assertions
do not return characters; the assertion pattern is not included in the final match.

These assertions are supported by the REGEXP search condition and the REGEXP_SUBSTR function. These
conventions are not supported by the SIMILAR TO search expression.

Lookahead and lookbehind assertions can be useful with REGEXP_SUBSTR when trying to split a string. For
example, you can return the list of street names (without the street numbers) in the Address column of the
Customers table by executing the following statement:

SELECT REGEXP_SUBSTR( Street, '(?<=^\\S+\\s+).*$' )


FROM GROUPO.Customers;

Another example is using a regular expression to verify that a password conforms to certain rules. You could use a
zero width assertion similar to the following:

IF password REGEXP '(?=.*[[:digit:]])(?=.*[[:alpha:]].*[[:alpha:]])[[:word:]]


{4,12}' THEN
MESSAGE 'Password conforms' TO CLIENT;
ELSE
MESSAGE 'Password does not conform' TO CLIENT;
END IF

The password is valid when the following are true:

● password has at least one digit (zero width positive assertion with [[:digit:]])
● password has at least two alphabetic characters (zero width positive assertion with [[:alpha:]].*[[:alpha:]])
● password contains only alpha-numeric or underscore characters ([[:word:]])
● password is at least 4 characters, and at most 12 characters ({4,12})

The following table contains supported assertions:

Syntax Meaning

(?= pattern ) Positive lookahead zero-width assertion

Looks to see if the current position in the string is imme­


diately followed by an occurrence of pattern, without
pattern becoming part of the match string. 'A(?=B)'
matches an A that is followed by a B, without making the
B part of the match.

For example, SELECT REGEXP_SUBSTR( 'in new


york city', 'new(?=\\syork)'); returns the
substring 'new' since it is immediately followed by ' york'
(note the space before york).

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 49
Syntax Meaning

(?! pattern ) Negative lookahead zero-width assertions

Looks to see if the current position in the string is not im­


mediately followed by an occurrence of pattern, without
pattern becoming part of the match string. So, 'A(?!
B)' matches an A that is not followed by a B.

For example,SELECT REGEXP_SUBSTR('new


jersey', 'new(?!\\syork)'); returns the sub­
string new.

(?<= pattern ) Positive lookbehind zero-width assertions

Looks to see if the current position in the string is imme­


diately preceded by an occurrence of pattern, without
pattern becoming part of the match string. So, '(?
<=A)B' matches a B that is immediately preceded by an
A, without making A part of the match.

For example, SELECT REGEXP_SUBSTR('new


york', '(?<=new\\s)york'); returns the sub­
string york.

(?<! pattern ) Negative lookbehind zero-width assertions

Looks to see if the current position in the string is not im­


mediately preceded by an occurrence of pattern, with­
out pattern becoming part of the match string.

For example, SELECT REGEXP_SUBSTR('about


york', '(?<!new\\s)york'); returns the sub­
string york.

(?> pattern ) Possessive local subexpression

Matches only the largest prefix of the remaining string


that matches pattern.

For example, in 'aa' REGEXP '(?>a*)a', (?>a*)


matches (and consumes) the aa, and never just the lead­
ing a. As a result, 'aa' REGEXP '(?>a*)a' evalu­
ates to false.

SQL Anywhere - SQL Reference


50 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Syntax Meaning

(?: pattern ) Non-capturing block

This is functionally equivalent to just pattern, and is


provided for compatibility.

For example, in 'bb' REGEXP '(?:b*)b', (?:b*)


matches (and consumes) the bb. However, unlike pos­
sessive local subexpression, the last b in bb is given up to
allow the whole match to succeed (that is, to allow the
matching to the b found outside the non-capturing
block).

Likewise, 'a(?:bc|b)c' matches abcc, and abc. In


matching abc, backtracking on the final c in bc takes
place so that the c outside the group can be used to make
the match successful.

(?# text ) Used for comments. The content of text is ignored.

Related Information

LIKE, REGEXP, and SIMILAR TO search conditions [page 62]


Regular expressions examples [page 51]
REGEXP_SUBSTR function [String] [page 487]
Regular expressions: Metacharacters [page 40]
Regular expressions: Special sub-character classes [page 44]

1.1.6.8 Regular expressions examples

There are many helpful examples of regular expressions you can refer to.

All examples work for REGEXP and some also work for SIMILAR TO, as noted in the Example column. Results vary
depending on the search condition you use for searching. For those that work with SIMILAR TO, results can vary
further depending on case and accent sensitivity.

Backslashes should be doubled if the examples are used in literal strings (for example, '.+@.+\\..+')

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 51
Example Sample matches

Credit Card Numbers (REGEXP only): Matches (Visa): 4123 6453 2222 1746

Visa: Non-Matches (Visa):

4[0-9]{3}\s[0-9]{4}\s[0-9]{4}\s[0-9]{4} 3124 5675 4400 4567, 4123-6453-2222-1746

Similarly, MasterCard matches a set of 16 numbers, starting


MasterCard:
with 5, with a space between each subset of four numbers.
American Express and Discover are the same, but must start
5[0-9]{3}\s[0-9]{4}\s[0-9]{4}\s[0-9]{4}
with 37 and 6011 respectively.
American Express:

37[0-9]{2}\s[0-9]{4}\s[0-9]{4}\s[0-9]
{4}

Discover:

6011\s[0-9]{4}\s[0-9]{4}\s[0-9]{4}

Dates (REGEXP and SIMILAR TO): Matches: 31/04/1999, 15/12/4567

([0-2][0-9]|30|31)/(0[1-9]|1[0-2])/ Non-Matches: 31/4/1999, 31/4/99, 1999/04/19,


[0-9]{4} 42/67/25456

Windows absolute paths (REGEXP only): Matches: \\server\share\file

([A-Za-z]:|\\\\)\\\\[[:alnum:] Non-Matches: \directory\directory2, /directory2


[:whitespace:].!"#$%&''()+,.\\\\;=@\
[^_`{}~\\]-]*

Email Addresses (REGEXP only): Matches: [email protected], [email protected]

[[:word:]\-.]+@[[:word:]\-.]+\. Non-Matches: abc@dummy, ab*[email protected]


[[:alpha:]]{2,3}

Email Addresses (REGEXP only): Matches: *@[email protected], __1234^


%@@abc.def.ghijkl
.+@.+\..+
Non-Matches: abc.123.*&ca, ^%abcdefg123

HTML Hexadecimal Color Codes (REGEXP and SIMILAR Matches: AB1234, CCCCCC, 12AF3B
TO):
Non-Matches: 123G45, 12-44-CC

[A-F0-9]{6}

HTML Hexadecimal Color Codes (REGEXP only): Matches: AB 11 00, CC 12 D3

[A-F0-9]{2}\s[A-F0-9]{2}\s[A-F0-9]{2} Non-Matches: SS AB CD, AA BB CC DD, 1223AB

SQL Anywhere - SQL Reference


52 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Example Sample matches

IP Addresses (REGEXP only): Matches: 10.25.101.216

((2(5[0-5]|[0-4][0-9])|1([0-9][0-9])| Non-Matches: 0.0.0, 256.89.457.02


([1-9][0-9])|[0-9])\.){3}(2(5[0-5]|
[0-4][0-9])|1([0-9][0-9])|([1-9][0-9])|
[0-9])

Java Comments (REGEXP only): Matches Java comments that are between /* and */, or one
line comments prefaced by //.
/\*.*\*/|//[^\n]*
Non-Matches: a=1

Money (REGEXP only): Matches: $1.00, -$97.65

(\+|-)?\$[0-9]*\.[0-9]{2} Non-Matches: $1, 1.00$, $-75.17

Positive, negative numbers, and decimal values (REGEXP Matches: +41, -412, 2, 7968412, 41, +41.1, -3.141592653
only):
Non-Matches: ++41, 41.1.19, -+97.14

(\+|-)?[0-9]+(\.[0-9]+)?

Passwords (REGEXP and SIMILAR TO): Matches: abcd, 1234, A1b2C3d4, 1a2B3

[[:alnum:]]{4,10} Non-Matches: abc, *ab12, abcdefghijkl

Passwords (REGEXP only): Matches: AB_cd, A1_b2c3, a123_

[a-zA-Z]\w{3,7} Non-Matches: *&^g, abc, 1bcd

Phone Numbers (REGEXP and SIMILAR TO): Matches: 519-883-6898, 519 888 6898

([2-9][0-9]{2}-[2-9][0-9]{2}-[0-9]{4})| Non-Matches: 888 6898, 5198886898, 519 883-6898


([2-9][0-9]{2}\s[2-9][0-9]{2}\s[0-9]
{4})

Sentences (REGEXP only): Matches: Hello, how are you?

[A-Z0-9].*(\.|\?|!) Non-Matches: i am fine

Sentences (REGEXP only): Matches: Hello, how are you?

[[:upper:]0-9].*[.?!] Non-Matches: i am fine

Social Security Numbers (REGEXP and SIMILAR TO): Matches: 123-45-6789

[0-9]{3}-[0-9]{2}-[0-9]{4} Non-Matches:123 45 6789, 123456789, 1234-56-7891

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 53
Example Sample matches

URLs (REGEXP only): Matches: http://www.sample.com, www.sample.com

(http://)?www\.[a-zA-Z0-9]+\.[a-zA-Z] Non-Matches: http://sample.com, http://


{2,3} www.sample.comm

Related Information

Regular expressions syntax [page 39]


LIKE, REGEXP, and SIMILAR TO search conditions [page 62]

1.1.6.9 Compatibility of expressions

SQL Anywhere uses the ANSI/ISO SQL Standard convention whereby strings enclosed in apostrophes are
constant expressions, and strings enclosed in quotation marks (double quotes) are delimited identifiers (names
for database objects).

In this section:

The quoted_identifier option [page 54]


You can use the quoted_identifier option to control the interpretation of delimited strings. By default, the
quoted_identifier option is set to On.

1.1.6.9.1 The quoted_identifier option

You can use the quoted_identifier option to control the interpretation of delimited strings. By default, the
quoted_identifier option is set to On.

You cannot use SQL reserved words as identifiers if the quoted_identifier option is Off.

Setting the option

The following statement changes the setting of the quoted_identifier option to On:

SET quoted_identifier On;

The following statement changes the setting of the quoted_identifier option to Off:

SET quoted_identifier Off;

SQL Anywhere - SQL Reference


54 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Compatible interpretation of delimited strings

You can choose to use either the ANSI/ISO SQL Standard or the default Transact-SQL convention as long as the
quoted_identifier option is set to the same value in each DBMS.

Example
If you choose to operate with the quoted_identifier option On (the default setting), then the following
statements involving the SQL keyword user are valid for both DBMSs.

CREATE TABLE "user" ( col1 char(5) )


go
INSERT "user" ( col1 )
VALUES ( 'abcde' )
go

If you choose to operate with the quoted_identifier option off then the following statement is valid for both
DBMSs. In the following example, Chin is a string and not an identifier.

SELECT *
FROM GROUPO.Employees
WHERE Surname = "Chin"
go

Related Information

Reserved words [page 6]

1.1.7 Search conditions

A search condition is the criteria specified for a WHERE clause, a HAVING clause, a CHECK clause, an ON phrase
in a join, or an IF expression. A search condition is also called a predicate.

Syntax

search-condition :
expression comparison-operator expression
| expression comparison-operator { [ ANY | SOME ] | ALL } ( subquery )
| expression IS [ NOT ] DISTINCT FROM expression
| expression IS [ NOT ] NULL
| expression [ NOT ] BETWEEN expression AND expression
| expression [ NOT ] LIKE pattern [ ESCAPE expression ]
| expression [ NOT ] SIMILAR TO pattern [ ESCAPE escape-expression ]
| expression [ NOT ] REGEXP pattern [ ESCAPE escape-expression ]
| expression [ NOT ] IN ( expression , ... )
| ( query-expression )
| NOT search-condition
| CONTAINS (column-name [,... ] , query-string )
| EXISTS ( query-expression )
| search-condition [ { AND | OR } search-condition ] [ ... ]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 55
| ( search-condition )
| ( search-condition , estimate )
| search-condition IS [ NOT ] { TRUE | FALSE | UNKNOWN }
| expression IS [ NOT ] OF ( type-name [ ONLY ],... )
| trigger-operation

comparison-operator :
=
| >
| <
| >=
| <=
| <>
| !=
| !<
| !>

trigger-operation :
INSERTING
| DELETING
| UPDATING [ ( column-name-string ) ]
| UPDATE( column-name )

Parameters

● ALL search condition


● ANY and SOME search conditions
● IS [NOT] DISTINCT FROM search condition
● BETWEEN search condition
● CONTAINS search condition
● EXISTS search condition
● LIKE search condition
● SIMILAR TO search condition
● REGEXP search condition
● IS OF type-expression, and IS NOT OF type-expression
This type predicate was added for support of spatial geometries, but it can be used for any existing data type
as well.

Remarks

Search conditions are used either to choose a subset of the rows from a table, or in a control statement such as
an IF statement to determine control of flow.

In SQL, every condition evaluates as one of TRUE, FALSE, or UNKNOWN. This is called three-valued logic. The
result of a comparison is UNKNOWN if either value being compared is the NULL value.

Rows satisfy a search condition only if the result of the condition is TRUE. Rows for which the condition is
UNKNOWN or FALSE do not satisfy the search condition.

SQL Anywhere - SQL Reference


56 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Subqueries form an important class of expression that is used in many search conditions.

The LIKE, SIMILAR TO, and REGEXP search conditions are very similar.

Prerequisites

Must be connected to the database.

Side effects

None.

In this section:

Subqueries in search conditions [page 58]


Subqueries that return exactly one column and either zero or one row can be used in any SQL statement
wherever a column name could be used, including in the middle of an expression.

ALL search condition [page 59]


Use the ALL search condition to compare a value to all values in a set.

ANY and SOME search conditions [page 60]


Use the ANY or SOME search condition to compare a value to any value in a set.

IS DISTINCT FROM and IS NOT DISTINCT FROM search conditions [page 61]
Use the IS DISTINCT FROM and IS NOT DISTINCT FROM search conditions to evaluate whether a value is
distinct from values in a set.

BETWEEN search condition [page 62]


Use the BETWEEN search condition to evaluate whether a value is between values in another set.

LIKE, REGEXP, and SIMILAR TO search conditions [page 62]


The REGEXP, LIKE, and SIMILAR TO search conditions are similar in that they all attempt to match a
pattern to a string. Also, all three attempt to match an entire string, not a substring within the string.

IN search condition [page 72]


Use the IN search condition to evaluate whether a value is found in a set.

CONTAINS search condition [page 73]


Use the CONTAINS search condition to evaluate whether a value is contained in a set.

EXISTS search condition [page 80]


Use the EXISTS search condition to evaluate whether a value is found in a set.

IS NULL and IS NOT NULL search conditions [page 81]


Use the IS NULL search condition to evaluate whether a value in a set is NULL.

Truth value search conditions [page 81]


Use the IS TRUE search condition to evaluate whether a condition evaluates to a specified value.

Three-valued logic [page 82]


The following tables display how the AND, OR, NOT, and IS logical operators of SQL work in three-valued
logic.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 57
Explicit selectivity estimates [page 83]
The database server uses statistical information to determine the most efficient strategy for executing
each statement.

Related Information

Expressions in SQL statements [page 32]


LIKE search condition [page 64]
SIMILAR TO search condition [page 70]
REGEXP search condition [page 69]
NULL special value [page 100]

1.1.7.1 Subqueries in search conditions

Subqueries that return exactly one column and either zero or one row can be used in any SQL statement wherever
a column name could be used, including in the middle of an expression.

For example, expressions can be compared to subqueries in comparison conditions as long as the subquery does
not return more than one row. If the subquery (which must have exactly one column) returns one row, then the
value of that row is compared to the expression. If a subquery returns no rows, the value of the subquery is NULL.

Subqueries that return exactly one column and any number of rows can be used in IN, ANY, ALL, and SOME
search conditions. Subqueries that return any number of columns and rows can be used in EXISTS search
conditions.

Standards

ANSI/ISO SQL Standard

Core Feature.

Related Information

Comparison operators [page 15]

SQL Anywhere - SQL Reference


58 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.1.7.2 ALL search condition

Use the ALL search condition to compare a value to all values in a set.

Syntax

expression comparison-operator ALL ( subquery )

comparison-operator:
=
| >
| <
| >=
| <=
| <>
| !=
| !<
| !>

Remarks

With the ALL search condition, if the value of subquery result set is the empty set, the search condition evaluates
to TRUE. Otherwise, the search condition evaluates to TRUE, FALSE, or UNKNOWN, depending on the value of
expression, and the result set returned by the subquery, as follows:

If the expression value is... and the result set returned by the sub­ or the result set returned by the sub­
query contains at least one NULL, query contains no NULLs, then...
then...

NULL UNKNOWN UNKNOWN

not NULL If there exists at least one value in the If there exists at least one value in the
subquery result set for which the com­ subquery result set for which the com­
parison with the expression value is parison with the expression value is
FALSE, then the search condition evalu­ FALSE, then the search condition evalu­
ates to FALSE. Otherwise, the search ates to FALSE. Otherwise, the search
condition evaluates to UNKNOWN. condition evaluates to TRUE.

Standards

ANSI/ISO SQL Standard

Core Feature.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 59
1.1.7.3 ANY and SOME search conditions

Use the ANY or SOME search condition to compare a value to any value in a set.

Syntax

expression comparison-operator { ANY | SOME }( subquery )

comparison-operator:
=
| >
| <
| >=
| <=
| <>
| !=
| !<
| !>

Remarks

The keywords ANY and SOME are synonymous.

With the ANY and SOME search conditions, if the subquery result set is the empty set, the search condition
evaluates to FALSE. Otherwise, the search condition evaluates to TRUE, FALSE, or UNKNOWN, depending on the
value of expression, and the result set returned by the subquery, as follows:

If the expression value is... and the result set returned by the sub­ or the result set returned by the sub­
query contains at least one NULL, query contains no NULLs, then...
then...

NULL UNKNOWN UNKNOWN

not NULL If there exists at least one value in the If there exists at least one value in the
subquery result set for which the com­ subquery result set for which the com­
parison with the expression value is parison with the expression value is
TRUE, then the search condition evalu­ TRUE, then the search condition evalu­
ates to TRUE. Otherwise, the search ates to TRUE. Otherwise, the search
condition evaluates to UNKNOWN. condition evaluates to FALSE.

An ANY or SOME search condition with an equality operator, evaluates to TRUE if expression is equal to any of
the values in the result of the subquery, and FALSE if the value of the expression is not NULL, does not equal any
of the values in the result of the subquery, and the result set doesn't contain NULLs.

Note
The usage of = ANY or = SOME is equivalent to using the IN keyword.

SQL Anywhere - SQL Reference


60 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Standards

ANSI/ISO SQL Standard

Core Feature.

1.1.7.4 IS DISTINCT FROM and IS NOT DISTINCT FROM


search conditions

Use the IS DISTINCT FROM and IS NOT DISTINCT FROM search conditions to evaluate whether a value is distinct
from values in a set.

Syntax

expression1 IS [ NOT ] DISTINCT FROM expression2

Remarks

The IS DISTINCT FROM and IS NOT DISTINCT FROM search conditions are sargable and evaluate to TRUE or
FALSE.

The IS NOT DISTINCT FROM search condition evaluates to TRUE if expression1 is equal to expression2, or if
both expressions are NULL. This is equivalent to a combination of two search conditions, as follows:

(expression1 = expression2) IS TRUE OR ( expression1 IS NULL AND expression2 IS


NULL )

The IS DISTINCT FROM syntax reverses the meaning. That is, IS DISTINCT FROM evaluates to TRUE if
expression1 is not equal to expression2, and at least one of the expressions is not NULL. This is equivalent to
the following:

NOT(( expression1 = expression2) IS TRUE OR ( expression1 IS NULL AND expression2


IS NULL ))

Standards

ANSI/ISO SQL Standard

The IS [NOT] DISTINCT FROM predicate is defined in the ANSI/ISO SQL Standard. The IS DISTINCT FROM
predicate is Feature T151, "DISTINCT predicate". The IS NOT DISTINCT FROM predicate is Feature T152,
"DISTINCT predicate with negation".

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 61
1.1.7.5 BETWEEN search condition

Use the BETWEEN search condition to evaluate whether a value is between values in another set.

Syntax

expression [ NOT ] BETWEEN start-expression AND end-expression

Remarks

The BETWEEN search condition can evaluate as TRUE, FALSE, or UNKNOWN. Without the NOT keyword, the
search condition evaluates as TRUE if expression is between start-expression and end-expression. The
NOT keyword reverses the meaning of the search condition but leaves UNKNOWN unchanged.

The BETWEEN search condition is equivalent to a combination of two inequalities:

[ NOT ] ( expression >= start-expression AND expression <= end-expression )

Standards

ANSI/ISO SQL Standard

Core Feature.

1.1.7.6 LIKE, REGEXP, and SIMILAR TO search conditions

The REGEXP, LIKE, and SIMILAR TO search conditions are similar in that they all attempt to match a pattern to a
string. Also, all three attempt to match an entire string, not a substring within the string.

The basic syntax for all three search conditions is similar:

expression search-condition pattern

LIKE, REGEXP, and SIMILAR TO: Differences in pattern definition

● REGEXP supports a superset of regular expression syntax supported by SIMILAR TO. In addition, for
compatibility with other products, the REGEXP search condition supports several syntax extensions. Also,
REGEXP and SIMILAR TO have a different default escape character and process the characters underscore
( _ ), percent ( % ), and caret ( ^ ) differently. REGEXP behavior matches closely with Perl 5 (except where
Perl syntax and operators are not supported).

SQL Anywhere - SQL Reference


62 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
● LIKE syntax for pattern is simple and supports a small set of wildcards, but does not support the full regular
expression syntax.
● SIMILAR TO syntax for pattern allows a robust pattern matching using the regular expression syntax
defined in the ANSI/ISO SQL standard.

LIKE, REGEXP, and SIMILAR TO: Differences in character comparisons

When performing comparisons, REGEXP behavior is different from LIKE and SIMILAR TO. For REGEXP
comparisons, the database server uses code point values in the database character set for comparisons. This is
consistent with other regular expression implementations such as Perl.

For LIKE and SIMILAR TO, the database server uses the equivalence and sort order in the database collation for
comparisons. This is consistent with how the database evaluates comparison operators such as > and =.

The difference in character comparison methods means that results for matching and range evaluation for
REGEXP and LIKE/SIMILAR differ as well.

Differences in matching

Since REGEXP uses code point values, it only matches a literal in a pattern if it is the exact same character.
REGEXP matching is therefore not impacted by such things as database collation, case-sensitivity, or accent
sensitivity. For example, 'A' could never be returned as a match for 'a'.

Since LIKE and SIMILAR TO use the database collation, results are impacted by case- and accent-sensitivity
when determining character equivalence. For example, if the database collation is case- and accent-
insensitive, matches are case- and accent-insensitive. So, an 'A' could be returned as a match for 'a'.
Differences in range evaluation

Since REGEXP uses code points for range evaluation, a character is considered to be in the range if its code
point value is equal to, or between, the code point values for the start and end of the range. For example, the
comparison x REGEXP '[A-C]', for the single character x, is equivalent to CAST(x AS BINARY) >=
CAST(A AS BINARY) AND CAST(x AS BINARY) <= CAST(C AS BINARY).

Since LIKE and SIMILAR TO use the collation sort order for range evaluation, a character is considered to be
in the range if its position in the collation is the same as, or between, the position of the start and end
characters for the range. For example, the comparison x SIMILAR TO '[A-C]' (where x is a single
character) is equivalent to x >= A AND x <= C, and the comparison operators are evaluated using the
collation sort ordering.

The following table shows the set of characters included in the range '[A-C]' as evaluated by LIKE, SIMILAR
TO, and REGEXP. Both databases use the 1252LATIN1 collation, but the first database is case-insensitive,
while the second one is case sensitive.

LIKE/SIMILAR TO '[A-C]' REGEXP '[A-C]'

demo.db (case-insensitive) A,B,C,a,b,c,ª,À,Á,Â,Ã,Ä,Å,Æ,Ç,à,á,â,ã,ä A, B, C


,å,æ,ç

charsensitive.db (case-sensi­ A,B,C,b,c,À,Á,Â,Ã,Ä,Å,Æ,Ç,ç A, B, C


tive)

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 63
The following can be observed in the results:

● LIKE and SIMILAR TO include accented characters in the range.


● LIKE and SIMILAR TO include different characters depending on database case-sensitivity. Specifically,
they include any lowercase letters found within the range, which you may not have anticipated when
searching on a case-sensitive database.
Similarly, on a case-sensitive database, some characters included in the range might appear to be
inconsistent. For example, SIMILAR TO '[A-C]' on a case-sensitive database includes A, b, B, c, C but
not a because a occurs before the uppercase A in the sort order.
● REGEXP returns only A, B, C regardless of database case sensitivity. If you want the range to include
lowercase letters, you must add them to the range definition. For example, REGEXP '[a-cA-C]'.
● the REGEXP set of characters does not change, regardless of database case-sensitivity.

Even though your database uses a different collation, or has different case- or accent-sensitivity settings than
the examples above, you can perform a similar test to see what is returned by LIKE, SIMILAR TO, or REGEXP
by connecting to the database and executing any of these statements:

SELECT CHAR( row_num ) FROM RowGenerator WHERE CHAR( row_num ) LIKE '[A-C]';
SELECT CHAR( row_num ) FROM RowGenerator WHERE CHAR( row_num ) REGEXP '[A-C]';
SELECT CHAR( row_num ) FROM RowGenerator WHERE CHAR( row_num ) SIMILAR TO '[A-
C]';

In this section:

LIKE search condition [page 64]


Use the LIKE search condition to evaluate whether a value is similar to values in a set.

REGEXP search condition [page 69]


Matches a pattern against a string.

SIMILAR TO search condition [page 70]


Matches a pattern against a string.

Related Information

Regular expressions overview [page 38]


Regular expressions syntax [page 39]
Regular expressions examples [page 51]

1.1.7.6.1 LIKE search condition


Use the LIKE search condition to evaluate whether a value is similar to values in a set.

Syntax
The syntax for the LIKE search condition is as follows:

expression [ NOT ] LIKE pattern [ ESCAPE escape-character ]

SQL Anywhere - SQL Reference


64 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Parameters

expression

The string to be searched.


pattern

The pattern to search for within expression.


escape-character

The character to use to escape special characters such as underscores and percent signs.

Remarks

The LIKE search condition attempts to match expression with pattern and evaluates to TRUE, FALSE, or
UNKNOWN.

The search condition evaluates to TRUE if expression matches pattern (assuming NOT was not specified). If
either expression or pattern is the NULL value, the search condition evaluates to UNKNOWN. The NOT
keyword reverses the meaning of the search condition, but leaves UNKNOWN unchanged.

expression is interpreted as a CHAR or NCHAR string. The entire contents of expression is used for matching.
Similarly, pattern is interpreted as a CHAR or NCHAR string and can contain any number of the supported
wildcards from the following table:

Wildcard Matches

_ (underscore) Any one character. For example, a_ matches ab and ac, but
not a.

% (percent) Any string of zero or more characters. For example, bl%


matches bl and bla.

[] Any single character in the specified range or set. For exam­


ple, T[oi]m matches Tom or Tim.

[^] Any single character not in the specified range or set. For ex­
ample, M[^c] matches Mb and Md, but not Mc.

All other characters must match exactly.

For example, the following search condition returns TRUE for any row where name starts with the letter a and has
the letter b as its second last character.

... name LIKE 'a%b_'

If escape-character is specified, it must evaluate to a single-byte CHAR or NCHAR character. The escape
character can precede a percent, an underscore, a left square bracket, or another escape character in the
pattern to prevent the special character from having its special meaning. When escaped in this manner, a
percent matches a percent, and an underscore matches an underscore.

Patterns up to 126 bytes in length are supported.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 65
Different ways to use the LIKE search condition

To search for Example Additional information

One of a set of characters LIKE 'sm[iy]th' A set of characters to look for is speci­
fied by listing the characters inside
square brackets. In this example, the
search condition matches smith and
smyth.

One of a range of characters LIKE '[a-r]ough' A range of characters to look for is speci­
fied by giving the ends of the range in­
side square brackets, separated by a hy­
phen. In this example, the search condi­
tion matches bough and rough, but not
tough.

The range of characters [a-z] is inter­


preted as "greater than or equal to a,
and less than or equal to z", where the
greater than and less than operations
are carried out within the collation of the
database.

The lower end of the range must pre­


cede the higher end of the range. For ex­
ample, [z-a] does not match anything
because no character matches the [z-a]
range.

Ranges and sets combined ... LIKE '[a-rt]ough' You can combine ranges and sets within
square brackets. In this example, ...
LIKE '[a-rt]ough' matches
bough, rough, and tough.

The pattern [a-rt] is interpreted as ex­


actly one character that is either in the
range a to r inclusive, or is t.

One character not in a range ... LIKE '[^a-r]ough' The caret character (^) is used to spec­
ify a range of characters that is excluded
from a search. In this example, LIKE
'[^a-r]ough' matches the string
tough, but not the strings rough or
bough.

The caret negates the rest of the con­


tents of the brackets. For example, the
bracket [^a-rt] is interpreted as exactly
one character that is not in the range a
to r inclusive, and is not t.

SQL Anywhere - SQL Reference


66 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
To search for Example Additional information

Search patterns with trailing blanks '90 ', '90[ ]' and '90_' When your search pattern includes trail­
ing blanks, the database server matches
the pattern only to values that contain
blanks. It does not blank pad strings. For
example, the patterns '90 ', '90[ ]', and
'90_' match the expression '90 ', but do
not match the expression '90', even if
the value being tested is in a CHAR or
VARCHAR column that is three or more
characters in width.

Special cases of ranges and sets

Any single character in square brackets means that character. For example, [a] matches just the character a.
[^] matches just the caret character, [%] matches just the percent character (the percent character does not act
as a wildcard in this context), and [_] matches just the underscore character. Also, [[] matches just the
character [.

Other special cases are as follows:

● The pattern [a-] matches either of the characters a or -.


● The pattern [] is never matched and always returns no rows.
● The patterns [ or [abp-q return syntax errors because they are missing the closing bracket.
● You cannot use wildcards inside square brackets. The pattern [a%b] finds one of a, %, or b.
● You cannot use the caret character to negate ranges except as the first character in the bracket. The pattern
[a^b] finds one of a, ^, or b.

Case sensitivity and how comparisons are performed

If the database collation is case sensitive, the search condition is also case sensitive. To perform a case insensitive
search with a case sensitive collation, you must include upper and lower characters. For example, the following
search condition evaluates to true for the strings Bough, rough, and TOUGH:

LIKE '[a-zA-Z][oO][uU][gG][hH]'

Comparisons are performed character by character, unlike the equivalence (=) operator and other operators
where the comparison is done string by string. For example, when a comparison is done in a UCA collation (CHAR
or NCHAR with the collation set to UCA), 'Æ'='AE' is true, but 'Æ' LIKE 'AE' is false.

For a character-by-character comparison to match, each single character in the expression being searched must
match a single character (using the collation's character equivalence), or a wildcard in the LIKE expression.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 67
National character (NCHAR) support

LIKE search conditions can be used to compare CHAR and NCHAR strings. In this case, character set conversion
is performed so that the comparison is done using a common data type. Then, a character-by-character
comparison is performed.

You can specify expression or pattern as an NCHAR string literal by prefixing the quoted value with N (for
example, expression LIKE N'pattern'). You can also use the CAST function to cast the pattern to CHAR or
NCHAR (for example, expression LIKE CAST(pattern AS datatype).

Blank padded databases

The semantics of a LIKE pattern does not change if the database is blank-padded since matching expression to
pattern involves a character-by-character comparison in a left-to-right fashion. No additional blank padding is
performed on the value of either expression or pattern during the evaluation. Therefore, the expression a1
matches the pattern a1, but not the patterns 'a1 ' (a1, with a space after it) or a1_.

Standards

ANSI/ISO SQL Standard

The LIKE search condition is a core feature of the ANSI/ISO SQL Standard. However, there are subtle
differences in behavior from that of the standard because the software supports case-insensitive collations
and blank-padding.

The software supports optional ANSI/ISO SQL Language Feature F281, which permits the pattern and
escape-expressions to be arbitrary expressions evaluated at execution time. Feature F281 also permits
expression to be an expression more complex than a simple column reference.

The use of character ranges and sets contained in square brackets [] is not in the standard.

The software supports ANSI/ISO SQL Feature T042, which permits LIKE search conditions to reference
string-expressions that are LONG VARCHAR values.

LIKE search conditions that specify NCHAR string expressions or patterns is optional ANSI/ISO SQL
Language Feature F421.

Related Information

Comparisons between CHAR and NCHAR [page 189]


String literals [page 13]
CAST function [Data type conversion] [page 265]
REGEXP search condition [page 69]
SIMILAR TO search condition [page 70]

SQL Anywhere - SQL Reference


68 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.1.7.6.2 REGEXP search condition

Matches a pattern against a string.

Syntax

expression [ NOT ] REGEXP pattern [ ESCAPE escape-expression ]

Parameters

expression

The string to be searched.


pattern

The regular expression to search for within expression.


escape-expression

The escape character to be used in the match. The default is the backslash character (\).

Remarks

The REGEXP search condition matches a whole string, not a substring. To match on a substring with the string,
enclose the string in wildcards that match the rest of the string (.*pattern.*). For example, SELECT ...
WHERE Description REGEXP 'car' matches only car, not sportscar. However, SELECT ... WHERE
Description REGEXP '.*car' matches car, sportscar, and any string that ends with car. Alternatively, you
can rewrite your query to make use the REGEXP_SUBSTR function, which is designed to search for substrings
within a string.

When matching against only a sub-character class, you must include the outer square brackets and the square
brackets for the sub-character class. For example, expression REGEXP '[[:digit:]]'.

Database collation and matching

REGEXP only matches a literal in a pattern if it is the exact same character (that is, they have the same code point
value). Ranges in character classes (for example, '[A-F]') only match characters that code point values greater
than or equal to the code point value of the first character in the range (A) and less than or equal to the code point
value of the second character in the range (F).

Comparisons are performed character by character, unlike the equivalence (=) operator and other operators
where the comparison is done string by string. For example, when a comparison is done in a UCA collation (CHAR
or NCHAR with the collation set to UCA), 'Æ'='AE' is true, but 'Æ' REGEXP 'AE' is false.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 69
National character (NCHAR) support

REGEXP search conditions can be used to compare CHAR and NCHAR strings. In this case, character set
conversion is performed so that the comparison is done using a common data type. Then, a code point by code
point comparison is performed.

You can specify expression or pattern as an NCHAR string literal by prefixing the quoted value with N (for
example, expression REGEXP N'pattern'). You can also use the CAST function to cast the pattern to CHAR
or NCHAR (for example, expression REGEXP CAST(pattern AS datatype).

Standards

ANSI/ISO SQL Standard

The REGEXP search condition is not in the standard, but is roughly compatible with the LIKE_REGEX search
condition of the ANSI/ISO SQL Standard, which is SQL language feature F841.

The software supports SQL Feature F281, which permits the pattern and escape-expressions to be arbitrary
expressions evaluated at execution time. Feature F281 also permits expression to be an expression more
complex than a simple column reference.

The software supports SQL Feature T042, which permits REGEXP search conditions to reference string-
expressions that are LONG VARCHAR values.

REGEXP search conditions that specify NCHAR string expressions or patterns is feature F421.

Related Information

Comparisons between CHAR and NCHAR [page 189]


String literals [page 13]
Regular expressions overview [page 38]
CAST function [Data type conversion] [page 265]
SIMILAR TO search condition [page 70]
LIKE search condition [page 64]
REGEXP_SUBSTR function [String] [page 487]
Regular expressions: Special sub-character classes [page 44]

1.1.7.6.3 SIMILAR TO search condition


Matches a pattern against a string.

Syntax

expression [ NOT ] SIMILAR TO pattern [ ESCAPE escape-expression ]

SQL Anywhere - SQL Reference


70 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Parameters

expression

The expression to be searched.


pattern

The regular expression to search for within expression.


escape-expression

The escape character to use in the match. The default escape character is the null character, which can be
specified in a string literal as '\x00'.

Regular expression syntax Meaning

\x Match anything that compares equal to x, where the escape


character is assumed to be the backslash character (\). For
example, \[ matches '['.

x Any character (other than a meta-character) matches itself.


For example, A matches 'A'.

Remarks

To match a substring with the string, use the percentage sign wildcard (%expression). For example,
SELECT ... WHERE Description SIMILAR TO 'car' matches only car, not sportscar. However,
SELECT ... WHERE Description SIMILAR TO '%car' matches car, sportscar, and any string that ends
with car.

When matching against only a sub-character class, you must include the outer square brackets, and the square
brackets for the sub-character class. For example, expression SIMILAR TO '[[:digit:]]').

Comparisons are performed character by character, unlike the equivalence (=) operator and other operators
where the comparison is done string by string. For example, when a comparison is done in a UCA collation (CHAR
or NCHAR with the collation set to UCA), 'Æ'='AE' is true, but 'Æ' SIMILAR TO 'AE' is false.

For a character-by-character comparison to match, each single character in the expression being searched must
match a single character or a wildcard in the SIMILAR TO pattern.

Database collation and matching

SIMILAR TO use the collation to determine character equivalence and evaluate character class ranges. For
example, if the database is case- and accent-insensitive, matches are case- and accent-insensitive. Ranges are
also evaluated using the collation sort order.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 71
National character (NCHAR) support

SIMILAR TO search conditions can be used to compare CHAR and NCHAR strings. In this case, character set
conversion is performed so that the comparison is done using a common data type. Then, a character-by-
character comparison is performed.

You can specify expression or pattern as an NCHAR string literal by prefixing the quoted value with N (for
example, expression SIMILAR TO N'pattern'). You can also use the CAST function to cast the pattern to
CHAR or NCHAR (for example, expression SIMILAR TO CAST(pattern AS datatype).

Standards

ANSI/ISO SQL Standard

The SIMILAR TO predicate is optional ANSI/ISO SQL Language Feature T141.

Related Information

Regular expressions overview [page 38]


Comparisons between CHAR and NCHAR [page 189]
String literals [page 13]
CAST function [Data type conversion] [page 265]
REGEXP search condition [page 69]
LIKE search condition [page 64]
REGEXP_SUBSTR function [String] [page 487]
Regular expressions: Special sub-character classes [page 44]

1.1.7.7 IN search condition

Use the IN search condition to evaluate whether a value is found in a set.

Syntax

expression [ NOT ] IN { ( query-expression ) | ( expression-list ) }

SQL Anywhere - SQL Reference


72 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Remarks

An IN search condition compares expression with the set of values returned by query-expression or the set
of values specified in expression-list. Without the NOT keyword, the IN search condition evaluates according
to the following rules:

● TRUE if expression is not NULL and equals at least one of the values.
● UNKNOWN if expression is NULL and the values list is not empty, or if at least one of the values is NULL and
expression does not equal any of the other values.
● FALSE if expression is NULL and query-expression returns no values; or if expression is not NULL,
none of the values are NULL, and expression does not equal any of the values.

The NOT keyword interchanges TRUE and FALSE.

The search condition expression IN ( expression-list) is equivalent to expression = ANY ( expression-


list).

The search condition expression NOT IN (expression-list ) is equivalent to expression <> ALL
( expression-list).

The expressions in an expression-list can be a literal, variable, host variable, or a query expression whose
result is a single row and a single column.

Standards

ANSI/ISO SQL Standard

Core Feature.

1.1.7.8 CONTAINS search condition

Use the CONTAINS search condition to evaluate whether a value is contained in a set.

Syntax

CONTAINS ( column-name [,...], contains-query-string )

contains-query-string :
simple-expression
| or-expression

simple-expression :
primary-expression
| and-expression

or-expression :
simple-expression { OR | | } contains-query-string

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 73
primary-expression :
basic-expression
| FUZZY " fuzzy-expression "
| and-not-expression

and-expression :
primary-expression [ AND | & ] simple-expression

and-not-expression :
primary-expression [ AND | & ] { NOT | - } basic-expression

basic-expression :
term
| phrase
| ( contains-query-string )
| near-expression
| before-expression

fuzzy-expression :
term
| fuzzy-expression term

term :
simple-term
| prefix-term

prefix-term :
simple-term*

phrase :
" phrase-string "

near-expression :
term NEAR [ [ min-distance ], max-distance ] term
| term { NEAR | ~ } term

before-expressions :
term BEFORE [ [ min-distance ] max-distance ] term
| term BEFORE term

phrase-string :
term
| phrase-string term

simple-term : a string separated by whitespace and special characters that


represents a single indexed term (word) to search for

distance : a positive integer

Parameters

and-expression

SQL Anywhere - SQL Reference


74 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Specifies that both primary-expression and simple-expression must be found in the text index.

By default, if no operator is specified between terms or expressions, an and-expression is assumed. For


example, 'a b' is interpreted as 'a AND b'.

An ampersand (&) can be used instead of AND, and can abut the expressions or terms on either side (for
example, 'a &b').
and-not-expression

Specifies that primary-expression must be present in the text index, but that basic-expression must
not be found in the text index. This is also known as a negation.

If you use a hyphen for negation, the hyphen must have a space to the left of it, and must adjoin the term to
the right; otherwise, the hyphen is not interpreted as a negation. For example, 'a -b' is equivalent to 'a AND
NOT b'; whereas for 'a - b', the hyphen is ignored and the string is equivalent to 'a AND b'. 'a-b' is
equivalent to the phrase '"a b"'.
or-expression

Specifies that at least one of simple-expression or contains-query-string must be present in the text
index. For example, 'a|b' is interpreted as 'a OR b'.
fuzzy-expression

Finds terms that are similar to what you specify. Fuzzy matching is only supported on NGRAM text indexes.
near-expression

Searches for terms that are near each other. This is also known as a proximity search. For example, 'b
NEAR[5] c' searches for instances of b and c that are five or fewer terms away from each other. The order of
terms is not significant; 'b NEAR c' is equivalent to 'c NEAR b'.

If the maximum distance is not specified, the default distance is 10. If the minimum distance is not specified,
the default is 1.

The query 'apple NEAR[2, 10] tree' matches the following documents:

'apple grows on the tree'


'apple and tree'
'tree and apple'

However, the query does not match the following documents:

'apple tree'
'tree apple'

You can specify a tilde (~) instead of NEAR. Using a tilde is equivalent to specifying NEAR without a distance,
so a default of maximum 10 terms and minimum 1 term is applied. You cannot specify a maximum or
minimum distance if you specify a tilde; it is always 10 terms.

NEAR expressions cannot be chained together (for example, 'a NEAR[1] b NEAR[1] c' is invalid).
before-expression

Use before-expression to search for a term that is before another term. This is also known as a proximity
search. The arguments in the matching text must be found in the same order as they are specified in the
CONTAINS query string. For example, 'apple BEFORE[2, 10] tree' matches the following documents:

'apple grows on the tree'


'apple and tree'

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 75
However, the query does not match the following documents:

'tree and apple'


'apple tree'
'tree apple'

The following queries are equivalent:

'apple BEFORE tree'


'apple BEFORE[10] tree'
'apple BEFORE[1, 10] tree'

If the maximum distance is not specified, the default distance is 10. If the minimum distance is not specified,
the default is 1.
prefix-term

Searches for terms that start with the specified prefix. For example, 'datab*' searches for any term
beginning with datab. This is also known as a prefix search. In a prefix search, matching is performed for the
portion of the term to the left of the asterisk.

Remarks

The CONTAINS search condition takes a column list and contains-query-string as arguments. It can be used
anywhere that a search condition (also referred to as predicate) can be specified, and returns TRUE or FALSE.
The contains-query-string must be a constant string or a variable, with a value that is known at query time.
The contains-query-string cannot be NULL, an empty string, or exceed 300 valid terms. A valid term is a
term that is within the permitted term length and is not included in the STOPLIST. An error is returned when the
contains-query-string exceeds 300 valid terms.

If the text configuration settings cause all of the terms in the contains-query-string to be dropped, the result
of the CONTAINS search condition is FALSE.

If multiple columns are specified, then they must all resolve to a single base table (a text index cannot span
multiple base tables). The base table can be referenced directly in the FROM clause, or it can be used in a view or
derived table. If column-name is a column from a view or derived table, the CONTAINS search condition is
recursively pushed into the nested query blocks of the query expression provided that the following is true:

● The columns of the query expressions referenced in the original CONTAINS search condition all resolve to a
single base table in the nested query blocks.
● If more than one text index is used in the nested query blocks, they must have the same text index
configuration.
● The nested query blocks cannot contain TOP, LIMIT, FIRST, or window aggregates.
● The original CONTAINS must be in the WHERE clause in a conjunctive predicate. The columns referenced in
the original CONTAINS search condition must resolve to columns of the same view or derived table.

The following warnings apply to the use of non-alphanumeric characters in query strings:

● An asterisk in the middle of a term returns an error.


● Do not use non-alphanumerics (including special characters) in fuzzy-expression because they are
treated as whitespace and serve as term breakers.
● If possible, do not include non-alphanumeric characters that are not special characters in your query string.
Any non-alphanumeric character that is not a special character causes the term containing it to be treated as

SQL Anywhere - SQL Reference


76 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
a phrase, breaking the term at the location of the character. For example, 'things we've done' is
interpreted as 'things "we ve" done'.

Within phrases, the asterisk is the only special character that continues to be interpreted as a special character.
All other special characters within phrases are treated as whitespace and serve as term breakers.

Interpretation of contains-query-string takes place in two main steps:

Step 1: Interpreting operators and precedence

During this step, keywords are interpreted as operators, and rules of precedence are applied.
Step 2: Applying text configuration object settings

During this step, the text configuration object settings are applied to terms. For example, on an NGRAM text
index, terms are broken down into their n-gram representation. During this step, the query terms that exceed
the term length settings, or that are in the stoplist, are dropped.

Operator precedence in a CONTAINS search condition

During query evaluation, expressions are evaluated using the following order of precedence:

1. FUZZY, NEAR
2. AND NOT
3. AND
4. OR

Treatment of BEFORE as a keyword

The BEFORE keyword is not currently supported as an operator. For example, if you specify CONTAINS(column-
name, 'a before b'), an error is returned. Construct your query using the NEAR keyword instead.

You can search for the word 'before, providing it is part of a phrase query. For example, CONTAINS(column-
name, '"a before b"'). This query searches for the phrase "a before b".

Allowed syntax for asterisk (*)

The asterisk is used for prefix searching. An asterisk can occur at the end of the query string, or be followed by a
space, ampersand, vertical bar, closing bracket, or closing quotation mark. Any other usage of asterisk returns an
error.

The following table shows allowable asterisk usage:

Query string Equivalent to Interpreted as

'th*' Find any term beginning with th.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 77
Query string Equivalent to Interpreted as

'th*&best' 'th* AND best' and 'th* best' Find any term beginning with th, and the
term best.

'th*|best' 'th* OR best' Find either any term beginning with th,
or the term best.

'very&(best|th*)' 'very AND (best OR th*)' Find the term very, and the term best or
any term beginning with th.

'"fast auto*"' Find the term fast, immediately followed


by a term beginning with auto.

'"auto* price"' Find a term beginning with auto, immedi­


ately followed by the term price.

Note
Interpretation of query strings containing asterisks can vary depending on the text configuration object
settings.

Allowed syntax for hyphen (-)

The hyphen can be used for term or expression negation and is equivalent to NOT. Whether a hyphen is
interpreted as a negation depends on its location in the query string. For example, when a hyphen immediately
precedes a term or expression, it is interpreted as a negation. If the hyphen is embedded within a term, it is
interpreted as a hyphen.

A hyphen used for negation must be preceded by a whitespace and followed immediately by an expression.

When used in a phrase of a fuzzy expression, the hyphen is treated as whitespace and used as a term breaker.

The following table shows the allowed syntax for hyphen:

Query string Equivalent to: Interpreted as:

'the -best' 'the AND NOT best', 'the AND Find the term the, and not the term best.

-best', 'the & -best', 'the


NOT best'

'the -(very best)' 'the AND NOT (very AND Find the term the, and not the terms
best)' very and best.

'the -"very best"' 'the AND NOT "very best"' Find the term the, and not the phrase
very best.

'alpha-numerics' '"alpha numerics"' Find the term alpha, immediately fol­


lowed by the term numerics.

'wild - west' 'wild west', and 'wild AND Find the term wild, and the term west.

west'

SQL Anywhere - SQL Reference


78 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Allowed syntax for special characters

The following table shows the allowed syntax for all special characters except asterisk and hyphen.

These characters are not considered special characters if they are found in a phrase, and are dropped.

Note
The same restrictions with regards to specifying string literals also apply to the query string. For example,
apostrophes must be escaped, and so on.

Character or syntax Usage examples and remarks

ampersand (&) The ampersand is equivalent to AND and can be specified as


follows:

● 'a & b'


● 'a &b'
● 'a&b'
● 'a& b'

vertical bar (|) The vertical bar is equivalent to OR and can be specified as fol­
lows:

● 'a|b'
● 'a |b'
● 'a | b'
● 'a| b'

double quotes (") Double quotes are used to contain a sequence of terms where
order and relative distance are important. For example, in the
query string 'learn "full text search"', full
text search is a phrase. In this example, learn can come
before or after the phrase, or exist in another column (if the
text index is built on more than one column), but the exact
phrase must be found in a single column.

parentheses () Parentheses are used to specify the order of evaluation of ex­


pressions if different from the default order. For example 'a
AND (b|c)' is interpreted as a, and b or c.

tilde (~) The tilde is equivalent to NEAR[10]. The query string


'full~text' is equivalent to 'full NEAR text', and
is interpreted as: the term full within ten terms of the term
text.

You cannot specify a distance with the tilde.

square brackets [ ] Square brackets are used with the keyword NEAR to contain
distance. Other uses of square brackets return an error.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 79
Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

String literals [page 13]


FROM clause [page 1116]
sa_char_terms system procedure [page 1456]
sa_nchar_terms system procedure [page 1580]

1.1.7.9 EXISTS search condition

Use the EXISTS search condition to evaluate whether a value is found in a set.

Syntax

EXISTS ( subquery )

Remarks

The EXISTS search condition is TRUE if the subquery result contains at least one row, and FALSE if the subquery
result does not contain any rows. The EXISTS search condition cannot be UNKNOWN.

Standards

ANSI/ISO SQL Standard

Core Feature.

SQL Anywhere - SQL Reference


80 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.1.7.10 IS NULL and IS NOT NULL search conditions

Use the IS NULL search condition to evaluate whether a value in a set is NULL.

Syntax

expression IS [ NOT ] NULL

Remarks

Without the NOT keyword, the IS NULL search condition is TRUE if the expression is the NULL value, and FALSE
otherwise. The NOT keyword reverses the meaning of the search condition.

Standards

ANSI/ISO SQL Standard

Core Feature.

1.1.7.11 Truth value search conditions

Use the IS TRUE search condition to evaluate whether a condition evaluates to a specified value.

Syntax

IS [ NOT ] truth-value

Remarks

Without the NOT keyword, the search condition is TRUE if the condition evaluates to the supplied truth-
value, which must be one of TRUE, FALSE, or UNKNOWN. Otherwise, the value is FALSE. The NOT keyword
reverses the meaning of the search condition, but leaves UNKNOWN unchanged.

Standards

ANSI/ISO SQL Standard

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 81
Truth value search conditions comprise optional ANSI/ISO SQL Language Feature F571.

1.1.7.12 Three-valued logic

The following tables display how the AND, OR, NOT, and IS logical operators of SQL work in three-valued logic.

AND operator

AND TRUE FALSE UNKNOWN

TRUE TRUE FALSE UNKNOWN

FALSE FALSE FALSE FALSE

UNKNOWN UNKNOWN FALSE UNKNOWN

OR operator

OR TRUE FALSE UNKNOWN

TRUE TRUE TRUE TRUE

FALSE TRUE FALSE UNKNOWN

UNKNOWN TRUE UNKNOWN UNKNOWN

NOT operator

TRUE FALSE UNKNOWN

FALSE TRUE UNKNOWN

IS operator

IS TRUE FALSE UNKNOWN

TRUE TRUE FALSE FALSE

FALSE FALSE TRUE FALSE

UNKNOWN FALSE FALSE TRUE

SQL Anywhere - SQL Reference


82 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Standards

ANSI/ISO SQL Standard

Core Feature. Truth value tests, such as IS UNKNOWN, comprise SQL Language Feature F571.

Related Information

NULL special value [page 100]

1.1.7.13 Explicit selectivity estimates

The database server uses statistical information to determine the most efficient strategy for executing each
statement.

The database server automatically gathers and updates these statistics. These statistics are stored permanently
in the database in the system table ISYSCOLSTAT. Statistics gathered while processing one statement are
available when searching for efficient ways to execute subsequent statements.

Occasionally, the statistics may become inaccurate or relevant statistics may be unavailable. This condition is
most likely to arise when few queries have been executed since a large amount of data was added, updated, or
deleted. In this situation, you may want to execute a CREATE STATISTICS statement.

If there are problems with a particular execution plan, you can use optimizer hints to require that a particular
index be used.

In unusual circumstances, however, these measures may prove ineffective. In such cases, you can sometimes
improve performance by supplying explicit selectivity estimates.

For each table in a potential execution plan, the optimizer must estimate the number of rows that will be part of
the result set. If you know that a condition has a success rate that differs from the optimizer's estimate, you can
explicitly supply a user estimate in the search condition.

The estimate is a percentage. It can be a positive integer or can contain fractional values.

Caution
Whenever possible, avoid supplying explicit estimates in statements that are to be used on an ongoing basis.
Should the data change, the explicit estimate may become inaccurate and may force the optimizer to select
poor plans. If you do use explicit selectivity estimates, ensure that the number is accurate. Do not, for example,
supply values of 0% or 100% to force the use of an index.

You can disable user estimates by setting the database option user_estimates to Off. The default value for
user_estimates is Override-Magic, which means that user-supplied selectivity estimates are used only when the
optimizer would use a MAGIC (default) selectivity value for the condition. The optimizer uses MAGIC values as a
last resort when it is unable to accurately predict the selectivity of a predicate.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 83
Example
The following query provides an estimate that one percent of the ShipDate values are later than 2001/06/30:

SELECT ShipDate
FROM GROUPO.SalesOrderItems
WHERE ( ShipDate > '2001/06/30', 1 )
ORDER BY ShipDate DESC;

The following query estimates that half a percent of the rows satisfy the condition:

SELECT *
FROM GROUPO.Customers c, GROUPO.SalesOrders o
WHERE (c.ID = o.CustomerID, 0.5);

Fractional values enable more accurate user estimates for joins and large tables.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

CREATE STATISTICS statement [page 945]


FROM clause [page 1116]

1.1.8 Special values

Special values can be used in expressions, and as column defaults when creating tables.

While some special values can be queried, some can only be used as default values for columns. For example,
LAST USER, TIMESTAMP and UTC TIMESTAMP can only be used as default values.

In this section:

CURRENT DATABASE special value [page 86]


CURRENT DATABASE returns the name of the current database.

CURRENT DATE special value [page 87]


CURRENT DATE returns the present year, month, and day.

CURRENT PUBLISHER special value [page 88]


CURRENT PUBLISHER returns a string that contains the publisher user ID of the database for SQL
Remote replications.

SQL Anywhere - SQL Reference


84 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
CURRENT REMOTE USER special value [page 89]
If the current connection belongs to the receive phase of SQL Remote, then CURRENT REMOTE USER
returns the user ID of the remote user that created the messages that are currently being applied on this
connection. In all other circumstances, CURRENT REMOTE USER is a NULL value.

CURRENT SERVER DATE special value [page 90]


CURRENT DATE returns the present year, month, and day in the time zone of the database server.

CURRENT SERVER TIME special value [page 90]


CURRENT SERVER TIME returns the present hour, minute, second, and fraction of a second in the time
zone of the database server.

CURRENT SERVER TIMESTAMP special value [page 91]


CURRENT TIMESTAMP combines CURRENT DATE and CURRENT TIME to form a TIMESTAMP value
containing the year, month, day, hour, minute, second, and fraction of a second in the time zone of the
database server.

CURRENT TIME special value [page 91]


CURRENT TIME returns the present hour, minute, second, and fraction of a second.

CURRENT TIMESTAMP special value [page 93]


CURRENT TIMESTAMP combines CURRENT DATE and CURRENT TIME to form a TIMESTAMP value
containing the year, month, day, hour, minute, second and fraction of a second.

CURRENT USER special value [page 95]


CURRENT USER contains the user ID of the current connection.

CURRENT UTC TIMESTAMP special value [page 96]


CURRENT UTC TIMESTAMP returns the Coordinated Universal Time (UTC) containing the year, month,
day, hour, minute, second, fraction of a second, and time zone.

EXECUTING USER special value [page 97]


SQL special value that returns the current effective user.

INVOKING USER special value [page 98]


SQL special value that returns the user that invoked the current procedure, or returns the current logged
in user if no procedure is executing.

LAST USER special value [page 99]


LAST USER is the user ID of the user who last modified the row.

NULL special value [page 100]


The NULL value specifies a value that is unknown or not applicable.

PROCEDURE OWNER special value [page 103]


SQL special value that returns the owner of the current procedure, or NULL if queried outside of a
procedure context.

SESSION USER special value [page 104]


SQL special value that stores the user that is currently logged in.

SQLCODE special value [page 105]


SQLCODE indicates the disposition of the most recently executed SQL statement.

SQLSTATE special value [page 106]


SQLSTATE indicates whether the most recently executed SQL statement resulted in a success, error, or
warning condition.

TIMESTAMP special value [page 108]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 85
The TIMESTAMP default value is used to record the local date and time of day when a row in a table was
last modified.

USER special value [page 110]


USER contains the user ID of the current connection.

UTC TIMESTAMP special value [page 110]


The UTC TIMESTAMP default value is used to record the Coordinated Universal Time (UTC) when a row in
a table was last modified.

1.1.8.1 CURRENT DATABASE special value

CURRENT DATABASE returns the name of the current database.

Data type

string

Remarks

During an UPDATE operation, columns with a default value of CURRENT DATABASE are not changed.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

Expressions in SQL statements [page 32]

SQL Anywhere - SQL Reference


86 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.1.8.2 CURRENT DATE special value

CURRENT DATE returns the present year, month, and day.

Data type

DATE

Remarks

When the database is using a simulated time zone, the simulated time zone is used to calculate this value.

During an UPDATE operation, columns with a default value of CURRENT DATE are not changed.

Standards

ANSI/ISO SQL Standard

Not in the ANSI/ISO SQL Standard. In the standard, the special register that defines the present date is called
CURRENT_DATE. The software does not support CURRENT_DATE.

Example
Create the Australian Eastern Time zone.

CREATE TIME ZONE NewSouthWales OFFSET '10:00'


STARTING 'Oct/Sun>=1' AT '2:00'
ENDING 'Apr/Sun>=1' AT '2:00';

Create a table with a DEFAULT column set to the CURRENT DATE special value. Then insert some values under
two different time zones.

CREATE OR REPLACE TABLE TEST( COL1 DATE DEFAULT CURRENT DATE,COL2 INT);
SET OPTION PUBLIC.time_zone='NewSouthWales';
INSERT INTO TEST(COL2) VALUES(1),(2);
SET OPTION PUBLIC.time_zone=;
INSERT INTO TEST(COL2) VALUES(3),(4);
SELECT * FROM TEST;

The first two rows are inserted using the current date in the NewSouthWales time zone and the last two rows
are inserted using the current date in the server's time zone.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 87
Related Information

DATE data type [page 163]


DATE function [Date and time] [page 304]
DATETIME data type [page 164]
DATETIME function [Date and time] [page 313]
DATETIMEOFFSET data type [page 165]
Expressions in SQL statements [page 32]
GETDATE function [Date and time] [page 377]
ISDATE function [Data type conversion] [page 409]
NOW function [Date and time] [page 460]
SMALLDATETIME data type [page 167]
TIME data type [page 169]

1.1.8.3 CURRENT PUBLISHER special value

CURRENT PUBLISHER returns a string that contains the publisher user ID of the database for SQL Remote
replications.

Data type

string

Remarks

The publisher is set using the PUBLIC.db_publisher option, or by using the GRANT PUBLISH and REVOKE
PUBLISH statements.

CURRENT PUBLISHER can be used as a default value in columns with character data types.

When an update or insert operation is performed on a column defined as DEFAULT CURRENT PUBLISHER, the
column is updated with the current value of CURRENT PUBLISHER.

Standards

ANSI/ISO SQL Standard

Not in the standard.

SQL Anywhere - SQL Reference


88 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Related Information

GRANT PUBLISH statement [SQL Remote] [page 1151]


REVOKE PUBLISH statement [SQL Remote] [page 1279]

1.1.8.4 CURRENT REMOTE USER special value

If the current connection belongs to the receive phase of SQL Remote, then CURRENT REMOTE USER returns the
user ID of the remote user that created the messages that are currently being applied on this connection. In all
other circumstances, CURRENT REMOTE USER is a NULL value.

Data type

string

Remarks

The CURRENT REMOTE USER special value is set by the receive phase of SQL Remote when it is applying
messages to the database. The CURRENT REMOTE USER special value is most useful in triggers to determine
whether the operations being applied are being applied by the receive phase of SQL Remote, and if they are, which
remote user generated the operations being applied.

When an update or insert operation is performed on a column defined as DEFAULT CURRENT REMOTE USER, the
column is updated with the current value of CURRENT REMOTE USER.

Standards

ANSI/ISO SQL Standard

Not in the standard.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 89
1.1.8.5 CURRENT SERVER DATE special value

CURRENT DATE returns the present year, month, and day in the time zone of the database server.

Data type

DATE

Remarks

During an UPDATE operation, the database server does not change columns with a default value of CURRENT
SERVER DATE.

Standards

ANSI/ISO SQL Standard

Not in the ANSI/ISO SQL Standard. In the standard, the special register that defines the present date is called
CURRENT_SERVER_DATE. The software does not support CURRENT_SERVER_DATE.

1.1.8.6 CURRENT SERVER TIME special value

CURRENT SERVER TIME returns the present hour, minute, second, and fraction of a second in the time zone of
the database server.

Data type

TIME

Remarks

The fraction of a second is stored to six decimal places. The accuracy of the present time is limited by the
accuracy of the system clock.

During an UPDATE operation, the database server does not change columns with a default value of CURRENT
SERVER TIME.

SQL Anywhere - SQL Reference


90 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Standards

ANSI/ISO SQL Standard

Not in the ANSI/ISO SQL Standard. In the standard, the special register that defines the present time is called
CURRENT_SERVER_TIME. The software does not support CURRENT_SERVER_TIME.

1.1.8.7 CURRENT SERVER TIMESTAMP special value

CURRENT TIMESTAMP combines CURRENT DATE and CURRENT TIME to form a TIMESTAMP value containing
the year, month, day, hour, minute, second, and fraction of a second in the time zone of the database server.

Data type

TIMESTAMP

Remarks

The fraction of a second is stored to six decimal places. The accuracy of the present time is limited by the
accuracy of the system clock.

Standards

ANSI/ISO SQL Standard

Not in the ANSI/ISO SQL Standard. In the standard, the special register that defines the present timestamp is
called CURRENT_TIMESTAMP.

1.1.8.8 CURRENT TIME special value

CURRENT TIME returns the present hour, minute, second, and fraction of a second.

Data type

TIME

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 91
Remarks

The fraction of a second is stored to 6 decimal places. The accuracy of the present time is limited by the accuracy
of the system clock.

When the database is using a simulated time zone, the simulated time zone is used to calculate this value.

During an UPDATE operation, columns with a default value of CURRENT TIME are not changed.

Standards

ANSI/ISO SQL Standard

Not in the ANSI/ISO SQL Standard. In the standard, the special register that defines the present time is called
CURRENT_TIME. The software does not support CURRENT_TIME.

Example
Create the Australian Eastern Time zone.

CREATE TIME ZONE NewSouthWales OFFSET '10:00'


STARTING 'Oct/Sun>=1' AT '2:00'
ENDING 'Apr/Sun>=1' AT '2:00';

Create a table with a DEFAULT column set to the CURRENT TIME special value. Then insert some values under
two different time zones.

CREATE OR REPLACE TABLE TEST( COL1 TIME DEFAULT CURRENT TIME,COL2 INT);
SET OPTION PUBLIC.time_zone='NewSouthWales';
INSERT INTO TEST(COL2) VALUES(1),(2);
SET OPTION PUBLIC.time_zone=;
INSERT INTO TEST(COL2) VALUES(3),(4);
SELECT * FROM TEST;

The first two rows are inserted using the current time in the NewSouthWales time zone and the last two rows
are inserted using the current time in the server's time zone.

Related Information

Expressions in SQL statements [page 32]


CURRENT TIMESTAMP special value [page 93]
CURRENT UTC TIMESTAMP special value [page 96]
DATE data type [page 163]
DATE function [Date and time] [page 304]
DATETIME data type [page 164]
DATETIME function [Date and time] [page 313]
DATETIMEOFFSET data type [page 165]

SQL Anywhere - SQL Reference


92 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
GETDATE function [Date and time] [page 377]
ISDATE function [Data type conversion] [page 409]
NOW function [Date and time] [page 460]
SMALLDATETIME data type [page 167]
TIME data type [page 169]
TIMESTAMP data type [page 170]
TIMESTAMP special value [page 108]
UTC TIMESTAMP special value [page 110]

1.1.8.9 CURRENT TIMESTAMP special value

CURRENT TIMESTAMP combines CURRENT DATE and CURRENT TIME to form a TIMESTAMP value containing
the year, month, day, hour, minute, second and fraction of a second.

Data type

TIMESTAMP

Remarks

The fraction of a second is stored to 6 decimal places. The accuracy of the present time is limited by the accuracy
of the system clock.

Unlike DEFAULT TIMESTAMP, columns declared with DEFAULT CURRENT TIMESTAMP do not necessarily
contain unique values. If uniqueness is required, consider using DEFAULT TIMESTAMP instead.

When the database is using a simulated time zone, the simulated time zone is used to calculate this value.

The information CURRENT TIMESTAMP returns is equivalent to the information returned by the GETDATE and
NOW functions.

CURRENT_TIMESTAMP is equivalent to CURRENT TIMESTAMP.

Note
The main difference between DEFAULT CURRENT TIMESTAMP and DEFAULT TIMESTAMP is that DEFAULT
CURRENT TIMESTAMP columns are set only at INSERT (unless explicitly set at UPDATE), while DEFAULT
TIMESTAMP columns are set at both INSERT and UPDATE.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 93
Standards

ANSI/ISO SQL Standard

Not in the ANSI/ISO SQL Standard. In the standard, the special register that defines the present timestamp is
called CURRENT_TIMESTAMP.

Example
Create the Australian Eastern Time zone.

CREATE TIME ZONE NewSouthWales OFFSET '10:00'


STARTING 'Oct/Sun>=1' AT '2:00'
ENDING 'Apr/Sun>=1' AT '2:00';

Create a table with a DEFAULT column set to the CURRENT TIMESTAMP special value. Then insert some
values under two different time zones.

CREATE OR REPLACE TABLE TEST( COL1 TIMESTAMP DEFAULT CURRENT TIMESTAMP,COL2 INT);
SET OPTION PUBLIC.time_zone='NewSouthWales';
INSERT INTO TEST(COL2) VALUES(1),(2);
SET OPTION PUBLIC.time_zone=;
INSERT INTO TEST(COL2) VALUES(3),(4);
SELECT * FROM TEST;

The first two rows are inserted using the current date and time in the NewSouthWales time zone and the last
two rows are inserted using the current date and time in the server's time zone.

Related Information

Expressions in SQL statements [page 32]


CURRENT TIME special value [page 91]
CURRENT UTC TIMESTAMP special value [page 96]
DATE data type [page 163]
DATE function [Date and time] [page 304]
DATETIME data type [page 164]
DATETIME function [Date and time] [page 313]
DATETIMEOFFSET data type [page 165]
GETDATE function [Date and time] [page 377]
ISDATE function [Data type conversion] [page 409]
NOW function [Date and time] [page 460]
SMALLDATETIME data type [page 167]
TIME data type [page 169]
TIMESTAMP data type [page 170]
TIMESTAMP special value [page 108]
UTC TIMESTAMP special value [page 110]

SQL Anywhere - SQL Reference


94 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.1.8.10 CURRENT USER special value

CURRENT USER contains the user ID of the current connection.

Data type

string

Remarks

CURRENT USER can be used as a default value in columns with character data types.

On UPDATE, columns with the CURRENT USER default are not changed unless explicitly updated. The LAST
USER default can be used to track updates by users.

CURRENT_USER is equivalent to CURRENT USER.

Standards

ANSI/ISO SQL Standard

Not in the ANSI/ISO SQL Standard. In the standard, the special register that defines the current user is called
CURRENT_USER.

Related Information

Expressions in SQL statements [page 32]


LAST USER special value [page 99]
USER special value [page 110]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 95
1.1.8.11 CURRENT UTC TIMESTAMP special value

CURRENT UTC TIMESTAMP returns the Coordinated Universal Time (UTC) containing the year, month, day, hour,
minute, second, fraction of a second, and time zone.

Data type

TIMESTAMP WITH TIME ZONE

Remarks

This feature allows data to be entered with a consistent time reference, regardless of the time zone in which the
data was entered.

During an UPDATE operation, columns with the CURRENT UTC TIMESTAMP default value are not changed unless
explicitly updated.

The UTC TIMESTAMP default can be used to track the UTC time of updates.

Standards

ANSI/ISO SQL Standard

Not in the standard. However, the TIMESTAMP WITH TIME ZONE data type is optional ANSI/ISO SQL
Language Feature F41.

Related Information

Expressions in SQL statements [page 32]


CURRENT TIME special value [page 91]
CURRENT TIMESTAMP special value [page 93]
DATE data type [page 163]
DATE function [Date and time] [page 304]
DATETIME data type [page 164]
DATETIME function [Date and time] [page 313]
DATETIMEOFFSET data type [page 165]
GETDATE function [Date and time] [page 377]
ISDATE function [Data type conversion] [page 409]
NOW function [Date and time] [page 460]

SQL Anywhere - SQL Reference


96 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
SMALLDATETIME data type [page 167]
TIME data type [page 169]
TIMESTAMP data type [page 170]
TIMESTAMP special value [page 108]
UTC TIMESTAMP special value [page 110]

1.1.8.12 EXECUTING USER special value

SQL special value that returns the current effective user.

Data type

STRING

Remarks

Use EXECUTING USER, INVOKING USER, SESSION USER, and PROCEDURE OWNER to determine which users
can execute, and are executing, procedures and user-defined functions. Depending on how many layers of nesting
a particular procedure call has, and based on whether the previous and current procedure are SQL SECURITY
DEFINER or SQL SECURITY INVOKER, the EXECUTING USER, and INVOKING USER can and do change.

EXECUTING_USER is equivalent to EXECUTING USER.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

INVOKING USER special value [page 98]


PROCEDURE OWNER special value [page 103]
SESSION USER special value [page 104]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 97
1.1.8.13 INVOKING USER special value

SQL special value that returns the user that invoked the current procedure, or returns the current logged in user if
no procedure is executing.

Data type

STRING

Remarks

Use INVOKING USER, SESSION USER, EXECUTING USER, and PROCEDURE OWNER to determine which users
can execute, and are executing, procedures and user-defined functions. Depending on how many layers of nesting
a particular procedure call has, and based on whether the previous and current procedure are SQL SECURITY
DEFINER or SQL SECURITY INVOKER, the INVOKING USER and EXECUTING USER can and do change.

INVOKING_USER is equivalent to INVOKING USER.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

EXECUTING USER special value [page 97]


PROCEDURE OWNER special value [page 103]
SESSION USER special value [page 104]

SQL Anywhere - SQL Reference


98 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.1.8.14 LAST USER special value

LAST USER is the user ID of the user who last modified the row.

Data type

String

Remarks

LAST USER can be used as a default value in columns with character data types.

On INSERT, this constant has the same effect as CURRENT USER.

On UPDATE, if a column with a default value of LAST USER is not explicitly modified, it is changed to the name of
the current user.

When combined with the DEFAULT TIMESTAMP, a default value of LAST USER can be used to record (in separate
columns) both the user and the date and time of day a row was last changed.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

CREATE TABLE statement [page 956]


CURRENT USER special value [page 95]
CURRENT TIMESTAMP special value [page 93]
USER special value [page 110]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 99
1.1.8.15 NULL special value

The NULL value specifies a value that is unknown or not applicable.

Syntax

NULL

Remarks

NULL is a special value that is different from any valid value for any data type. However, the NULL value is a legal
value in any data type. NULL is used to represent missing or inapplicable information. There are two separate and
distinct cases where NULL is used:

Situation Description

missing The field does have a value, but that value is unknown.

inapplicable The field does not apply for this particular row.

SQL allows columns to be created with the NOT NULL restriction. Those particular columns cannot contain NULL.

The NULL value introduces the concept of three valued logic to SQL. The NULL value compared using any
comparison operator with any value (including the NULL value) is "UNKNOWN." The only search condition that
returns TRUE is the IS NULL predicate. In SQL, rows are selected only if the search condition in the WHERE clause
evaluates to TRUE; rows that evaluate to UNKNOWN or FALSE are not selected.

Column space utilization for NULL values is 1 bit per column and space is allocated in multiples of 8 bits. The NULL
bit usage is fixed based on the number of columns in the table that allow NULL values.

The IS [ NOT ] truth-value clause, where truth-value is one of TRUE, FALSE or UNKNOWN can be used to
select rows where the NULL value is involved.

In the following examples, the column Salary contains NULL.

Condition Truth value Selected?

Salary = NULL UNKNOWN NO

Salary <> NULL UNKNOWN NO

NOT (Salary = NULL) UNKNOWN NO

NOT (Salary <> NULL) UNKNOWN NO

Salary = 1000 UNKNOWN NO

Salary IS NULL TRUE YES

Salary IS NOT NULL FALSE NO

Salary = expression IS UNKNOWN TRUE YES

The same rules apply when comparing columns from two different tables. Therefore, joining two tables together
does not select rows where any of the columns compared contain the NULL value.

SQL Anywhere - SQL Reference


100 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
NULL also has an interesting property when used in numeric expressions. The result of any numeric expression
involving the NULL value is NULL. If NULL is added to a number, then the result is NULL, not a number. To treat
NULL as 0, use the ISNULL( expression, 0 ) function.

Many common errors in formulating SQL queries are caused by the behavior of NULL. You have to be careful to
avoid these problem areas.

Set operators and DISTINCT clause

In SQL, comparisons to NULL within search conditions yield UNKNOWN as the result. However, when determining
whether two rows are duplicates of each other, SQL treats NULL as equivalent to NULL. These semantics apply to
the set operators (UNION, INTERSECT, EXCEPT), GROUP BY, PARTITION within a WINDOW clause, and SELECT
DISTINCT.

For example, if a column called redundant contained NULL for every row in a table T1, then the following
statement would return a single row:

SELECT DISTINCT redundant FROM T1;

You can also use the IS DISTINCT FROM and IS NOT DISTINCT FROM sargable search conditions to determine
whether two expressions are equal or if both expressions are NULL.

Prerequisites

Must be connected to the database.

Side effects

None.

Standards

ANSI/ISO SQL Language

Core Feature.
Transact-SQL

In some contexts, Adaptive Server Enterprise treats comparisons to NULL values differently. If an
expression is compared to a variable or NULL literal using equality or inequality, and if expression is a
simple expression that refers to the column of a base table or view, then the comparison is performed using

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 101
two-valued logic, with NULL = NULL yielding TRUE rather than UNKNOWN. The list of possible comparisons
with these semantics, and their ANSI/ISO SQL Standard equivalents, are as follows:

Transact-SQL comparison ANSI/ISO SQL Standard equivalent

expression = NULL expression IS NULL

expression != NULL NOT (expression IS NULL)

expression = variable expression = variable IS TRUE OR (expression IS


NULL AND variable IS NULL)

expression != variable expression != variable IS TRUE AND ( NOT


expression IS NULL OR NOT variable IS NULL)

SQL Anywhere will implement these semantics to match Adaptive Server Enterprise behavior if the ansinull
option is set to OFF. The ansinull option is set to OFF by default for Open Client and jConnect connections. To
ensure ANSI/ISO SQL Standard semantics, you can either reset the ansinull option to ON, or use an IS [NOT]
NULL predicate instead of an equality comparison.

Unique indexes in SQL Anywhere can hold rows that hold NULL and are otherwise identical. Adaptive Server
Enterprise does not permit such entries in unique indexes.

If you use jConnect, the tds_empty_string_is_null option controls whether empty strings are returned as
NULL strings or as a string containing one blank character.

Example
The following INSERT statement inserts a NULL into the date_returned column of the Borrowed_book table.

INSERT INTO Borrowed_book ( date_borrowed, date_returned, book )


VALUES ( CURRENT DATE, NULL, '1234' );

Related Information

Expressions in SQL statements [page 32]


Search conditions [page 55]
IS DISTINCT FROM and IS NOT DISTINCT FROM search conditions [page 61]

SQL Anywhere - SQL Reference


102 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.1.8.16 PROCEDURE OWNER special value

SQL special value that returns the owner of the current procedure, or NULL if queried outside of a procedure
context.

Data type

STRING

Remarks

Use PROCEDURE OWNER, INVOKING USER, SESSION USER, and EXECUTING USER to determine which users
can execute, and are executing, procedures and user-defined functions. Depending on how many layers of nesting
a particular procedure call has, and based on whether the previous and current procedure are SQL SECURITY
DEFINER or SQL SECURITY INVOKER, the EXECUTING USER and INVOKING USER can and do change.

PROCEDURE_OWNER is equivalent to PROCEDURE OWNER.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

EXECUTING USER special value [page 97]


INVOKING USER special value [page 98]
SESSION USER special value [page 104]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 103
1.1.8.17 SESSION USER special value

SQL special value that stores the user that is currently logged in.

Data type

STRING

Remarks

Use SESSION USER, INVOKING USER, EXECUTING USER, and PROCEDURE OWNER to determine which users
can execute, and are executing, procedures and user-defined functions. Depending on how many layers of nesting
a particular procedure call has, and based on whether the previous and current procedure are SQL SECURITY
DEFINER or SQL SECURITY INVOKER, the INVOKING USER, and EXECUTING USER can and do change. However,
SESSION USER always remains the logged in user.

SESSION_USER is equivalent to SESSION USER.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

EXECUTING USER special value [page 97]


INVOKING USER special value [page 98]
PROCEDURE OWNER special value [page 103]

SQL Anywhere - SQL Reference


104 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.1.8.18 SQLCODE special value

SQLCODE indicates the disposition of the most recently executed SQL statement.

Data type

Signed INTEGER

Remarks

The database server sets a SQLSTATE and SQLCODE for each SQL statement it executes. SQLCODEs are
product-specific (for example, MobiLink has its own SQLCODEs), and can be used to learn additional information
about the SQLSTATE. For example, positive values other than 100 indicate product-specific warning conditions.
Negative values indicate product-specific exception conditions. The value 100 indicates "no data" (for example,
at the end of a result set fetched via a cursor).

SQLSTATE and SQLCODE are related in that each SQLCODE corresponds to a SQLSTATE, and each SQLSTATE
can correspond to one or more SQLCODEs.

To return the error condition associated with a SQLCODE, you can use the ERRORMSG function.

Note
SQLSTATE is the preferred status indicator for the outcome of a SQL statement.

Standards

ANSI/ISO SQL Standard

Not in the standard. SQLSTATE is the preferred status indicator.

Related Information

SQLSTATE special value [page 106]


Expressions in SQL statements [page 32]
ERRORMSG function [Miscellaneous] [page 351]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 105
1.1.8.19 SQLSTATE special value

SQLSTATE indicates whether the most recently executed SQL statement resulted in a success, error, or warning
condition.

Data type

String

Remarks

The database server sets a SQLSTATE and SQLCODE for each SQL statement it executes. A SQLSTATE is a string
that indicates the whether the most recently executed SQL statement resulted in a success, warning, or error
condition.

Each SQLSTATE represents errors that are common to all platforms, and usually contain non-product-specific
wording. The format of a SQLSTATE value is a two-character class value, followed by a three-character subclass
value. Guidelines for SQLSTATE conformance with regard to class and subclass values are outlined in the ISO/
ANSI SQL standard.

The database server conforms to the ISO/ANSI SQLSTATE conventions with the following additions and
exceptions:

Class and subclass Condition

01WCx Warnings related to character set conversion

38xxx External function exception

42Xxx Syntax error: expressions

42Rxx Syntax error: referential integrity (for example, attempt to


create second primary key)

42Wxx Syntax error: generic

42Uxx Syntax error: duplicate, undefined, or ambiguous object refer­


ence

42Zxx Access violation

54Wxx Product limit exceeded

55Wxx Object not in required state for operation to succeed

57xxx Resource not available or operator intervention

5Rxxx SQL Remote errors

WBxxx Online backup errors

WIxxx Internal database errors

SQL Anywhere - SQL Reference


106 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Class and subclass Condition

WPxxx Errors in procedures, variables, and so on

WLxxx Errors loading and/or unloading

WWxxx Miscellaneous SQL Anywhere-specific errors/warnings (in­


cluding system failures)

WOxxx Remote data access feature-related errors

WJxxx JCS and JDBC related errors

WCxxx Character translation errors

WXxxx XML-related errors

WTxxx Text-related errors

The successful completion class is '00xxx' (for example, '00000').

SQLSTATE and SQLCODE are related in that each SQLCODE corresponds to a SQLSTATE, and each SQLSTATE
can correspond to one or more SQLCODEs.

To return the error condition associated with a SQLSTATE, you can use the ERRORMSG function.

Standards

ANSI/ISO SQL Standard

SQLSTATE classes (the first two characters) beginning with the values '0'-'4', and 'A'-'H' are defined by the
ANSI/ISO SQL Standard. Other classes are implementation-defined. Similarly, subclass values that begin
with values '0'-'4', and 'A'-'H' are defined by the ANSI/ISO SQL Standard. Subclass values outside these
ranges are implementation-defined.

Related Information

ERRORMSG function [Miscellaneous] [page 351]


SQLCODE special value [page 105]
Expressions in SQL statements [page 32]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 107
1.1.8.20 TIMESTAMP special value

The TIMESTAMP default value is used to record the local date and time of day when a row in a table was last
modified.

Data type

TIMESTAMP

Remarks

The fraction of a second is stored to 6 decimal places. The accuracy of the present time is limited by the accuracy
of the system clock.

When a column is declared with DEFAULT TIMESTAMP, a default value is provided for inserts, and the value is
updated with the present date and time of day whenever the row is updated.

When the database is using a simulated time zone, the simulated time zone is used to calculate this value.

Columns declared with DEFAULT TIMESTAMP contain unique values so that applications can detect near-
simultaneous updates to the same row. If the present timestamp value is the same as the last value, it is
incremented by the value of the default_timestamp_increment option.

You can automatically truncate timestamp values with the default_timestamp_increment option. This is useful for
maintaining compatibility with other database software that records less precise timestamp values.

The global variable @@dbts returns a TIMESTAMP value corresponding to the last value generated for any column
using DEFAULT TIMESTAMP in the database. When the database is using a simulated time zone, the TIMESTAMP
value is relative to that time zone.

Note
The main difference between DEFAULT TIMESTAMP and DEFAULT CURRENT TIMESTAMP is that DEFAULT
CURRENT TIMESTAMP columns are set only at INSERT (unless explicitly set at UPDATE), while DEFAULT
TIMESTAMP columns are set at both INSERT and UPDATE.

Standards

ANSI/ISO SQL Standard

Not in the standard.

SQL Anywhere - SQL Reference


108 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Example
Create the Australian Eastern Time zone.

CREATE TIME ZONE NewSouthWales OFFSET '10:00'


STARTING 'Oct/Sun>=1' AT '2:00'
ENDING 'Apr/Sun>=1' AT '2:00';

Create a table with a DEFAULT column set to the CURRENT TIMESTAMP special value. Then insert some
values under two different time zones.

CREATE OR REPLACE TABLE TEST( COL1 TIMESTAMP DEFAULT TIMESTAMP,COL2 INT);


SET OPTION PUBLIC.time_zone='NewSouthWales';
INSERT INTO TEST(COL2) VALUES(1),(2);
SET OPTION PUBLIC.time_zone=;
INSERT INTO TEST(COL2) VALUES(3),(4);
SELECT * FROM TEST;

The first two rows are inserted using the current date and time in the NewSouthWales time zone and the last
two rows are inserted using the current date and time in the server's time zone.

Related Information

CURRENT TIME special value [page 91]


CURRENT TIMESTAMP special value [page 93]
CURRENT UTC TIMESTAMP special value [page 96]
DATE data type [page 163]
DATE function [Date and time] [page 304]
DATETIME data type [page 164]
DATETIME function [Date and time] [page 313]
DATETIMEOFFSET data type [page 165]
GETDATE function [Date and time] [page 377]
ISDATE function [Data type conversion] [page 409]
NOW function [Date and time] [page 460]
SMALLDATETIME data type [page 167]
TIME data type [page 169]
TIMESTAMP data type [page 170]
UTC TIMESTAMP special value [page 110]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 109
1.1.8.21 USER special value

USER contains the user ID of the current connection.

Data type

string

Remarks

USER can be used as a default value in columns with character data types. It is equivalent to CURRENT USER.

On UPDATE, columns with the USER default are not changed unless explicitly updated. Instead, the LAST USER
default can be used to track updates by users.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

Expressions in SQL statements [page 32]


CURRENT USER special value [page 95]
LAST USER special value [page 99]

1.1.8.22 UTC TIMESTAMP special value

The UTC TIMESTAMP default value is used to record the Coordinated Universal Time (UTC) when a row in a table
was last modified.

Data type

TIMESTAMP WITH TIME ZONE

SQL Anywhere - SQL Reference


110 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Remarks

The fraction of a second is stored to 6 decimal places. The accuracy of the present time is limited by the accuracy
of the system clock.

When a column is declared with DEFAULT UTC TIMESTAMP, a default value is provided for inserts, and the value
is updated with the present UTC date and time of day whenever the row is updated.

Columns declared with DEFAULT UTC TIMESTAMP contain unique values so that applications can detect near-
simultaneous updates to the same row. If the present UTC timestamp value is the same as the last value, it is
incremented by the value of the default_timestamp_increment option.

You can automatically truncate UTC TIMESTAMP values with the default_timestamp_increment option. This is
useful for maintaining compatibility with other database software that records less precise timestamp values.

Note
DEFAULT UTC TIMESTAMP is set at both INSERT and UPDATE and DEFAULT CURRENT UTC TIMESTAMP is
set at INSERT.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

Expressions in SQL statements [page 32]


CURRENT TIME special value [page 91]
CURRENT TIMESTAMP special value [page 93]
CURRENT UTC TIMESTAMP special value [page 96]
DATE data type [page 163]
DATE function [Date and time] [page 304]
DATETIME data type [page 164]
DATETIME function [Date and time] [page 313]
DATETIMEOFFSET data type [page 165]
GETDATE function [Date and time] [page 377]
ISDATE function [Data type conversion] [page 409]
NOW function [Date and time] [page 460]
SMALLDATETIME data type [page 167]
TIME data type [page 169]
TIMESTAMP data type [page 170]
TIMESTAMP special value [page 108]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 111
TIMESTAMP WITH TIME ZONE data type [page 172]

1.1.9 %TYPE and %ROWTYPE attributes

In addition to explicitly setting the data type for an object, you can also set the data type by specifying the %TYPE
and %ROWTYPE attributes.

Use the %TYPE and %ROWTYPE attributes when creating or declaring variables, converting values, creating or
altering tables, and creating procedures, to define the data type(s) based on the data type of a column or row in a
table, view, or cursor. The %TYPE attribute sets the data type to that of a column in the specified object, while the
%ROWTYPE attribute sets the data types to those of a row in the specified object.

When %TYPE or %ROWTYPE is specified for a schema object, the database server derives the actual data type
information from system tables. For example, if a %TYPE attribute specifies a table column, the data type is
retrieved from the ISYSTABCOL system table.

Once the data types have been derived and the object (variable, column, and so on) is created, there is no further
link or dependency to the object referenced in the %TYPE and %ROWTYPE attribute. However, in the case of
procedures that use %TYPE and %ROWTYPE to define parameters and return types, the procedure can return
different results if the underlying referenced objects change. This is because %TYPE and %ROWTYPE are
evaluated when the procedure is executed, not when it is created.

Tables and views

Specify the %TYPE attribute to set the data type of a column to the data type of a column in another table or view.
For example:

● myColumnName other-table-name.column-name%TYPE

The second statement in the following example creates a table, myT2, and sets the data type of its column,
myColumn, to the data type of the last_name column in myT1. Since additional attributes such as nullability are
not applied, myT2.myColumn will not have the same NOT NULL restriction that myT1.last_name does.

CREATE TABLE myT1


( first_name CHAR(20),
last_name VARCHAR NOT NULL );
CREATE TABLE myT2
( myColumn myT1.last_name%TYPE );

Procedures and functions

Specify the %TYPE or %ROWTYPE attribute to set the data type(s) of the parameters to the data type(s) of a
column or row in a specified table or view.

SQL Anywhere - SQL Reference


112 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
The following statement creates a procedure, DepartmentsCloseToCustomerLocation, and sets its IN parameter
to the data type of the ID column in the Customers table:

CREATE OR REPLACE PROCEDURE DepartmentsCloseToCustomerLocation( IN customer_ID


Customers.ID%TYPE )
BEGIN
DECLARE cust_rec Customers%ROWTYPE;
SELECT City, State, Country
INTO cust_rec.City, cust_rec.State, cust_rec.Country
FROM Customers
WHERE ID = customer_ID;
SELECT Employees.Surname, Employees.GivenName, Departments.DepartmentName
FROM Employees JOIN Departments
ON Departments.DepartmentHeadID = Employees.EmployeeID
WHERE Employees.City = cust_rec.City
AND Employees.State = cust_rec.State
AND Employees.Country = cust_rec.Country;
END;
CALL DepartmentsCloseToCustomerLocation(158);

The following statement creates a function called fullname and sets the data types of the firstname and lastname
parameters to the data types of the Surname and Givenname column of the Employees table:

CREATE OR REPLACE FUNCTION fullname(


firstname Employees.Surname%TYPE,
lastname Employees.GivenName%TYPE )
RETURNS LONG VARCHAR
BEGIN
RETURN ( firstname || ' ' || lastname );
END;
SELECT fullname ( Surname, GivenName )FROM GROUPO.Employees;

Casting and converting values

Specify the %TYPE attribute when to cast or convert a value to the data type of another database object.

The following statement casts a value to the data type defined for the BirthDate column (DATE data type) of the
Employees table:

SELECT CAST ( '1966-10-30' AS Employees.BirthDate%TYPE );

Domains

Specify the %TYPE attribute to set the domain data type to the data type of a column in a specified table or view.

In the following example, the second two CREATE DOMAIN statements in the following set of statements create
domains based on the data types of the Surname and GivenName columns of the Customers table.

CREATE DOMAIN identifier UNSIGNED INT


DEFAULT AUTOINCREMENT;
CREATE DOMAIN customers_surname Customers.Surname%TYPE;
CREATE DOMAIN customers_givenname Customers.GivenName%TYPE;

CREATE TABLE Customers3 (

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 113
ID identifier PRIMARY KEY,
SurName customers_surname,
GivenName customers_givenname
);

Variables

Specify the %TYPE attribute to set the data type of a variable to the data type of a column in a specified table,
view, or cursor. When %TYPE is used, only the data type is derived from the referenced object. Other column
attributes such as default values, constraints, and whether NULLs are allowed, are not included and must be
specified separately. Use the %TYPE attribute to declare a variable with the same type as column data when you
want your application to be able to adjust to changes to an underlying table schema.

The following example creates a new variable, ProductID, and uses the %TYPE attribute to set its data type to the
data type of the ID column in the Products table:

CREATE VARIABLE ProductID Products.ID%TYPE;

Specify the %ROWTYPE attribute to set the data type of a set of columns to the data types of a row in a specified
table, view, or cursor. For example, use the %ROWTYPE attribute to define a variable that can store row or array
values.

When %ROWTYPE is specified, other column attributes such as default values, constraints, and whether NULLs
are allowed, are not included in the derivation.

The following example uses the %ROWTYPE attribute to create a variable, @a_product, and then inserts data
from the Products table into the variable:

CREATE OR REPLACE PROCEDURE CheckStock (


IN @id Products.ID%TYPE
)
BEGIN
DECLARE @a_product Products%ROWTYPE;
SET (@a_product).ID = 200;
END;

You can also use the %TYPE attribute to set the data type of a variable to type of another variable, as shown in the
second DECLARE statement in this example:

DECLARE cust_rec Customers%ROWTYPE;


DECLARE cust_rec2 cust_rec%TYPE;

In this section:

%TYPE attribute syntax [page 115]


Sets the data type to that of a column in a specified object or variable when creating or declaring variables,
or creating or altering tables, views, procedures, and functions. It can also be used for casting data from
one type to another.

%ROWTYPE attribute syntax [page 117]


Sets the data type to the composite data type of a row in a specified table, view, table reference variable,
or cursor.

SQL Anywhere - SQL Reference


114 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.1.9.1 %TYPE attribute syntax

Sets the data type to that of a column in a specified object or variable when creating or declaring variables, or
creating or altering tables, views, procedures, and functions. It can also be used for casting data from one type to
another.

Syntax

type-source%TYPE
| TYPE OF ( type-source )
type-source :
[ owner. ]{ table-name
| view-name }.column-name
| variable-name
| variable-name.field-name

Parameters

table-name

The name of a table.


view-name

The name of an enabled view (including materialized views). Materialized views must be initialized as well.
variable-name

The name of a variable.


column-name

The name of a column.

Remarks

When creating or altering procedures (parameters and return types), tables, views, and domains, an object that is
referenced in a %TYPE specification must be a permanent object. A reference to a temporary object, such as a
variable, cursor, or temporary table returns an error.

When %TYPE is specified in an IS OF search expression, a WITH hint expression in a FROM clause, or a CAST or
CONVERT function, the referenced item must be a permanent object. Specifying a correlation name or a derived
table returns an error.

When %TYPE is specified, other attributes, such as default values, constraints, and whether NULLs are allowed,
are not part of the definition that is inherited and must be specified separately.

When defining or declaring a variable, if the identifier portion of type-source is one of the following, then the
identifier portion must be quoted:

● IN

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 115
● OUT
● INOUT
● DYNAMIC
● SCROLL
● NO
● INSENSITIVE
● SENSITIVE
● TIMESTAMP
● a name that starts with #

For example, the statement below declares a variable called DYNAMIC. It then declares another variable called
var1, and sets its data type to that of DYNAMIC (INT). Since DYNAMIC is one of the keywords that must be
quoted, quotes are placed around it:

BEGIN
DECLARE dynamic INT;
DECLARE var1 "DYNAMIC"%TYPE;
SET var1 = 1;
MESSAGE var1;
END

Privileges

None.

Side effects

None.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
In addition to the following examples, there are examples in the documentation for the SQL statements and
functions that support specifying the %TYPE attribute.

The following statement creates a procedure, DepartmentsCloseToCustomerLocation, and sets its IN


parameter to the data type of the ID column in the Customers table using a %TYPE attribute:

CREATE OR REPLACE PROCEDURE DepartmentsCloseToCustomerLocation( IN customer_ID


Customers.ID%TYPE )
BEGIN

SQL Anywhere - SQL Reference


116 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
DECLARE cust_rec Customers%ROWTYPE;
SELECT City, State, Country
INTO cust_rec.City, cust_rec.State, cust_rec.Country
FROM Customers
WHERE ID = customer_ID;
SELECT Employees.Surname, Employees.GivenName, Departments.DepartmentName
FROM Employees JOIN Departments
ON Departments.DepartmentHeadID = Employees.EmployeeID
WHERE Employees.City = cust_rec.City
AND Employees.State = cust_rec.State
AND Employees.Country = cust_rec.Country;
END;
CALL DepartmentsCloseToCustomerLocation(158);

The following statement casts a value to the data type defined for the BirthDate column (DATE data type) of
the Employees table:

SELECT CAST ( '1966-10-30' AS Employees.BirthDate%TYPE );

Related Information

%TYPE and %ROWTYPE attributes [page 112]


DECLARE statement [page 1014]

1.1.9.2 %ROWTYPE attribute syntax

Sets the data type to the composite data type of a row in a specified table, view, table reference variable, or
cursor.

Syntax

rowtype-source%ROWTYPE
| ROWTYPE OF ( rowtype-source )
rowtype-source :
[ owner. ]{ table-name | view-name }
| cursor-name
| TABLE REF ( table-reference-variable )

Parameters

table-name

The name of a table.

When specifying table-name, the data type of the %ROWTYPE variable is comprised of the data types of the
columns in table-name.
view-name

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 117
The name of an enabled view (including materialized views). Materialized views must be initialized as well.

When specifying view-name, the data type of the %ROWTYPE variable is comprised of the data types of the
columns in view-name.
cursor-name

The name of a cursor.

When specifying cursor-name, the data type of the %ROWTYPE variable is comprised of the data types of
the select items for the cursor.
table-reference-variable

The name of a table reference variable.

When specifying a table reference variable, the data type of the %ROWTYPE variable is comprised of the data
types of the columns in the table referenced in table-reference-variable.

Remarks

When creating a %ROWTYPE variable, other attributes, such as default values, constraints, and whether NULLs
are allowed, are not part of the definition that is inherited, and must be specified separately.

Restrictions when specifying %ROWTYPE with a table, view, or cursor reference:

When creating or altering procedures, views, and domains, an object referenced in a %ROWTYPE
specification must be a permanent object. A reference to a temporary table returns an error.

If you declare a row variable and the argument to the %ROWTYPE construct is a cursor which is not yet
opened, it is possible that the schema of the cursor will be different at open time if any of the underlying
objects have changed. It is safer to declare row variables based on cursors that are already open.

When %ROWTYPE is specified in an IS OF search expression, a WITH hint expression in a FROM clause, or a
CAST or CONVERT function, the referenced item must be a permanent object. Specifying a temporary table,
correlation name, or a derived table, returns an error.

When rowtype-source references a cursor, the names of the items in the cursor (for example, column
names) must be simple names, or an alias. If the select list item names in the cursor cannot be successfully
derived, then an error is returned.

When defining or declaring a variable, if the identifier portion of rowtype-source is one of the following, then
the identifier portion must be quoted:

● IN
● OUT
● INOUT
● DYNAMIC
● SCROLL
● NO
● INSENSITIVE
● SENSITIVE
● TIMESTAMP
● identifiers that start with #

SQL Anywhere - SQL Reference


118 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Restrictions when specifying %ROWTYPE with a table reference variable (TABLE REF (table-reference-
variable) %ROWTYPE):

Specifying %ROWTYPE with a table reference variable is not supported: when creating or altering procedures,
views, and domains. Similarly, specifying %ROWTYPE with a table reference variable is not supported in an IS
OF search expression, or in a WITH hint expression in a FROM clause, or in a CAST or CONVERT function.

When rowtype-source references a table reference variable, the table reference variable must already be
initialized when the %ROWTYPE is processed. If TABLE REF (table-reference-variable) %ROWTYPE is
used in a statement that is in a batch or procedure, statement must be nested inside another BEGIN...END
block after the table reference variable has been assigned a value or passed as a parameter.

Privileges

None.

Side effects

None.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
In addition to the following examples, there are examples in the documentation for the SQL statements and
functions that support specifying the %ROWTYPE attribute.

The following example creates a new variable, ItemsForSale, and uses the %ROWTYPE attribute to set its data
type to a composite data type comprised of the columns defined for the Products table:

CREATE VARIABLE ItemsForSale Products%ROWTYPE;

The following statement declares a variable, cust_rec, and sets its data type to the composite data type of a
row in the Customers table:

CREATE OR REPLACE PROCEDURE DepartmentsCloseToCustomerLocation( IN customer_ID


Customers.ID%TYPE )
BEGIN
DECLARE cust_rec Customers%ROWTYPE;
SELECT City, State, Country
INTO cust_rec.City, cust_rec.State, cust_rec.Country
FROM Customers
WHERE ID = customer_ID;
SELECT Employees.Surname, Employees.GivenName, Departments.DepartmentName

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 119
FROM Employees JOIN Departments
ON Departments.DepartmentHeadID = Employees.EmployeeID
WHERE Employees.City = cust_rec.City
AND Employees.State = cust_rec.State
AND Employees.Country = cust_rec.Country;
END;
CALL DepartmentsCloseToCustomerLocation(158);

Related Information

%TYPE and %ROWTYPE attributes [page 112]


DECLARE statement [page 1014]

1.1.10 SQL variables

The supported variables can be grouped by scope: connection, database, and global.

When a variable is created, the initial value is set to NULL unless a default is specified. The value can subsequently
be changed by using the SET statement, the UPDATE statement, or a SELECT statement with an INTO clause.

Variables are not affected by COMMIT or ROLLBACK statements.

Connection-scope variables

Connection-scope variables are set and used in the context of a connection. They are not available to other
connections. There are two types of connection-scope variables: connection-level and local (also referred to
as declared). You can also create connection-scope variables of type TABLE REF to hold references to tables;
these are called table reference variables.

Connection-level variables

Connection-level variables are created by using the CREATE VARIABLE statement and are typically used
to make values available to any procedure executed by the connection.

Connection-level variables persist only for the duration of the connection or until the variable is explicitly
dropped by using the DROP VARIABLE statement

Local (declared) variables

Local variables are created by using the DECLARE statement inside of a BEGIN...END block, and are
typically used to store and modify values within the same compound statement that the local variable is
declared in. Local variable values are not available for use outside of the context of the BEGIN...END
block.

Local variables persist only for the duration of the BEGIN...END block in which they are declared, and they
can also be dropped.
Database-scope variables

Database-scope variables are used in the context of the database (instead of connection), and are a great way
to share values across connections. Their intended use is to store small, infrequently changing, shared values.
Storing large or frequently changing values may affect the performance of your application, and is not

SQL Anywhere - SQL Reference


120 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
recommended. The initial values of database-scope variables persist after the database restarts (that is,
changes to their initial value do not persist between database restarts). Database-scope variables can be
used in the same manner as connection-scope and global variables, but they cannot be defined with the data
type ROW, ARRAY, or TABLE REF.

Database-scope variables owned by users

When a database-scope variable is owned by a user, only that user can select from, and update, that
variable, and can do so regardless of the connection.

Database-scope variables can also be owned by a role. However, the only access to a database-scope
variable owned by a role is through the stored procedures, user-defined functions, and events owned by
that role.
Database-scope variables owned by PUBLIC

Database variables owned by PUBLIC are available to all users and connections provided the users have
the right system privileges.

Access to, and administration of, database-scope variables requires system privileges that vary depending on
who owns the variable (self, another user, or PUBLIC). The following table summarizes the privileges required
to access and administer database-scope variables:

Table 1: Privileges required for administering database-scope variables


Action Owned by Privilege required

Create a database-scope variable self CREATE DATABASE VARIABLE or


MANAGE ANY DATABASE VARIABLE

Create a database-scope variable another user MANAGE ANY DATABASE VARIABLE

Create a database-scope variable PUBLIC MANAGE ANY DATABASE VARIABLE

Update a database-scope variable self none required

Update a database-scope variable another user not allowed

Update a database-scope variable PUBLIC UPDATE PUBLIC DATABASE VARIA­


BLE

Select from a database-scope variable self none

Select from a database-scope variable another user not allowed

Select from a database-scope variable PUBLIC SELECT PUBLIC DATABASE VARIA­


BLE

Drop a database-scope variable self none required

Drop a database-scope variable another user MANAGE ANY DATABASE VARIABLE

Drop a database-scope variable PUBLIC MANAGE ANY DATABASE VARIABLE

Global variables

Global variables are used in the context of the database, but can only be set by the database server. Although
you cannot directly set a global variable, some global variable values are indirectly set in response to user
activity. For example, some global variables, such as @@identity, hold connection-specific information, while
other variables, such as @@connections, have values that are common to all connections.

Global variables are visually distinguished from other variables by having two @ signs preceding their names.
For example, @@error and @@rowcount are global variables.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 121
Variables and aliases with identical names

It is possible to have a statement that has aliases and variables with identical names. This is the sequence the
database server follows when processing an identifier to help you know how the reference is resolved:

1. Match any aliases specified in the query SELECT list.


2. Match column names for any referenced tables.
3. Assume the name is a variable.

Standards

ANSI/ISO SQL Standard

Variables declared within SQL stored procedures or functions by using the DECLARE statement is supported
in the ANSI/ISO SQL Standard as SQL Language Feature P002, "Computational completeness". CREATE
VARIABLE, DROP VARIABLE, and global variables are not in the ANSI/ISO SQL Standard.

In this section:

@@identity global variable [page 122]


The @@identity variable holds the most recent value inserted by the current connection into an IDENTITY
column, a DEFAULT AUTOINCREMENT column, or a DEFAULT GLOBAL AUTOINCREMENT column, or
zero if the most recent insert was into a table that had no such column.

Related Information

CREATE VARIABLE statement [page 996]


DROP VARIABLE statement [page 1089]
SET statement [page 1328]
DECLARE statement [page 1014]
UPDATE statement [page 1395]
SYSDATABASEVARIABLE system view [page 1868]

1.1.10.1 @@identity global variable

The @@identity variable holds the most recent value inserted by the current connection into an IDENTITY column,
a DEFAULT AUTOINCREMENT column, or a DEFAULT GLOBAL AUTOINCREMENT column, or zero if the most
recent insert was into a table that had no such column.

The value of @@identity is connection specific. If a statement inserts multiple rows, @@identity reflects the
IDENTITY value for the last row inserted. If the affected table does not contain an IDENTITY column, @@ identity
is set to zero.

SQL Anywhere - SQL Reference


122 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
The value of @@identity is not affected by the failure of an INSERT or SELECT INTO statement, or the rollback of
the transaction that contained it. @@identity retains the last value inserted into an IDENTITY column, even if the
statement that inserted it fails to commit.

@@identity and triggers

When an insert causes referential integrity actions or fires a trigger, @@identity behaves like a stack. For example,
if an insert into a table T1 (with an IDENTITY or AUTOINCREMENT column) fires a trigger that inserts a row into
table T2 (also with an IDENTITY or AUTOINCREMENT column), then the value returned to the application or
procedure which carried out the insert is the value inserted into T1. Within the trigger, @@identity has the T1 value
before the insert into T2 and the T2 value after. The trigger can copy the values to local variables if it needs to
access both.

Standards

ANSI/ISO SQL Standard

Global variables are not in the standard.

1.1.11 Comments

Comments are used to attach explanatory text to SQL statements or statement blocks. The database server does
not execute comments.

The following comment indicators are supported:

-- (Double hyphen)

The database server ignores any remaining characters on the line. This is the ANSI/ISO SQL Standard
comment indicator.

You can add and remove this comment indicator by selecting text and pressing Ctrl+Minus Sign in Interactive
SQL or on the SQL tab of the Procedures & Functions window of SQL Central.

The SQL comment indicator is added to the beginning of each line of the selected text. If no text is selected,
the comment indicator is added to the beginning of the current line.
// (Double slash)

The double slash has the same meaning as the double hyphen.

You can add and remove this comment indicator by selecting text and pressing Ctrl+Forward Slash in
Interactive SQL or on the SQL tab of the Procedures & Functions window of SQL Central.

The SQL comment indicator is added to the beginning of each line of the selected text. If no text is selected,
the comment indicator is added to the beginning of the current line.
/* ... */ (Slash-asterisk)

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 123
Any characters between the two comment markers are ignored. The two comment markers can be on the
same or different lines. Comments indicated in this style can be nested, but nested comments must be
balanced. Any comments made inside the comment block must not contain single instances of the starting
comment marker. This style of commenting is also called C-style comments.

Example
The following example illustrates the use of double-hyphen comments:

CREATE FUNCTION fullname ( firstname CHAR(30),


lastname CHAR(30))
RETURNS CHAR(61)
-- fullname concatenates the firstname and lastname
-- arguments with a single space between.
BEGIN
DECLARE name CHAR(61);
SET name = firstname || ' ' || lastname;
RETURN ( name );
END;

The following example illustrates the use of C-style comments:

/* Lists the names and employee IDs of employees


who work in the sales department. */
CREATE VIEW SalesEmployees AS
SELECT EmployeeID, Surname, GivenName
FROM GROUPO.Employees
WHERE DepartmentID = 200;

Standards

ANSI/ISO SQL Standard

The use of double-minus signs for a comment is a core feature of the ANSI/ISO SQL Standard. The use of C-
style, bracketed comments (/* ... */) is SQL Language Feature T351. Double-slash comments (//) are
supported by the software but are not in the standard.

1.1.12 Named parameters

Functions and procedures that are referenced from the CALL statement, the EXECUTE statement (Transact-
SQL), the FROM clause of a DML statement, and the TRIGGER EVENT statement support positional parameters
and named parameters. Named parameters support specifying any subset of the available parameters in any
order.

Named parameters cannot be used with functions except in CALL statements. Named parameters cannot be
used with built-in functions such as ABS, COMPRESS, DAYNAME.The following named parameter syntaxes are
supported:

● parameter-name = parameter-value
● parameter-name => parameter-value

SQL Anywhere - SQL Reference


124 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Example
The following example uses = to specify a named parameter:

CALL sa_conn_properties( connidparm = 1 );

This example uses named parameters when calling the system procedure sp_remote_exported_keys, and
returns information about the foreign key relationships in the Employees table owned by HR on the remote
server named RemoteSA:

CALL sp_remote_exported_keys(
@server_name => 'RemoteSA',
@table_owner => 'HR',
@table_name => 'Employees' );

This example uses named parameters in the TRIGGER EVENT statement.

CREATE EVENT ev_TimePlace


HANDLER BEGIN
MESSAGE 'ev_TimePlace - was triggered at ' || event_parameter( 'what_time' )
|| ' in ' || event_parameter( 'what_place' );
END;
TRIGGER EVENT ev_TimePlace( what_time => string( current timestamp ), what_place
=> 'Waterloo' );

Named parameters cannot be used with functions, except in CALL statements. The following is an example.

CREATE OR REPLACE FUNCTION PLUS( val1 INTEGER DEFAULT 0, val2 INTEGER DEFAULT 0 )
RETURNS INTEGER
BEGIN
RETURN val1 + val2;
END
CREATE VARIABLE rslt INTEGER;
rslt = CALL PLUS( val1=1, val2=99 );
SELECT rslt;

Named parameters cannot be used with functions in general expressions. The following is an example of the
syntax that must be used.

SELECT PLUS( 1, 99 );

Standards

ANSI/ISO SQL Standard

The = operator is not in the standard.

Related Information

CALL statement [page 760]


EXECUTE IMMEDIATE statement [SP] [page 1094]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 125
EXECUTE statement [ESQL] [page 1097]
EXECUTE statement [T-SQL] [page 1100]
FROM clause [page 1116]
TRIGGER EVENT statement [page 1369]

1.2 SQL data types


There are many SQL data types supported by the software.

In this section:

Character data types [page 127]


Character data types store strings of letters, numbers, and other symbols.

Numeric data types [page 139]


Numeric data types store numerical data.

Money data types [page 151]


Money data types are used for storing monetary data.

Bit array data types [page 153]


A bit array is similar to a character string, except that the individual pieces are bit data (0s (zeros) and 1s
(ones)) instead of characters. Typically, bit arrays are used to hold a string of Boolean values.

Date and time data types [page 155]


Date values can be output in full century format, and the internal storage of dates always explicitly
includes the century portion of a year value.

Binary data types [page 174]


Binary data types store binary data, including images and other types of information that are not
interpreted by the database.

ROW and ARRAY composite data types [page 180]


Composite data types are values that are comprised of zero or more elements, where each element has a
value of a particular data type. Currently only ROW and ARRAY composite data types are supported.

TABLE REF data type [page 182]


The TABLE REF data type stores a reference to a base table, temporary table, or view. This data type is
only for use with connection-scope variables.

Spatial data types [page 186]


Many spatial data types are supported. The documentation for these data types are located with the
spatial SQL API documentation.

Domains [page 186]


Domains are aliases for built-in data types, including precision and scale values where applicable, and
optionally including DEFAULT values and CHECK conditions. Some domains, such as the monetary data
types, are predefined, but you can add more of your own.

Data type comparisons [page 187]


When a comparison (such as =) is performed between arguments with different data types, one or more
arguments must be converted so that the comparison operation is done using one data type.

Data type conversions [page 194]

SQL Anywhere - SQL Reference


126 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Type conversions can happen automatically, or they can be explicitly requested using the CAST or
CONVERT function. The following functions can also be used to force type conversions:

1.2.1 Character data types

Character data types store strings of letters, numbers, and other symbols.

There are classes of character data types and some domains defined using those types:

CHAR, VARCHAR, LONG VARCHAR

Character data stored in a single- or multibyte character set, often chosen to correspond most closely to the
primary language or languages stored in the database.
NCHAR, NVARCHAR, LONG NVARCHAR

Character data stored in the UTF-8 Unicode encoding. All Unicode code points can be stored using these
types, regardless of the primary language or languages stored in the database.
TEXT, UNIQUEIDENTIFIERSTR, XML

Domains based on other character data types.

UltraLite: UltraLite supports the CHAR, VARCHAR, and LONG VARCHAR data types, which are stored in a single-
or multi- byte character set, and are often chosen to correspond most closely to the primary language or
languages stored in the database.

Storage

All character data values are stored in the same manner. By default, values up to 128 bytes are stored in a single
piece. Values longer than 128 bytes are stored with a 4-byte prefix kept locally on the database page and the full
value stored in one or more other database pages. These default sizes are controlled by the INLINE and PREFIX
clauses of the CREATE TABLE statement.

UltraLite: Fixed character types, such as VARCHAR, are embedded in the row whereas long character types, such
as LONG VARCHAR, are stored separately. Consider your page size when creating a table with many columns of
large fixed types. A full row must fit on a page, and fixed character column types are stored with a row. For
example, a database created with a page size of 1000 cannot hold character values larger than 1000 because they
cannot fit on the page.

In this section:

CHAR data type [page 128]


The CHAR data type stores character data, up to 32767 bytes.

LONG NVARCHAR data type [page 130]


The LONG NVARCHAR data type stores Unicode character data of arbitrary length.

LONG VARCHAR data type [page 131]


The LONG VARCHAR data type stores character data of arbitrary length.

NCHAR data type [page 132]


The NCHAR data type stores Unicode character data, up to 32767 characters.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 127
NTEXT data type [page 133]
The NTEXT data type stores Unicode character data of arbitrary length.

NVARCHAR data type [page 134]


The NVARCHAR data type stores Unicode character data, up to 32767 characters.

TEXT data type [page 135]


The TEXT data type stores character data of arbitrary length.

UNIQUEIDENTIFIERSTR data type [page 136]


UNIQUEIDENTIFIERSTR is a domain, implemented as CHAR(36).

VARCHAR data type [page 136]


The VARCHAR data type stores character data, up to 32767 bytes.

XML data type [page 138]


The XML data type stores character data of arbitrary length, and stores XML documents.

Related Information

CREATE TABLE statement [page 956]

1.2.1.1 CHAR data type

The CHAR data type stores character data, up to 32767 bytes.

Syntax

CHAR [ ( max-length [ CHAR | CHARACTER ] ) ]

UltraLite:

CHAR [ ( max-length) ]

Parameters

max-length

The maximum length of the string. If byte-length semantics are used (CHAR or CHARACTER is not specified
as part of the length), then the length is in bytes, and the length must be in the range 1 to 32767. If the length
is not specified, then it is 1.

If character-length semantics are used (CHAR or CHARACTER is specified as part of the length), then the
length is in characters, and you must specify max-length. max-length can be a maximum of 32767
characters.

SQL Anywhere - SQL Reference


128 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Remarks

Multibyte characters can be stored as CHAR, but the declared length refers to bytes, not characters, unless
character-length semantics are used.

CHAR can also be specified as CHARACTER. Regardless of which syntax is used, the data type is described as
CHAR.

CHAR is semantically equivalent to VARCHAR, although they are different types. CHAR is a variable-length type.
In other relational database management systems, CHAR is a fixed-length type, and data is padded with blanks to
max-length bytes of storage. SQL Anywhere does not blank-pad stored character data.

How CHAR columns are described depends on the client interface, the character sets used, and if character-
length semantics are used. For example, in Embedded SQL the described length is the maximum number of bytes
in the client character set. If the described length would be more than 32767 bytes, the column is described as
type DT_LONGVARCHAR. The following table shows some Embedded SQL examples and the results returned
when a DESCRIBE is performed:

Type being described Database character set Client character set Result of DESCRIBE

CHAR(10) Windows-1252 Windows-1252 DT_FIXCHAR length 10

CHAR(10) UTF-8 UTF-8 DT_FIXCHAR length 10

CHAR(10) Windows-1252 UTF-8 DT_FIXCHAR length 30

CHAR(20000) Windows-31J UTF-8 DT_LONGVARCHAR

CHAR(10 CHAR ) Windows-1252 Windows-1252 DT_FIXCHAR length 10

CHAR(10 CHAR ) UTF-8 UTF-8 DT_FIXCHAR length 40

For ODBC, CHAR is described as either SQL_CHAR or SQL_VARCHAR depending on the


odbc_distinguish_char_and_varchar option.

UltraLite remarks

CHAR is a domain, implemented as VARCHAR.

Standards

ANSI/ISO SQL Standard

Compatible with the ANSI/ISO SQL Standard. In the standard, character-length semantics are the default,
whereas in the software, byte-length semantics are the default. There are minor inconsistencies with the SQL
standard due to case-insensitive collation support and the software's support for blank-padding.

The ANSI/ISO SQL Standard supports explicit character- or byte-length semantics as SQL Language Feature
T061.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 129
Related Information

VARCHAR data type [page 136]


LONG VARCHAR data type [page 131]
NCHAR data type [page 132]

1.2.1.2 LONG NVARCHAR data type

The LONG NVARCHAR data type stores Unicode character data of arbitrary length.

Syntax

LONG NVARCHAR

Remarks

The maximum size is 2 GB minus 1 byte (231 - 1).

Characters are stored in UTF-8. Each character requires from one to four bytes. The maximum number of
characters that can be stored in a LONG NVARCHAR is over 500 million and possibly over 2 billion, depending on
the lengths of the characters stored.

When an Embedded SQL client performs a DESCRIBE on a LONG NVARCHAR column, the data type returned is
either DT_LONGVARCHAR or DT_LONGNVARCHAR, depending on whether the db_change_nchar_charset
function has been called.

For ODBC, a LONG NVARCHAR expression is described as SQL_WLONGVARCHAR.

Standards

ANSI/ISO SQL Standard

The use of LONG NVARCHAR to declare a national character string is not in the standard.

Related Information

NCHAR data type [page 132]


NVARCHAR data type [page 134]
LONG VARCHAR data type [page 131]

SQL Anywhere - SQL Reference


130 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.2.1.3 LONG VARCHAR data type

The LONG VARCHAR data type stores character data of arbitrary length.

Syntax

LONG VARCHAR

Remarks

The maximum byte size is 2 GB minus 1 byte (231 - 1).

You can cast strings to/from LONG VARCHAR data. LONG VARCHAR data cannot be concatenated.

Conditions in SQL statements, such as in the WHERE clause, cannot operate on LONG VARCHAR columns. Only
INSERT, UPDATE, and DELETE operations are allowed on LONG VARCHAR columns. LONG VARCHAR columns
can also be included in the result set of a SELECT query.

Multibyte characters can be stored as LONG VARCHAR, but the length is in bytes, not characters.

UltraLite: Indexes cannot be created on a LONG VARCHAR type. A LONG VARCHAR type can only be used in the
LENGTH and CAST functions.

Standards

ANSI/ISO SQL Standard

Large object support is SQL Language Feature T041.

Related Information

CHAR data type [page 128]


VARCHAR data type [page 136]
LONG NVARCHAR data type [page 130]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 131
1.2.1.4 NCHAR data type

The NCHAR data type stores Unicode character data, up to 32767 characters.

Syntax

NCHAR [ ( max-length ) ]

Parameters

max-length

The maximum length of the string, in characters. The length must be in the range 1 to 32767. If the length is
not specified, then it is 1.

Remarks

Characters are stored using UTF-8 encoding. The maximum number of bytes of storage required is four multiplied
by max-length. However, the actual number of bytes of storage required is usually much less.

For example, the encoding of the character Yee from the Deseret alphabet (U+10437) in UTF-8 requires 4 bytes.
The following SQL query displays the character Yee when using Interactive SQL.

SELECT CAST(0xF09090B7 as NCHAR(1));

NCHAR can also be specified as NATIONAL CHAR or NATIONAL CHARACTER. Regardless of which syntax is
used, the data type is described as NCHAR.

NCHAR is semantically equivalent to NVARCHAR, although they are different types. Note that NCHAR is treated
as a variable-length type and columns are not blank-padded when stored.

When an Embedded SQL client performs a DESCRIBE on an NCHAR column, the data type returned is either
DT_FIXCHAR or DT_NFIXCHAR, depending on whether the db_change_nchar_charset function has been called.

Also, when an Embedded SQL client performs a DESCRIBE on an NCHAR column, the length returned is the
maximum byte length in the client NCHAR character set. For example, for an Embedded SQL client using the
Western European character set cp1252 as the NCHAR character set, an NCHAR(10) column is described as type
DT_NFIXCHAR of length 10 (10 characters multiplied by a maximum one byte per character). For an Embedded
SQL client using the Japanese character set cp932, the same column is described as type DT_NFIXCHAR of
length 20 (10 characters multiplied by a maximum two bytes per character). If the described length would return
more then 32767 bytes, the column is described as type DT_LONGNVARCHAR.

For ODBC, if the byte length (octet length) is less than 32767, NCHAR is described as SQL_WCHAR; otherwise, it
is described as SQL_WLONGVARCHAR. For example, NCHAR(8192) requires a maximum 32768 bytes of storage
so it is described as SQL_WLONGVARCHAR with octet length 2147483647.

SQL Anywhere - SQL Reference


132 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Standards

ANSI/ISO SQL Standard

National character support is Feature F421.

Related Information

CHAR data type [page 128]


NVARCHAR data type [page 134]
LONG NVARCHAR data type [page 130]

1.2.1.5 NTEXT data type

The NTEXT data type stores Unicode character data of arbitrary length.

Syntax

NTEXT

Remarks

NTEXT is a domain, implemented as a LONG NVARCHAR.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

LONG NVARCHAR data type [page 130]


TEXT data type [page 135]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 133
1.2.1.6 NVARCHAR data type

The NVARCHAR data type stores Unicode character data, up to 32767 characters.

Syntax

NVARCHAR [ ( max-length ) ]

Parameters

max-length

The maximum length of the string, in characters. The length must be in the range 1 to 32767. If the length is
not specified, then it is 1.

Remarks

Characters are stored in UTF-8 encoding. The maximum number of bytes of storage required is four multiplied by
max-length, although the actual storage required is usually much less.

For example, the encoding of the character Yee from the Deseret alphabet (U+10437) in UTF-8 requires 4 bytes.
The following SQL query displays the character Yee when using Interactive SQL.

SELECT CAST(0xF09090B7 as NVARCHAR(1));

NVARCHAR can also be specified as NCHAR VARYING, NATIONAL CHAR VARYING, or NATIONAL CHARACTER
VARYING. Regardless of which syntax is used, the data type is described as NVARCHAR.

When an Embedded SQL client performs a DESCRIBE on a NVARCHAR column, the data type returned is either
DT_VARCHAR or DT_NVARCHAR, depending on whether the db_change_nchar_charset function has been called.

Also, when an Embedded SQL client performs a DESCRIBE on an NVARCHAR column, the length returned is the
maximum byte length in the client NCHAR character set. For example, for an Embedded SQL client using the
Western European character set cp1252 as the NCHAR character set, an NVARCHAR(10) column is described as
type DT_NVARCHAR of length 10 (10 characters multiplied by a maximum of one byte per character). For an
Embedded SQL client using the Japanese character set cp932, the same column is described as type
DT_NVARCHAR of length 20 (10 characters multiplied by a maximum two bytes per character). If the describe
length would return more than 32767 bytes, the column is described as type DT_LONGNVARCHAR.

For ODBC, if the byte length (octet length) is less than 32767, NVARCHAR is described as SQL_WVARCHAR;
otherwise, it is described as SQL_WLONGVARCHAR. For example, NVARCHAR(8192) requires a maximum 32768
bytes of storage so it is described as SQL_WLONGVARCHAR with octet length 2147483647.

SQL Anywhere - SQL Reference


134 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Standards

ANSI/ISO SQL Standard

National character support is SQL Language Feature F421.

Related Information

NCHAR data type [page 132]


LONG NVARCHAR data type [page 130]
VARCHAR data type [page 136]

1.2.1.7 TEXT data type

The TEXT data type stores character data of arbitrary length.

Syntax

TEXT

Remarks

TEXT is a domain, implemented as a LONG VARCHAR.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

LONG VARCHAR data type [page 131]


NTEXT data type [page 133]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 135
1.2.1.8 UNIQUEIDENTIFIERSTR data type

UNIQUEIDENTIFIERSTR is a domain, implemented as CHAR(36).

Syntax

UNIQUEIDENTIFIERSTR

Remarks

Used for remote data access, when mapping Microsoft SQL Server uniqueidentifier columns.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

STRTOUUID function [String] [page 552]

1.2.1.9 VARCHAR data type

The VARCHAR data type stores character data, up to 32767 bytes.

Syntax

VARCHAR [ ( max-length [ CHAR | CHARACTER ] ) ]

UltraLite:

VARCHAR [ ( max-length) ]

Parameters

max-length

SQL Anywhere - SQL Reference


136 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
The maximum length of the string. This default value is 1.

If byte-length semantics are used (CHAR or CHARACTER is not specified as part of the length), then the
length is in bytes, and the length must be in the range of 1 to 32767. If character-length semantics are used
(CHAR or CHARACTER is specified as part of the length), then the length is in characters, and you must
specify max-length. max-length can be a maximum of 32767 characters.

UltraLite: UltraLite databases only support byte-length semantics. A non-English character can require up to
3 bytes of storage.

Remarks

Multibyte characters can be stored as VARCHAR, but the declared length refers to bytes, not characters.

UltraLite: UltraLite compacts data as much as possible. When a VARCHAR value does not require the number of
bytes specified by max-length, then only the number of bytes needed to store the value is used. When evaluating
expressions, the maximum length for a temporary character value is 2048 bytes.

Caution
UltraLite:

Although it is possible to create a table with a VARCHAR column where the max-length exceeds the page size,
an error occurs if you insert a value with a length exceeding that page size.

For ODBC, VARCHAR is described as SQL_VARCHAR. VARCHAR can also be specified as CHAR VARYING or
CHARACTER VARYING. Regardless of which syntax is used, the data type is described as VARCHAR. VARCHAR is
semantically equivalent to CHAR, although they are different types. In SQL Anywhere, VARCHAR is a variable-
length type. In other relational database management systems, VARCHAR is a fixed-length type, and data is
padded with blanks to max-length bytes of storage. SQL Anywhere does not blank-pad stored character data.
How VARCHAR columns are described depends on the client interface, the character sets used, and if character-
length semantics are used. For example, in Embedded SQL the described length is the maximum number of bytes
in the client character set. If the described length would be more than 32767 bytes, the column is described as
type DT_LONGVARCHAR. The following table shows some Embedded SQL examples and the results returned
when a DESCRIBE is performed:

Type being described Database character set Client character set Result of DESCRIBE

VARCHAR(10) Windows-1252 Windows-1252 DT_VARCHAR length 10

VARCHAR(10) UTF-8 UTF-8 DT_VARCHAR length 10

VARCHAR(10) Windows-1252 UTF-8 DT_VARCHAR length 30

VARCHAR(20000) Windows-31J UTF-8 DT_LONGVARCHAR

VARCHAR(10 CHAR ) Windows-1252 Windows-1252 DT_VARCHAR length 10

VARCHAR(10 CHAR ) UTF-8 UTF-8 DT_VARCHAR length 40

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 137
Standards

ANSI/ISO SQL Standard

Compatible with the ANSI/ISO SQL Standard. In the standard, character-length semantics are the default,
whereas in the software, byte-length semantics are the default. There are minor inconsistencies with the SQL
standard due to case-insensitive collation support and support for blank-padding by the software.

The ANSI/ISO SQL Standard supports explicit character- or byte-length semantics as SQL Language Feature
T061.

Related Information

CHAR data type [page 128]


LONG VARCHAR data type [page 131]
NVARCHAR data type [page 134]

1.2.1.10 XML data type

The XML data type stores character data of arbitrary length, and stores XML documents.

Syntax

XML

Remarks

The maximum size is 2 GB minus 1 byte (231 - 1).

Data of type XML is not quoted when generating element content from relational data.

You can cast between the XML data type and any other data type that can be cast to or from a string. There is no
checking that the string is well-formed when it is cast to XML.

When an Embedded SQL client application performs a DESCRIBE on an XML column, it is described as LONG
VARCHAR.

Standards

ANSI/ISO SQL Standard

The XML data type is SQL Language Feature X010.

SQL Anywhere - SQL Reference


138 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.2.2 Numeric data types
Numeric data types store numerical data.

The NUMERIC and DECIMAL data types, and the various INTEGER data types, are sometimes called exact
numeric data types, in contrast to the approximate numeric data types FLOAT, DOUBLE, and REAL.

The exact numeric data types are those for which precision and scale values can be specified, while approximate
numeric data types are stored in a predefined manner. Only exact numeric data is guaranteed accurate to the least
significant digit specified after an arithmetic operation.

Data type lengths and precision of less than one are not allowed.

Compatibility

Be careful when using default precision and scale settings for NUMERIC and DECIMAL data types because these
settings could be different in other database solutions. The default precision is 30 and the default scale is 6.

The FLOAT ( p ) data type is a synonym for REAL or DOUBLE, depending on the value of p. For SQL Anywhere, the
cutoff is platform-dependent, but on all platforms the cutoff value is greater than 15.

Only the NUMERIC data type with scale = 0 can be used for the Transact-SQL identity column. Avoid default
precision and scale settings for NUMERIC and DECIMAL data types, because these are different between SQL
Anywhere and Adaptive Server Enterprise. In SQL Anywhere, the default precision is 30 and the default scale is 6.
In Adaptive Server Enterprise, the default precision is 18 and the default scale is 0.

In this section:

BIGINT data type [page 140]


The BIGINT data type stores BIGINTs, which are integers requiring 8 bytes of storage.

BIT data type [page 141]


The BIT data type stores a bit (0 or 1).

DECIMAL data type [page 142]


The DECIMAL data type is a decimal number with precision total digits and with scale digits after the
decimal point.

DOUBLE data type [page 143]


The DOUBLE data type stores double-precision floating-point numbers.

FLOAT data type [page 144]


The FLOAT data type stores a floating-point number, which can be single or double precision.

INTEGER data type [page 146]


The INTEGER data type stores integers that require 4 bytes of storage.

NUMERIC data type [page 147]


The NUMERIC data type stores decimal numbers with precision total digits and with scale digits after
the decimal point.

REAL data type [page 148]


The REAL data type stores single-precision floating-point numbers stored in 4 bytes.

SMALLINT data type [page 149]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 139
The SMALLINT data type stores integers that require 2 bytes of storage.

TINYINT data type [page 150]


The TINYINT data type stores unsigned integers requiring 1 byte of storage.

1.2.2.1 BIGINT data type

The BIGINT data type stores BIGINTs, which are integers requiring 8 bytes of storage.

Syntax

[ UNSIGNED ] BIGINT

Remarks

The BIGINT data type is an exact numeric data type: its accuracy is preserved after arithmetic operations.

A BIGINT value requires 8 bytes of storage.

The range for BIGINT values is -263 to 263 - 1, or -9223372036854775808 to 9223372036854775807.

The range for UNSIGNED BIGINT values is 0 to 264 - 1, or 0 to 18446744073709551615.

By default, the data type is signed.

When converting a string to a BIGINT, leading and trailing spaces are removed. If the leading character is +, it is
ignored. If the leading character is -, the remaining digits are interpreted as a negative number. Leading 0
characters are skipped, and the remaining characters are converted to an integer value. An error is returned if the
value is out of the valid range for the destination data type, if the string contains illegal characters, or if the string
cannot be decoded as an integer value.

Standards

ANSI/ISO SQL Standard

SQL Language Feature T071.


MySQL

The UNSIGNED keyword may follow BIGINT.

Related Information

Numeric functions [page 212]

SQL Anywhere - SQL Reference


140 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Aggregate functions [page 202]
BIT data type [page 141]
INTEGER data type [page 146]
SMALLINT data type [page 149]
TINYINT data type [page 150]

1.2.2.2 BIT data type

The BIT data type stores a bit (0 or 1).

Syntax

BIT

Remarks

BIT is an integer type that can store the values 0 or 1.

By default, the BIT data type does not allow NULL.

When converting a string to a BIT, leading and trailing spaces are removed. If the leading character is +, it is
ignored. If the leading character is -, the remaining digits are interpreted as a negative number. Leading 0
characters are skipped, and the remaining characters are converted to an integer value. An error is returned if the
value is not 0 or 1.

A BIT value requires 1 byte of storage.

UltraLite: A BIT value requires 1 bit of storage.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

Numeric functions [page 212]


Aggregate functions [page 202]
BIGINT data type [page 140]
INTEGER data type [page 146]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 141
SMALLINT data type [page 149]
TINYINT data type [page 150]

1.2.2.3 DECIMAL data type

The DECIMAL data type is a decimal number with precision total digits and with scale digits after the decimal
point.

Syntax

DECIMAL [ ( precision [ , scale ] ) ]

Parameters

precision

An integer expression between 1 and 127, inclusive, that specifies the number of digits in the expression. The
default setting is 30.
scale

An integer expression between 0 and 127, inclusive, that specifies the number of digits after the decimal point.
The scale value should always be less than, or equal to, the precision value. The default setting is 6.

Change the defaults by setting database options.

UltraLite: Change the defaults by setting the appropriate creation parameter.

Remarks

The DECIMAL data type is an exact numeric data type; its accuracy is preserved to the least significant digit after
arithmetic operations.

The number of bytes required to store a decimal number can be estimated as

2 + INT(((precision - scale) + 1) / 2) + INT((scale + 1) / 2);

The INT function takes the integer portion of its argument. The storage is based on the value being stored, not on
the maximum precision and scale allowed in the column.

If you are using a precision of 20 or less and a scale of 0, it may be possible to use one of the integer data types
(BIGINT, INTEGER, SMALLINT, or TINYINT) instead. Integer values require less storage space than NUMERIC and
DECIMAL values with a similar number of significant digits. Operations on integer values, such as fetching or
inserting, and arithmetic operators, typically perform better than operations on NUMERIC and DECIMAL values.

SQL Anywhere - SQL Reference


142 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Note
If you create a column or variable of a DECIMAL data type with a precision or scale that exceeds the precision
and scale settings for the database, values are truncated to the database settings. So, if you notice truncated
values in a column or variable defined as DECIMAL, check that precision and scale do not exceed the database
option settings.

DECIMAL can also be specified as DEC. Regardless of which syntax is used, the data type is described as
DECIMAL. DECIMAL is semantically equivalent to NUMERIC.

Standards

ANSI/ISO SQL Standard

Core Feature.

Related Information

Numeric functions [page 212]


Aggregate functions [page 202]
FLOAT data type [page 144]
REAL data type [page 148]
DOUBLE data type [page 143]
NUMERIC data type [page 147]

1.2.2.4 DOUBLE data type

The DOUBLE data type stores double-precision floating-point numbers.

Syntax

DOUBLE

Remarks

The DOUBLE data type is an approximate numeric data type and subject to rounding errors after arithmetic
operations. The approximate nature of DOUBLE values means that queries using equalities should generally be
avoided when comparing DOUBLE values.

DOUBLE values require 8 bytes of storage.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 143
The range of values is -1.79769313486231e+308 to 1.79769313486231e+308, with numbers close to zero as
small as 2.22507385850721e-308. Values held as DOUBLE are accurate to 15 significant digits, but may be
subject to rounding errors beyond the fifteenth digit.

Standards

ANSI/ISO SQL Standard

Core Feature

Related Information

Numeric functions [page 212]


Numeric set conversions [page 198]
Aggregate functions [page 202]
FLOAT data type [page 144]
REAL data type [page 148]
DECIMAL data type [page 142]
NUMERIC data type [page 147]

1.2.2.5 FLOAT data type

The FLOAT data type stores a floating-point number, which can be single or double precision.

Syntax

FLOAT [ ( precision ) ]

Parameters

precision

An integer expression that specifies the number of bits in the mantissa, the decimal part of a logarithm. For
example, in the number 5.63428, the mantissa is 0.63428. The IEEE standard 754 floating-point precision is
as follows:

Supplied precision value Decimal precision Equivalent SQL data type Storage size

1-24 7 decimal digits REAL 4 bytes

SQL Anywhere - SQL Reference


144 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Supplied precision value Decimal precision Equivalent SQL data type Storage size

25-53 15 decimal digits DOUBLE 8 bytes

Remarks

When a column is created using the FLOAT ( precision ) data type, columns on all platforms are guaranteed to
hold the values to at least the specified minimum precision. REAL and DOUBLE do not guarantee a platform-
independent minimum precision.

If precision is not supplied, the FLOAT data type is a single-precision floating-point number, equivalent to the
REAL data type, and requires 4 bytes of storage.

If precision is supplied, the FLOAT data type is either single or double precision, depending on the value of
precision specified. The cutoff between REAL and DOUBLE is platform-dependent. Single-precision FLOAT values
require 4 bytes of storage, and double-precision FLOAT values require 8 bytes.

The FLOAT data type is an approximate numeric data type. It is subject to rounding errors after arithmetic
operations. The approximate nature of FLOAT values means that queries using equalities should be avoided when
comparing FLOAT values.

Standards

ANSI/ISO SQL Standard

Core Feature.

Related Information

Numeric functions [page 212]


Aggregate functions [page 202]
DOUBLE data type [page 143]
REAL data type [page 148]
DECIMAL data type [page 142]
NUMERIC data type [page 147]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 145
1.2.2.6 INTEGER data type

The INTEGER data type stores integers that require 4 bytes of storage.

Syntax

[ UNSIGNED ] INTEGER

Remarks

The INTEGER data type is an exact numeric data type; its accuracy is preserved after arithmetic operations.

If you specify UNSIGNED, the integer can never be assigned a negative number. By default, the data type is
signed.

The range for INTEGER values is -231 to 231 - 1, or -2147483648 to 2147483647.

The range for UNSIGNED INTEGER values is 0 to 232 - 1, or 0 to 4294967295.

When converting a string to an INTEGER, leading and trailing spaces are removed. If the leading character is +, it is
ignored. If the leading character is -, the remaining digits are interpreted as a negative number. Leading 0
characters are skipped, and the remaining characters are converted to an integer value. An error is returned if the
value is out of the valid range for the destination data type, if the string contains illegal characters, or if the string
cannot be decoded as an integer value.

Standards

ANSI/ISO SQL Standard

Core Feature. However, the UNSIGNED keyword is not in the standard.


MySQL

The UNSIGNED keyword may follow INTEGER.

Related Information

Numeric functions [page 212]


Aggregate functions [page 202]
BIGINT data type [page 140]
BIT data type [page 141]
SMALLINT data type [page 149]
TINYINT data type [page 150]

SQL Anywhere - SQL Reference


146 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.2.2.7 NUMERIC data type
The NUMERIC data type stores decimal numbers with precision total digits and with scale digits after the
decimal point.

Syntax

NUMERIC [ ( precision [ , scale ] ) ]

Parameters

precision

An integer expression between 1 and 127, inclusive, that specifies the number of digits in the expression. The
default setting is 30.
scale

An integer expression between 0 and 127, inclusive, that specifies the number of digits after the decimal point.
The scale value should always be less than or equal to the precision value. The default setting is 6.

Remarks

The NUMERIC data type is an exact numeric data type; its accuracy is preserved to the least significant digit after
arithmetic operations.

UltraLite: NUMERIC is a domain, implemented as DECIMAL.

The number of bytes required to store a decimal number can be estimated as

2 + INT( (BEFORE+1)/2 ) + INT( (AFTER+1)/2 );

The INT function takes the integer portion of its argument, and BEFORE and AFTER are the number of significant
digits before and after the decimal point. The storage is based on the value being stored, not on the maximum
precision and scale allowed in the column.

If you are using a precision of 20 or less and a scale of 0, it may be possible to use one of the integer data types
(BIGINT, INTEGER, SMALLINT, or TINYINT) instead. Integer values require less storage space than NUMERIC and
DECIMAL values with a similar number of significant digits. Operations on integer values, such as fetching or
inserting, and arithmetic operators, typically perform better than operations on NUMERIC and DECIMAL values.

NUMERIC is semantically equivalent to DECIMAL.

Note
If you create a column or variable of a NUMERIC data type with a precision or scale that exceeds the precision
and scale settings for the database, values are truncated to the database settings. So, if you notice truncated
values in a column or variable defined as NUMERIC, check that precision and scale do not exceed the database
option settings.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 147
Standards

ANSI/ISO SQL Standard

Compatible with ANSI/ISO SQL Standard if the scale option is set to zero.

Related Information

Numeric functions [page 212]


Aggregate functions [page 202]
Numeric set conversions [page 198]
FLOAT data type [page 144]
REAL data type [page 148]
DOUBLE data type [page 143]
DECIMAL data type [page 142]

1.2.2.8 REAL data type

The REAL data type stores single-precision floating-point numbers stored in 4 bytes.

Syntax

REAL

Remarks

The REAL data type is an approximate numeric data type and subject to rounding errors after arithmetic
operations. The approximate nature of REAL values means that queries using equalities should generally be
avoided when comparing REAL values.

REAL values require 4 bytes of storage.

The range of values is -3.402823e+38 to 3.402823e+38, with numbers close to zero as small as 1.175494351e-38.
Values held as REAL are accurate to 7 significant digits, but may be subject to rounding error beyond the sixth
digit.

Standards

ANSI/ISO SQL Standard

SQL Anywhere - SQL Reference


148 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Core Feature.

Related Information

Numeric functions [page 212]


Aggregate functions [page 202]
DOUBLE data type [page 143]
FLOAT data type [page 144]
DECIMAL data type [page 142]
NUMERIC data type [page 147]

1.2.2.9 SMALLINT data type

The SMALLINT data type stores integers that require 2 bytes of storage.

Syntax

[ UNSIGNED ] SMALLINT

Remarks

The SMALLINT data type is an exact numeric data type; its accuracy is preserved after arithmetic operations. It
requires 2 bytes of storage.

The range for SMALLINT values is -215 to 215 - 1, or -32768 to 32767.

The range for UNSIGNED SMALLINT values is 0 to 216 - 1, or 0 to 65535.

When converting a string to a SMALLINT, leading and trailing spaces are removed. If the leading character is +, it
is ignored. If the leading character is -, the remaining digits are interpreted as a negative number. Leading 0
characters are skipped, and the remaining characters are converted to an integer value. An error is returned if the
value is out of the valid range for the destination data type, if the string contains illegal characters, or if the string
cannot be decoded as an integer value.

Standards

ANSI/ISO SQL Standard

Compatible with the standard. However, the UNSIGNED keyword is not in the standard.
MySQL

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 149
The UNSIGNED keyword may follow SMALLINT.

Related Information

Numeric functions [page 212]


Aggregate functions [page 202]
BIGINT data type [page 140]
BIT data type [page 141]
INTEGER data type [page 146]
TINYINT data type [page 150]

1.2.2.10 TINYINT data type

The TINYINT data type stores unsigned integers requiring 1 byte of storage.

Syntax

TINYINT

Remarks

The TINYINT data type is an exact numeric data type; its accuracy is preserved after arithmetic operations.

The range for TINYINT values is 0 to 28 - 1, or 0 to 255.

When converting a string to a TINYINT, leading and trailing spaces are removed. If the leading character is +, it is
ignored. If the leading character is -, the remaining digits are interpreted as a negative number. Leading 0
characters are skipped, and the remaining characters are converted to an integer value. An error is returned if the
value is out of the valid range for the destination data type, if the string contains illegal characters, or if the string
cannot be decoded as an integer value.

In Embedded SQL, TINYINT columns should not be fetched into variables defined as CHAR or UNSIGNED CHAR,
since the result is an attempt to convert the value of the column to a string and then assign the first byte to the
variable in the program. Instead, TINYINT columns should be fetched into 2-byte or 4-byte integer columns. To
send a TINYINT value to a database from an application written in C, the type of the C variable should be INTEGER.

UltraLite: In Embedded SQL, TINYINT columns should not be fetched into variables defined as CHAR, since the
result is an attempt to convert the value of the column to a string and then assign the first byte to the variable in
the program. Instead, TINYINT columns should be fetched into 2-byte or 4-byte integer columns. To send a
TINYINT value to a database from an application written in C, the type of the C variable should be INTEGER.

SQL Anywhere - SQL Reference


150 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Standards

ANSI/ISO SQL Standard

Not in the standard.


MySQL

The UNSIGNED keyword may precede or follow TINYINT, but the UNSIGNED modifier has no effect as the
type is always unsigned.

Related Information

Numeric functions [page 212]


Aggregate functions [page 202]
BIGINT data type [page 140]
BIT data type [page 141]
INTEGER data type [page 146]
SMALLINT data type [page 149]

1.2.3 Money data types

Money data types are used for storing monetary data.

In this section:

MONEY data type [page 151]


The MONEY data type stores monetary data.

SMALLMONEY data type [page 152]


The SMALLMONEY data type stores monetary data that is less than one million currency units.

1.2.3.1 MONEY data type

The MONEY data type stores monetary data.

Syntax

MONEY

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 151
Remarks

MONEY is a domain, implemented as NUMERIC(19,4).

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

Numeric functions [page 212]


Aggregate functions [page 202]
SMALLMONEY data type [page 152]

1.2.3.2 SMALLMONEY data type

The SMALLMONEY data type stores monetary data that is less than one million currency units.

Syntax

SMALLMONEY

Remarks

SMALLMONEY is a domain, implemented as NUMERIC(10,4).

Standards

ANSI/ISO SQL Standard

Not in the standard.

SQL Anywhere - SQL Reference


152 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Related Information

Numeric functions [page 212]


Aggregate functions [page 202]
MONEY data type [page 151]

1.2.4 Bit array data types

A bit array is similar to a character string, except that the individual pieces are bit data (0s (zeros) and 1s (ones))
instead of characters. Typically, bit arrays are used to hold a string of Boolean values.

The bit array data types supported include VARBIT and LONG VARBIT.

In this section:

LONG VARBIT data type [page 153]


The LONG VARBIT data type stores arbitrary length bit arrays.

VARBIT data type [page 154]


The VARBIT data type is used for storing bit arrays that are under 32767 bits in length.

1.2.4.1 LONG VARBIT data type

The LONG VARBIT data type stores arbitrary length bit arrays.

Syntax

LONG VARBIT

Remarks

Used to store arbitrary length array of bits (1s and 0s), or bit arrays longer than 32767 bits.

LONG VARBIT can also be specified as LONG BIT VARYING. Regardless of which syntax is used, the data type is
described as LONG VARBIT.

Standards

ANSI/ISO SQL Standard

Not in the standard.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 153
Related Information

Bit array conversions [page 196]


Bit array functions [page 204]
Aggregate functions [page 202]
BIT data type [page 141]
VARBIT data type [page 154]

1.2.4.2 VARBIT data type

The VARBIT data type is used for storing bit arrays that are under 32767 bits in length.

Syntax

VARBIT [ (max-length ) ]

Parameters

max-length

The maximum length of the bit array, in bits. The length must be in the range 1 to 32767. If the length is not
specified, then it is 1.

Remarks

VARBIT can also be specified as BIT VARYING. Regardless of which syntax is used, the data type is described as
VARBIT.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

Bit array conversions [page 196]

SQL Anywhere - SQL Reference


154 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Bit array functions [page 204]
Aggregate functions [page 202]
BIT data type [page 141]
LONG VARBIT data type [page 153]
Bitwise operators [page 31]

1.2.5 Date and time data types

Date values can be output in full century format, and the internal storage of dates always explicitly includes the
century portion of a year value.

Correct values are always returned for any legal arithmetic and logical operations on dates, regardless of whether
the calculated values span different centuries.

In this section:

How date and time of day are stored [page 156]


Date and time of day are stored in the database one of many data types.

Ways to send dates and times to the database [page 156]


The date and time of day can be sent to the database as a string using any interface. It can also be sent
using ODBC or OLE DB, as a binary value (using an ODBC TIMESTAMP_STRUCT structure, for example),
or using Embedded SQL, as a SQLDATETIME structure

Retrieval of dates and times from the database [page 162]


Dates and times can be retrieved from the database as a string using any interface, as a string. They can
also be retrieved using ODBC or OLE DB, as a binary value (using an ODBC TIMESTAMP_STRUCT
structure for example), or using Embedded SQL, as a SQLDATETIME structure

DATE data type [page 163]


The DATE data type stores calendar dates, such as a year, month, and day.

DATETIME data type [page 164]


DATETIME stores date and time of day information.

DATETIMEOFFSET data type [page 165]


The DATETIMEOFFSET data type is an alias for TIMESTAMP WITH TIME ZONE, used to store date, time of
day, and time zone information.

SMALLDATETIME data type [page 167]


SMALLDATETIME is a domain, implemented as TIMESTAMP, used to store date and time of day
information. SMALLDATETIME is a Transact-SQL type.

TIME data type [page 169]


The TIME data type stores the time of day, containing the hour, minute, second, and fraction of a second.

TIMESTAMP data type [page 170]


The TIMESTAMP data type stores a point in time containing the year, month, day, hour, minute, second,
and fraction of a second stored to six decimal places.

TIMESTAMP WITH TIME ZONE data type [page 172]


The TIMESTAMP WITH TIME ZONE data type stores a point in time with a time zone offset.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 155
1.2.5.1 How date and time of day are stored
Date and time of day are stored in the database one of many data types.

Data type Contains Stored in Range of possible values

DATE Calendar date (year, month, 4 bytes Dates from 0001-01-01 to


day) 9999-12-31.

TIME Time of day (hour, minute, 8 bytes Times from


second, and fraction of a sec­ 00:00:00.000000 to
ond accurate to 6 decimal 24:00:00.000000.
places)

TIMESTAMP Calendar date and time of day 8 bytes Dates from 0001-01-01 to
(year, month, day, hour, mi­ 9999-12-31 (precision of the
nute, second, and fraction of hours and minutes portion of
a second accurate to 6 deci­ a TIMESTAMP is dropped be­
mal places) fore 1600-02-28 23:59:59
and after 7911-01-01
00:00:00).

TIMESTAMP WITH TIME Calendar date, time of day, 10 bytes Dates from 0001-01-01 to
ZONE and time zone offset (year, 9999-12-31 (precision of the
month, day, hour, minute, hours and minutes portion of
second, fraction of a second a TIMESTAMP WITH TIME
accurate to 6 decimal places, ZONE is dropped before
and time zone offset in hours 1600-02-28 23:59:59 and af­
and minutes) ter 7911-01-01 00:00:00).
Zone offset from -14:59 to
+14:59.

1.2.5.2 Ways to send dates and times to the database


The date and time of day can be sent to the database as a string using any interface. It can also be sent using
ODBC or OLE DB, as a binary value (using an ODBC TIMESTAMP_STRUCT structure, for example), or using
Embedded SQL, as a SQLDATETIME structure

The date and time of day with a time zone offset can be sent to the database as a string only.

In this section:

Date formats [page 157]


When a date is sent to the database as a string (for the DATE data type) or as part of a string (for the
TIMESTAMP or TIMESTAMP WITH TIME ZONE data types), the string can be specified in several different
ways including that described by the ISO 8601 international standard.

Time formats [page 159]


The time of day can be specified in the ISO 8601 format, using the 24-hour timekeeping system.

Date with time formats [page 160]


ISO 8601 permits the date and time of day to be combined using a space character or the letter T.

Time zone formats [page 161]


ISO 8601 also permits the addition of a time zone offset to a date and time of day string.

SQL Anywhere - SQL Reference


156 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Related Information

Comparisons of dates and times [page 191]


DATE data type [page 163]
TIME data type [page 169]
TIMESTAMP data type [page 170]
TIMESTAMP WITH TIME ZONE data type [page 172]

1.2.5.2.1 Date formats

When a date is sent to the database as a string (for the DATE data type) or as part of a string (for the TIMESTAMP
or TIMESTAMP WITH TIME ZONE data types), the string can be specified in several different ways including that
described by the ISO 8601 international standard.

A date can be specified in one of the following ISO 8601 formats.

Calendar date

The calendar date format is YYYY-MM-DD where YYYY is the year in the Gregorian calendar, MM is the month
of the year between 01 (January) and 12 (December), and DD is the day of the month between 01 and 31. For
example, '2010-04-01' represents the first day of April in 2010. ISO 8601 does not require the separator
character. Therefore, '20100401' also represents the first day of April in 2010.

ISO calendar date Format Example

Basic YYYYMMDD 20100401

Extended YYYY-MM-DD 2010-04-01

Week date

Another ISO date format is the week date. The format is YYYY-Www-D where YYYY is the year in the
Gregorian calendar, W is the letter W, ww is the week of the year between 01 (the first week) and 52 or 53 (the
last week), and D is the day in the week between 1 (Monday) and 7 (Sunday). For example, '2010-W13-4'
represents the fourth day of the thirteenth week of 2010 (April 1 2010). ISO 8601 does not require the
separator character. Therefore, '2010W134' also represents the fourth day of the thirteenth week of 2010. For
reduced accuracy, one digit can be omitted from the representation ('2010W13' represents March 29 2010).

ISO week date Format Example

Basic YYYYWwwD 2010W134

Extended YYYY-Www-D 2010-W13-4

Ordinal date

The last ISO date format is the ordinal date. The format is YYYY-DDD where YYYY is the year in the Gregorian
calendar and DDD is the ordinal number of a calendar day within the calendar year. For example, '2010-091'
represents the first day of April in 2010. ISO 8601 does not require the separator character. For example,
'2010091' also represents April 1 2010. The maximum ordinal date is 366 for those years with leap years. For
example, '2008366' represents the last day of the year in 2008 (December 31 2008).

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 157
ISO ordinal date Format Example

Basic YYYYDDD 2010091

Extended YYYY-DDD 2010-091

Other date formats are supported. SQL Anywhere is very flexible in its interpretation of strings containing dates.
Whenever there is any ambiguity, the interpretation of the date value is guided by the date_order and
nearest_century database option settings. For example, depending on the date_order setting, '02/05/2002' can
be interpreted by the database server as the 2nd of May (DMY), or the 5th of February (MDY), or an illegal value
(YMD).

The nearest_century setting determines whether a two-digit year value is interpreted as a year in the twentieth or
twenty-first century. For example, in the string '02/05/10', the date_order setting would determine whether 02 or
10 is interpreted as the year and the nearest_century setting would determine whether 02 represented 1902 or
2002, or whether 10 represented 1910 or 2010. The value of the nearest_century option affects the interpretation
of 2-digit years: 2000 is added to values less than nearest_century and 1900 is added to all other values. The
default value of this option is 50. So, by default, the year 50 is interpreted as 1950 and the year 49 is interpreted
as 2049.

The following table shows how the first day of April in 2010 could be specified using the indicated date_order
setting and a nearest_century setting of 50.

date_order Format Example

YMD YYYY/MM/DD 2010/04/01

YMD YY/MM/DD 10/04/01

MDY MM/DD/YYYY 04/01/2010

MDY MM/DD/YY 04/01/10

DMY DD/MM/YYYY 01/04/2010

DMY DD/MM/YY 01/04/10

Since ISO 8601 formats are not ambiguous and are not affected by the user's setting of date_order and
nearest_century, their use is recommended.

Dates can also be specified using month names. Examples are '2010 April 01', 'April 1, 2010', and '1 April 2010'.
When the year is ambiguously specified, the date_order option is used to factor the year and day of month parts.
Therefore, '01 April 10' is interpreted as April 10 2001 when the date_order is 'YMD' or as April 1 2010 when the
date_order is 'DMY'.

The year in a date can range from 0001 to 9999. The minimum date is 0001-01-01.

If a string contains only a partial date specification, default values are used to fill out the date. The following
defaults are used:

year

The current year is used when no year is specified (for example, 'April 1').
month

The current month is used when no year and month are specified (for example, '23:59:59') or 01 if a year is
specified (for example, '2010').
day

SQL Anywhere - SQL Reference


158 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
The current day is used when no year and month are specified (for example, '23:59:59') or 01 if a month is
specified (for example, 'April').

In the following example, the date value is constructed from the current date.

SELECT CAST('23:59:59' AS TIMESTAMP);

Related Information

Comparisons of dates and times [page 191]


DATE data type [page 163]
TIME data type [page 169]
TIMESTAMP data type [page 170]
TIMESTAMP WITH TIME ZONE data type [page 172]

1.2.5.2.2 Time formats

The time of day can be specified in the ISO 8601 format, using the 24-hour timekeeping system.

It is hh:mm:ss, where hh is the number of complete hours that have passed since midnight, mm is the number of
complete minutes since the start of the hour, and ss is the number of complete seconds since the start of the
minute. For example, '23:59:59' represents the time one second before midnight.

The ISO 8601 standard allows for the omission of seconds and minutes. For example, '23:59' represents the time
sixty seconds before midnight.

The ISO 8601 standard also allows you to include a decimal fraction to the seconds unit. Fractional seconds are
specified using a comma (,) or a period (.). The fraction is stored to a maximum of six decimal places. For
example, '23:59:59,500000' and '23:59:59.500000' both represent the time one-half second before midnight.
Fractional minutes or hours are not supported.

ISO 8601 does not require the colon separator character when the time of day is included with a date
specification. For example, '235959' represents the time one second before midnight.

The maximum time of day is '24:00:00'. It represents midnight. When combined with a date, it represents
midnight, or 00:00:00 of the next day. For example, '2010-04-01 24:00:00' is equivalent to '2010-04-02
00:00:00'.

ISO time Format Example

Basic (with date) hhmmss.ssssss 20100401 235959.500000

Basic (with date) hhmmss,ssssss 20100401 235959,500000

Extended hh:mm:ss.ssssss 23:59:59.500000

Extended hh:mm:ss,ssssss 23:59:59,500000

The non-ISO AM and PM designators are also supported. For example, '11:59:59 PM' is equivalent to '23:59:59'.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 159
AM/PM Format Example

AM hh:mm:ss.ssssss AM 11:59:59.500000 AM

AM hh:mm:ss,ssssss AM 11:59:59,500000 AM

PM hh:mm:ss.ssssss PM 11:59:59.500000 PM

PM hh:mm:ss,ssssss PM 11:59:59,500000 PM

Related Information

Comparisons of dates and times [page 191]


DATE data type [page 163]
TIME data type [page 169]
TIMESTAMP data type [page 170]
TIMESTAMP WITH TIME ZONE data type [page 172]

1.2.5.2.3 Date with time formats

ISO 8601 permits the date and time of day to be combined using a space character or the letter T.

For example, '2010-04-01 23:59:59' and '2010-04-01T23:59:59' both represent the time one second before
midnight on the first day of April in 2010. The hyphen and colon separator characters can be omitted. For
example, '20100401T235959' also represents the same date and time. As an extension to this format, the
omission of the date and time separator are also supported. For example, '20100401235959' also represents the
same date and time.

Mixing basic and extended date and time formats is supported. For example, '20100401T23:59:59' combines
both the basic and extended formats.

Related Information

Comparisons of dates and times [page 191]


DATE data type [page 163]
TIME data type [page 169]
TIMESTAMP data type [page 170]
TIMESTAMP WITH TIME ZONE data type [page 172]

SQL Anywhere - SQL Reference


160 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.2.5.2.4 Time zone formats

ISO 8601 also permits the addition of a time zone offset to a date and time of day string.

The format is one of:

(Zulu) The date and time of day are in Coordinated Universal Time (UTC). For example, '2010-04-01
23:00:00Z' represents 11:00 PM Coordinated Universal Time on the first day of April in 2010.
+hh:mm

The specified date and time of day are the indicated number of hours and minutes ahead of UTC. For
example, '2010-04-01 23:00:00+04:00' represents 11:00 PM on the first day of April in 2010 in a time zone 4
hours east of UTC.
-hh:mm

The specified date and time of day are the indicated number of hours and minutes behind UTC. For example,
'2010-04-01 23:00:00-05:00' represents 11:00 PM on the first day of April in 2010 in a time zone 5 hours west
of UTC.

If the minutes are 0, it is not necessary to specify them in the time zone offset. Also, a space can precede the time
zone offset. For example, '2010-04-01 23:00:00 -03:30' represents 11:00 PM on the first day of April in 2010 in a
time zone three and a half hours west of UTC.

ISO time zone Format Example

Basic Z 20100401 235959Z

Basic +hhmm 20100401 235959+0400

Basic +hh 20100401 235959+04

Basic -hhmm 20100401 235959-0500

Basic -hh 20100401 235959-05

Basic using T, fraction 20100401T235959.50-0330

Extended Z 2010-04-01 23:59:59Z

Extended +hh:mm 2010-04-01 23:59:59+04:00

Extended -hh:mm 2010-04-01 23:59:59-05:00

Extended using T, fraction 2010-04-01T23:59:59.50-03:30

Mixing basic and extended date, time, and time zone formats is supported. For example, '20100401T23:59:59-05'
combines both basic and extended formats.

Related Information

Comparisons of dates and times [page 191]


DATE data type [page 163]
TIME data type [page 169]
TIMESTAMP data type [page 170]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 161
TIMESTAMP WITH TIME ZONE data type [page 172]

1.2.5.3 Retrieval of dates and times from the database

Dates and times can be retrieved from the database as a string using any interface, as a string. They can also be
retrieved using ODBC or OLE DB, as a binary value (using an ODBC TIMESTAMP_STRUCT structure for example),
or using Embedded SQL, as a SQLDATETIME structure

Date and time of day with a time zone offset can be retrieved from the database as a string only.

When a date or time, with or without a time zone offset, is retrieved as a string, it is retrieved in the format
specified by the database options date_format, time_format, timestamp_format, and
timestamp_with_time_zone_format.

The following arithmetic operators are allowed on dates:

timestamp + integer

Add the specified number of days to a date or timestamp.


timestamp - integer

Subtract the specified number of days from a date or timestamp.


date - date

Compute the number of days between two dates or timestamps.


date + time

Create a timestamp combining the given date and time.

Leap years

The database server uses a globally accepted algorithm for determining which years are leap years. Using this
algorithm, a year is considered a leap year if it is divisible by four, unless the year is a century date (such as the
year 1900), in which case it is a leap year only if it is divisible by 400.

All leap years are handled correctly. For example, the following SQL statement results in a return value of
"Tuesday":

SELECT DAYNAME('2000-02-29');

The database server accepts February 29, 2000 (a leap year)as a date, and using this date determines the day of
the week.

However, the following statement is rejected by the database server:

SELECT DAYNAME('2001-02-29');

This statement results in an error (cannot convert '2001-02-29' to a date) because February 29th does not exist
in the year 2001.

SQL Anywhere - SQL Reference


162 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Related Information

Date and time functions [page 206]


SET OPTION statement [page 1314]

1.2.5.4 DATE data type

The DATE data type stores calendar dates, such as a year, month, and day.

Syntax

DATE

Remarks

A DATE value requires 4 bytes of storage.

The format in which DATE values are retrieved as strings by applications is controlled by the date_format option
setting. For example, a DATE value representing the 19th of July, 2010 can be returned to an application as
2010/07/19, or as Jul 19, 2010 depending on the date_format option setting.

UltraLite: The format in which DATE values are retrieved as strings by applications is controlled by the
date_format creation parameter. For example, a DATE value representing the 19th of July, 2010 can be returned
to an application as 2010/07/19, or as Jul 19, 2010 depending on the date_format creation parameter.

Standards

ANSI/ISO SQL Standard

A feature in the standard.


Transact-SQL

Supported by Adaptive Server Enterprise.

Related Information

Date and time functions [page 206]


Date formats [page 157]
CURRENT TIME special value [page 91]
CURRENT TIMESTAMP special value [page 93]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 163
DATE function [Date and time] [page 304]
DATETIME data type [page 164]
DATETIME function [Date and time] [page 313]
DATETIMEOFFSET data type [page 165]
ISDATE function [Data type conversion] [page 409]
NOW function [Date and time] [page 460]
SMALLDATETIME data type [page 167]
TIME data type [page 169]
TIMESTAMP data type [page 170]
TIMESTAMP special value [page 108]
TIMESTAMP WITH TIME ZONE data type [page 172]
UTC TIMESTAMP special value [page 110]

1.2.5.5 DATETIME data type

DATETIME stores date and time of day information.

Syntax

DATETIME

Remarks

DATETIME is a Transact-SQL type.

UltraLite: DATETIME is a domain, implemented as TIMESTAMP.

The format in which DATETIME values are retrieved as strings by applications is controlled by the
timestamp_format option setting. For example, the DATETIME value 2010/04/01T23:59:59.999999 can be
returned to an application as 2010/04/01 23:59:59, or as April 1, 2010 23:59:59.999999 depending on the
timestamp_format option setting.

A DATETIME value requires 8 bytes of storage.

Although the range of possible dates for the DATETIME data type is the same as the DATE type (covering years
0001 to 9999), the useful range of the DATETIME date type is from 1600-02-28 23:59:59 to 7911-01-01 00:00:00.
Before and after this range, the hours and minutes portion of the DATETIME value is not retained.

Note
When the precision of the DATETIME value is reduced, built-in functions that pertain to minutes or seconds will
produce meaningless results.

SQL Anywhere - SQL Reference


164 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
When a DATETIME value is converted to a DATETIMEOFFSET, the connection's time_zone_adjustment setting is
used for the time zone offset in the result. In other words, the value is considered to be local to the connection.
When a DATETIMEOFFSET value is converted to DATETIME, the offset is discarded.

Standards

ANSI/ISO SQL Standard

Not in the standard.


Transact-SQL

DATETIME, rather than TIMESTAMP, is used by Adaptive Server Enterprise. The DATETIME type in Adaptive
Server Enterprise supports dates between January 1, 1753 and December 31, 9999 and supports less
precision with the time portion of the value. In SQL Anywhere, DATETIME is implemented as a TIMESTAMP
without these restrictions. You should be aware of these differences when migrating data between SQL
Anywhere and Adaptive Server Enterprise.

Related Information

Date and time functions [page 206]


Ways to send dates and times to the database [page 156]
CURRENT TIME special value [page 91]
CURRENT TIMESTAMP special value [page 93]
CURRENT UTC TIMESTAMP special value [page 96]
DATE function [Date and time] [page 304]
DATE data type [page 163]
DATETIME function [Date and time] [page 313]
DATETIMEOFFSET data type [page 165]
SMALLDATETIME data type [page 167]
TIME data type [page 169]
TIMESTAMP data type [page 170]
TIMESTAMP WITH TIME ZONE data type [page 172]
UTC TIMESTAMP special value [page 110]

1.2.5.6 DATETIMEOFFSET data type


The DATETIMEOFFSET data type is an alias for TIMESTAMP WITH TIME ZONE, used to store date, time of day,
and time zone information.

Syntax

DATETIMEOFFSET

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 165
Remarks

The DATETIMEOFFSET value contains the year, month, day, hour, minute, second, fraction of a second, and
number of minutes before or after Coordinated Universal Time (UTC). The fraction is stored to 6 decimal places.

The format in which DATETIMEOFFSET values are retrieved as strings by applications is controlled by the
timestamp_with_time_zone_format option setting. For example, the DATETIMEOFFSET value
2010/04/01T23:59:59.999999-6:00 can be returned to an application as 2010/04/01 23:59:59 -06:00, or as
April 1, 2010 23:59:59.999999 -06:00 depending on the timestamp_with_time_zone_format option setting.

A DATETIMEOFFSET value requires 10 bytes of storage.

Although the range of possible dates for the DATETIMEOFFSET data type is the same as the DATE type (covering
years 0001 to 9999), the useful range of DATETIMEOFFSET date types is from 1600-02-28 23:59:59 to
7911-01-01 00:00:00. Before and after this range, the hours and minutes portion of the DATETIMEOFFSET value
is not retained.

Do not use DATETIMEOFFSET for computed columns or in materialized views because the value of the governing
time_zone_adjustment option varies between connections based on their location and the time of year.

Two DATETIMEOFFSET values are considered identical when they represent the same instant in UTC, regardless
of the TIME ZONE offset applied. For example, the following statement returns Yes because the results are
considered identical:

IF CAST('2009-07-15 08:00:00 -08:00' AS DATETIMEOFFSET) =


CAST('2009-07-15 11:00:00 -05:00' AS DATETIMEOFFSET) THEN
SELECT 'Yes'
ELSE
SELECT 'No'
END IF;

If you omit the time zone offset from a DATETIMEOFFSET value, it defaults to the current UTC offset of the client
regardless of whether the timestamp represents a date and time in standard time or daylight time. For example, if
the client is located in the Eastern Standard time zone and executes the following statement while daylight time is
in effect, then a timestamp with a time zone appropriate for the Atlantic Standard time zone (-4 hours from UTC)
will be returned.

SELECT CAST('2009/01/30 12:34:55' AS DATETIMEOFFSET);

The comparison of DATETIMEOFFSET values with timestamps without time zones is not recommended because
the default time zone offset of the client varies with the geographic location of the client and with the time of the
year.

Execute the following statement to determine the current time zone offset in minutes for a client:

SELECT CONNECTION_PROPERTY( 'TimeZoneAdjustment' );

Note
The TimeZoneAdjustment connection property is not supported in UltraLite databases.

SQL Anywhere - SQL Reference


166 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Standards

ANSI/ISO SQL Standard

The specific use of DATETIMEOFFSET is not in the standard. To be compatible with the ANSI/ISO SQL
Standard, use TIMESTAMP WITH TIME ZONE. The TIMESTAMP WITH TIME ZONE type is optional ANSI/ISO
SQL Language Feature F411.

Related Information

Date and time functions [page 206]


Ways to send dates and times to the database [page 156]
CURRENT TIME special value [page 91]
CURRENT TIMESTAMP special value [page 93]
CURRENT UTC TIMESTAMP special value [page 96]
DATE data type [page 163]
DATETIME data type [page 164]
DATE function [Date and time] [page 304]
DATETIME function [Date and time] [page 313]
Expressions in SQL statements [page 32]
GETDATE function [Date and time] [page 377]
ISDATE function [Data type conversion] [page 409]
NOW function [Date and time] [page 460]
SMALLDATETIME data type [page 167]
TIME data type [page 169]
TIMESTAMP special value [page 108]
TIMESTAMP data type [page 170]
TIMESTAMP WITH TIME ZONE data type [page 172]
UTC TIMESTAMP special value [page 110]

1.2.5.7 SMALLDATETIME data type

SMALLDATETIME is a domain, implemented as TIMESTAMP, used to store date and time of day information.
SMALLDATETIME is a Transact-SQL type.

Syntax

SMALLDATETIME

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 167
Remarks

None

Standards

ANSI/ISO SQL Standard

Not in the standard.


Transact-SQL

SMALLDATETIME is supported by Adaptive Server Enterprise. In Adaptive Server Enterprise, the


SMALLDATETIME type supports dates between January 1, 1900 and June 6, 2079 and supports less
precision with the time portion of the value. In SQL Anywhere, SMALLDATETIME is implemented as a
TIMESTAMP without these restrictions. You should be aware of these differences when migrating data
between SQL Anywhere and Adaptive Server Enterprise.

Related Information

Ways to send dates and times to the database [page 156]


Date and time functions [page 206]
CURRENT TIME special value [page 91]
CURRENT TIMESTAMP special value [page 93]
CURRENT UTC TIMESTAMP special value [page 96]
DATE data type [page 163]
DATETIME data type [page 164]
DATE function [Date and time] [page 304]
DATETIME function [Date and time] [page 313]
Expressions in SQL statements [page 32]
GETDATE function [Date and time] [page 377]
ISDATE function [Data type conversion] [page 409]
NOW function [Date and time] [page 460]
TIME data type [page 169]
TIMESTAMP special value [page 108]
TIMESTAMP data type [page 170]
TIMESTAMP WITH TIME ZONE data type [page 172]
UTC TIMESTAMP special value [page 110]

SQL Anywhere - SQL Reference


168 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.2.5.8 TIME data type

The TIME data type stores the time of day, containing the hour, minute, second, and fraction of a second.

Syntax

TIME

Remarks

A TIME value requires 8 bytes of storage.

When using ODBC, a TIME value sent or retrieved as a binary value (using an ODBC TIME_STRUCT structure) is
restricted to an accuracy of hours, minutes, and seconds. Fractional seconds are not part of the structure. For this
reason, TIME values should be sent or retrieved as strings if increased accuracy is desired. The format in which
TIME values are retrieved as strings by applications is controlled by the time_format option setting. For example,
the TIME value 23:59:59.999999 can be returned to an application as 23:59:59, 23:59:59.999, or
23:59:59.999999 depending on the time_format option setting.

UltraLite: The format in which TIME values are retrieved as strings by applications is controlled by the
time_format creation parameter. For example, the TIME value 23:59:59.999999 can be returned to an application
as 23:59:59, 23:59:59.999, or 23:59:59.999999 depending on the time_format creation parameter.

Standards

ANSI/ISO SQL Standard

A feature in the standard.


Transact-SQL

The TIME data type is supported by Adaptive Server Enterprise. However, Adaptive Server Enterprise
supports millisecond resolution (three digits) rather than microsecond resolution (six digits). You should be
aware of these differences when migrating data between SQL Anywhere and Adaptive Server Enterprise. To
migrate TIME values, use the Adaptive Server Enterprise BIGTIME data type.

Related Information

Time formats [page 159]


Date and time functions [page 206]
CURRENT TIME special value [page 91]
CURRENT TIMESTAMP special value [page 93]
CURRENT UTC TIMESTAMP special value [page 96]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 169
DATE data type [page 163]
DATETIME data type [page 164]
DATE function [Date and time] [page 304]
DATETIME function [Date and time] [page 313]
Expressions in SQL statements [page 32]
GETDATE function [Date and time] [page 377]
ISDATE function [Data type conversion] [page 409]
NOW function [Date and time] [page 460]
SMALLDATETIME data type [page 167]
TIMESTAMP special value [page 108]
TIMESTAMP data type [page 170]
TIMESTAMP WITH TIME ZONE data type [page 172]
UTC TIMESTAMP special value [page 110]

1.2.5.9 TIMESTAMP data type


The TIMESTAMP data type stores a point in time containing the year, month, day, hour, minute, second, and
fraction of a second stored to six decimal places.

Syntax

TIMESTAMP

Remarks

A TIMESTAMP value requires 8 bytes of storage.

The format in which TIMESTAMP values are retrieved as strings by applications is controlled by the
timestamp_format option setting. For example, the TIMESTAMP value 2010/04/01T23:59:59.999999 can be
returned to an application as 2010/04/01 23:59:59 or as April 1, 2010 23:59:59.999999, depending on the
timestamp_format option setting.

UltraLite: The format in which TIMESTAMP values are retrieved as strings by applications is controlled by the
timestamp_format creation parameter. For example, the TIMESTAMP value 2010/04/01T23:59:59.999999 can
be returned to an application as 2010/04/01 23:59:59 or as April 1, 2010 23:59:59.999999, depending on the
timestamp_format creation parameter.

Although the range of possible dates for the TIMESTAMP data type is the same as the DATE type (covering years
0001 to 9999), the useful range of TIMESTAMP date types is from 1600-02-28 23:59:59 to 7911-01-01 00:00:00.
Before and after this range, the hours and minutes portion of the TIMESTAMP value is not retained.

Note
When the precision of the TIMESTAMP value is reduced, built-in functions that pertain to minutes or seconds
produce meaningless results.

SQL Anywhere - SQL Reference


170 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
When a TIMESTAMP value is converted to TIMESTAMP WITH TIME ZONE, the connection's
time_zone_adjustment setting is used for the time zone offset in the result. In other words, the value is considered
to be local to the connection. When a TIMESTAMP WITH TIME ZONE value is converted to TIMESTAMP, the offset
is discarded.

UltraLite: When a TIMESTAMP value is converted to TIMESTAMP WITH TIME ZONE, the local time zone offset on
the system is used in the final result.

Standards

ANSI/ISO SQL Standard

Compatible with the standard.


Transact-SQL

Adaptive Server Enterprise uses the DATETIME type for TIMESTAMP values.

Related Information

Ways to send dates and times to the database [page 156]


Date and time functions [page 206]
CURRENT TIME special value [page 91]
CURRENT TIMESTAMP special value [page 93]
CURRENT UTC TIMESTAMP special value [page 96]
DATE data type [page 163]
DATETIME data type [page 164]
DATE function [Date and time] [page 304]
DATETIME function [Date and time] [page 313]
Expressions in SQL statements [page 32]
GETDATE function [Date and time] [page 377]
ISDATE function [Data type conversion] [page 409]
NOW function [Date and time] [page 460]
SMALLDATETIME data type [page 167]
TIME data type [page 169]
TIMESTAMP special value [page 108]
TIMESTAMP WITH TIME ZONE data type [page 172]
UTC TIMESTAMP special value [page 110]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 171
1.2.5.10 TIMESTAMP WITH TIME ZONE data type

The TIMESTAMP WITH TIME ZONE data type stores a point in time with a time zone offset.

Syntax

TIMESTAMP WITH TIME ZONE

Remarks

The TIMESTAMP WITH TIME ZONE value contains the year, month, day, hour, minute, second, fraction of a
second, and number of minutes before or after Coordinated Universal Time (UTC). The fraction is stored to six
decimal places.

Note
By default, the TIMESTAMP WITH TIME ZONE value is the current time zone of the database.

The format in which TIMESTAMP WITH TIME ZONE values are retrieved as strings by applications is controlled by
the timestamp_with_time_zone_format option setting . For example, the TIMESTAMP WITH TIME ZONE value
2010/04/01T23:59:59.999999-6:00 can be returned to an application as 2010/04/01 23:59:59 -06:00 or as
April 1, 2010 23:59:59.999999 -06:00, depending on the timestamp_with_time_zone_format option setting.

UltraLite: The format in which TIMESTAMP WITH TIME ZONE values are retrieved as strings by applications is
controlled by the timestamp_with_time_zone_format creation parameter. For example, the TIMESTAMP WITH
TIME ZONE value 2010/04/01T23:59:59.999999-6:00 can be returned to an application as 2010/04/01
23:59:59 -06:00 or as April 1, 2010 23:59:59.999999 -06:00, depending on the
timestamp_with_time_zone_format creation parameter.

A TIMESTAMP WITH TIME ZONE value requires 10 bytes of storage.

Although the range of possible dates for the TIMESTAMP WITH TIME ZONE data type is the same as the DATE
type (covering years 0001 to 9999), the useful range of TIMESTAMP WITH TIME ZONE date types is from
1600-02-28 23:59:59 to 7911-01-01 00:00:00. Before and after this range, the hours and minutes portion of the
TIMESTAMP WITH TIME ZONE value is not retained.

Do not use TIMESTAMP WITH TIME ZONE for computed columns or in materialized views because the value of
the governing time_zone_adjustment option varies between connections based on their location and the time of
year.

Two TIMESTAMP WITH TIME ZONE values are considered identical when they represent the same instant in UTC,
regardless of the TIME ZONE offset applied. For example, the following statement returns Yes because the results
are considered identical:

IF CAST('2009-07-15 08:00:00 -08:00' AS TIMESTAMP WITH TIME ZONE) =


CAST('2009-07-15 11:00:00 -05:00' AS TIMESTAMP WITH TIME ZONE) THEN
SELECT 'Yes'
ELSE
SELECT 'No'
END IF;

SQL Anywhere - SQL Reference


172 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
UltraLite:

SELECT IF CAST('2009-07-15 08:00:00 -08:00' AS TIMESTAMP WITH TIME ZONE) =


CAST('2009-07-15 11:00:00 -05:00' AS TIMESTAMP WITH TIME ZONE)
THEN 'Yes'
ELSE 'No'
END IF;

If you omit the time zone offset from a TIMESTAMP WITH TIME ZONE value, it defaults to the current UTC offset
of the client regardless of whether the timestamp represents a date and time in standard time or daylight time.
For example, if the client is located in the Eastern Standard time zone and executes the following statement while
daylight time is in effect, then a timestamp with a time zone appropriate for the Atlantic Standard time zone (-4
hours from UTC) is returned.

SELECT CAST('2009/01/30 12:34:55' AS TIMESTAMP WITH TIME ZONE)

Comparing TIMESTAMP WITH TIME ZONE with other data types

The comparison of TIMESTAMP WITH TIME ZONE values with timestamps without time zones is not
recommended because the default time zone offset of the client varies with the geographic location of the
client and with the time of the year.

Execute the following statement to determine the current time zone offset in minutes for a client:

SELECT CONNECTION_PROPERTY( 'TimeZoneAdjustment' );

Converting to or from TIMESTAMP WITH TIME ZONE

When a TIMESTAMP value is converted to TIMESTAMP WITH TIME ZONE, the connection's
time_zone_adjustment setting is used for the time zone offset in the result. In other words, the value is
considered to be local to the connection. When a TIMESTAMP WITH TIME ZONE value is converted to
TIMESTAMP, the offset is discarded. Conversions to or from types other than strings, date, or date-time types
is not supported.

UltraLite: When a TIMESTAMP value is converted to TIMESTAMP WITH TIME ZONE, the client's time zone is
used for the time zone offset in the result. In other words, the value is considered to be local to the
connection. When a TIMESTAMP WITH TIME ZONE value is converted to TIMESTAMP, the offset is discarded.
Conversions to or from types other than strings, date, or date-time types is not supported.

Standards

ANSI/ISO SQL Standard

TIMESTAMP WITH TIME ZONE is part of optional ANSI/ISO SQL Language Feature F411.

Related Information

Comparisons of dates and times [page 191]


Ways to send dates and times to the database [page 156]
Date and time functions [page 206]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 173
CURRENT TIME special value [page 91]
CURRENT TIMESTAMP special value [page 93]
CURRENT UTC TIMESTAMP special value [page 96]
DATE data type [page 163]
DATETIME data type [page 164]
DATE function [Date and time] [page 304]
DATETIME function [Date and time] [page 313]
DATETIMEOFFSET data type [page 165]
Expressions in SQL statements [page 32]
GETDATE function [Date and time] [page 377]
ISDATE function [Data type conversion] [page 409]
NOW function [Date and time] [page 460]
SMALLDATETIME data type [page 167]
TIME data type [page 169]
TIMESTAMP special value [page 108]
TIMESTAMP data type [page 170]
UTC TIMESTAMP special value [page 110]

1.2.6 Binary data types

Binary data types store binary data, including images and other types of information that are not interpreted by
the database.

In this section:

BINARY data type [page 175]


The BINARY data type stores binary data of a specified maximum length (in bytes).

IMAGE data type [page 176]


The IMAGE data type stores binary data of arbitrary length.

LONG BINARY data type [page 176]


The LONG BINARY data type stores binary data of arbitrary length.

UNIQUEIDENTIFIER data type [page 177]


The UNIQUEIDENTIFIER data type stores UUID (also known as GUID) values.

VARBINARY data type [page 178]


The VARBINARY data type stores binary data of a specified maximum length (in bytes).

SQL Anywhere - SQL Reference


174 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.2.6.1 BINARY data type

The BINARY data type stores binary data of a specified maximum length (in bytes).

Syntax

BINARY [ ( max-length ) ]

Parameters

max-length

The maximum length of the value, in bytes. If the length is not specified, then it is 1.

The length must be in the 1 to 32767 range.

Remarks

During comparisons, BINARY values are compared exactly byte for byte. This differs from the CHAR data type,
where values are compared using the collation sequence of the database.

If one binary string is a prefix of the other, the shorter string is considered to be less than the longer string.

Unlike CHAR values, BINARY values are not transformed during character set conversion.

BINARY is semantically equivalent to VARBINARY. It is a variable-length type. In other database management


systems, BINARY is a fixed-length type.

UltraLite: BINARY is a domain, implemented as VARBINARY.

Standards

ANSI/ISO SQL Standard

SQL Language Feature T021.

Related Information

String functions [page 214]


VARBINARY data type [page 178]
LONG BINARY data type [page 176]
Bitwise operators [page 31]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 175
1.2.6.2 IMAGE data type

The IMAGE data type stores binary data of arbitrary length.

Syntax

IMAGE

Remarks

IMAGE is a domain, implemented as LONG BINARY.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

String functions [page 214]


LONG BINARY data type [page 176]

1.2.6.3 LONG BINARY data type

The LONG BINARY data type stores binary data of arbitrary length.

Syntax

LONG BINARY

Remarks

The maximum size is 2 GB minus 1 byte (231 - 1).

You can cast strings to/from LONG BINARY data. LONG BINARY data cannot be concatenated.

SQL Anywhere - SQL Reference


176 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Conditions in SQL statements, such as in the WHERE clause, cannot operate on LONG BINARY columns. Only
INSERT, UPDATE, and DELETE operations are allowed on LONG BINARY columns. LONG BINARY columns can
also be included in the result set of a SELECT query.

UltraLite: Indexes cannot be created on a LONG BINARY type. A LONG BINARY type can only be used in the
LENGTH and CAST functions.

Standards

ANSI/ISO SQL Standard

The LONG BINARY data type comprises SQL Language Features T021, "BINARY and VARBINARY data types",
and T041, "Basic LOB data type support".

Related Information

BINARY data type [page 175]


VARBINARY data type [page 178]

1.2.6.4 UNIQUEIDENTIFIER data type

The UNIQUEIDENTIFIER data type stores UUID (also known as GUID) values.

Syntax

UNIQUEIDENTIFIER

Remarks

The UNIQUEIDENTIFIER data type is typically used for a primary key or other unique column to hold UUID
(Universally Unique Identifier) values that uniquely identify rows. The NEWID function generates UUID values in
such a way that a value produced on one computer does not match a UUID produced on another computer.
UNIQUEIDENTIFIER values generated using NEWID can therefore be used as keys in a synchronization
environment.

For example:

CREATE TABLE T1 (
pk UNIQUEIDENTIFIER PRIMARY KEY DEFAULT NEWID(),
c1 INT );

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 177
In UltraLite:

CREATE TABLE T1 (
pk UNIQUEIDENTIFIER PRIMARY KEY DEFAULT NEWID(),
c1 INT );

UUID values are also referred to as GUID (Globally Unique Identifier) values. UUID values contain hyphens so they
are compatible with other RDBMSs.

You can change this by setting the uuid_has_hyphens option to Off.

UltraLite: You can change this setting by using the UUIDTOSTR and STRTOUUID functions.

UNIQUEIDENTIFIER values are automatically converted between string and binary values as needed.

UNIQUEIDENTIFIER values are stored as BINARY(16) but are described to client applications as BINARY(36). This
description ensures that if the client fetches the value as a string, it has allocated enough space for the result.

For SQL Anywhere ODBC client applications, uniqueidentifier values appear as a SQL_GUID type.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

String functions [page 214]


NEWID function [Miscellaneous] [page 450]
UUIDTOSTR function [String] [page 587]
STRTOUUID function [String] [page 552]

1.2.6.5 VARBINARY data type

The VARBINARY data type stores binary data of a specified maximum length (in bytes).

Syntax

VARBINARY [ ( max-length ) ]

SQL Anywhere - SQL Reference


178 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Parameters

max-length

The maximum length of the value, in bytes. If the length is not specified, then it is 1.

The length must be in the 1 to 32767 range.

Remarks

During comparisons, VARBINARY values are compared exactly byte for byte. This behavior differs from the CHAR
data type, where values are compared using the collation sequence of the database.

VARBINARY values are not transformed during character set conversion.

VARBINARY can also be specified as BINARY VARYING. Regardless of which syntax is used, the data type is
described as VARBINARY. If one binary string is a prefix of the other, the shorter string is considered to be less
than the longer string.

UltraLite: If one binary string is a prefix of the other, the shorter string is compared to the other as though the
shorter string were padded with zeros. When evaluating expressions, the maximum length for a temporary
character value is 2048 bytes.

Standards

ANSI/ISO SQL Standard

SQL Language Feature T021, "BINARY and VARBINARY data types".

Related Information

String functions [page 214]


BINARY data type [page 175]
LONG BINARY data type [page 176]
Bitwise operators [page 31]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 179
1.2.7 ROW and ARRAY composite data types

Composite data types are values that are comprised of zero or more elements, where each element has a value of
a particular data type. Currently only ROW and ARRAY composite data types are supported.

Composite data types are not a specific data type, they are constructors containing the definition for how to
assemble one or more data types into a row. When you define a ROW or ARRAY type, you are defining the number
and data type of each element that make up a row (an array is a set of these rows).

ROWS and ARRAYS are a more efficient way to store lists because they define the structure and data type of their
values. They also simplify the creation of list elements, either directly, by using double square brackets; or as
result set, by using the UNNEST operator. Consider using the ARRAY data type if you are storing lists as delimited
strings in VARCHAR columns, and parsing them using sa_split_list. ARRAYS are helpful when storing different
objects that are all related. ROWS are helpful when storing multiple values related to one object.

Creating domains of ROW or ARRAY type

You can create domains of ROW or ARRAY type. For example, the following statement creates a domain called
MyRow, and defines its composite type as two integer values.

CREATE DOMAIN MyRow ROW( a INT, b INT );

Creating a ROW or ARRAY domain allows you to reference the row or array type, instead of defining it repeatedly
inside statements.

Declaring an ARRAY type

An ARRAY type is a homogeneous, ordered collection that can be passed in whole or in part as an argument to
SQL stored procedures or functions.

An ARRAY type can consist of up to 6.4 million elements. An ARRAY is initialized to a zero-length ARRAY of the
declared type, where each element is NULL.

An ARRAY constructor builds an ARRAY value so the array can be processed in a query or passed as an argument
to a SQL stored procedure or function.

The database server supports the following syntaxes for declaring variables of the ARRAY type:

DECLARE variable-name element-type-name ARRAY [ ( maximum-size ) ]

DECLARE variable-name ARRAY [ ( maximum-size ) ] OF element-type-name

If maximum-size is omitted, then the array can contain up to 6.4 million elements. Variables of the ARRAY type
are not initialized to NULL the way all other non-composite variables are. Instead, they are initialized to a zero-
length array.

SQL Anywhere - SQL Reference


180 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
ARRAY types cannot be stored as columns in a base or temporary table and are not supported in:

● the outermost SELECT list of a view definition


● a top-level SELECT block or query expression that is returned to the client
● a base table
● a temporary table
● an Embedded SQL FETCH statement

Note
If a procedure returns a column of type ROW or ARRAY in its result set, the procedure must have a RESULT
column, or an error is returned. If necessary, change the procedure to use Watcom SQL syntax.

The following example illustrates how to declare an array of 5 integers:

DECLARE NewArray INTEGER ARRAY( 5 );

The following example illustrates an alternative way of declaring an array of 5 integers that is compatible with the
Oracle syntax:

DECLARE NewArray ARRAY( 5 ) OF INTEGER;

The following example illustrates how to declare a two-dimensional array, where New2DArray contains 10
elements, each of which is a five-element array of integers:

DECLARE New2DArray INTEGER ARRAY( 5 ) ARRAY( 10 );

The following example illustrates an alternative way of declaring a two-dimensional array that is compatible with
the Oracle syntax, where New2DArray contains 10 elements, each of which is a five-element array of integers:

DECLARE New2DArray ARRAY( 10 ) OF ARRAY( 5 ) OF INTEGER;

Declaring a ROW type

A ROW type is described by a row type descriptor, which consists of the field descriptor of each field in the ROW
type. ROW types are restricted to 45000 fields, which is the same limit as the number of columns in a table.

Variables in the ROW type are initialized to a ROW of the declared type where each field is initialized as NULL.

A ROW supports the construction of structured types, consisting of a group of fields of potentially different types.
ROW types can be part of higher-order row types, which permits complex structures involving other row types
and arrays.

The following example illustrates how to declare a variable, student, that is defined as a structured type of four
different fields:

DECLARE student ROW( studentID INTEGER,


student_first_name VARCHAR( 40 ),
student_last_name VARCHAR( 50 ),
student address LONG VARCHAR );

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 181
The following example illustrates how to assign a ROW as a complete structure:

DECLARE employee ROW( empID INTEGER,


address ROW( street_address LONG VARCHAR,
city VARCHAR( 50 ),
province VARCHAR( 30 ),
country VARCHAR( 40 )
)
);
DECLARE temp_address ROW( street_address LONG VARCHAR,
city VARCHAR( 50 ),
province VARCHAR( 30 ),
country VARCHAR( 40 )
);
SET temp_address = employee.address;

Related Information

ARRAY constructor [Composite] [page 235]


ROW constructor [Composite] [page 513]
UNNEST array operator [page 26]

1.2.8 TABLE REF data type

The TABLE REF data type stores a reference to a base table, temporary table, or view. This data type is only for
use with connection-scope variables.

Syntax
Declaring a variable of type TABLE REF

DECLARE table-ref-variable TABLE REF


[ { DEFAULT | = } TABLE REF ( [ owner.]table-name ) ]

Creating a variable of type TABLE REF

CREATE VARIABLE table-ref-variable TABLE REF


[ { DEFAULT | = } TABLE REF ( [ owner.]table-name ) ]

Setting a variable of type TABLE REF

SET table-ref-variable = TABLE REF ( table-name )

Referencing a variable of type TABLE REF in DML statements

TABLE REF ( table-ref-variable ) AS correlation-name

Referencing a variable of type TABLE REF as a parameter in a function or procedure

TABLE REF ( table-ref-variable )

SQL Anywhere - SQL Reference


182 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Parameters

table-ref-variable A valid identifier for the table reference variable.


table-name The name of a base table. Optionally, include the owner as part of the specification (for example,
GROUPO.Employees); this is recommended for base tables and views.

Remarks

Table reference variables (variables of type TABLE REF) allow procedures and functions to be defined even
though the names of the tables they operate on change or have not yet been defined.

When referencing a variable of TABLE REF type in a DML statement, you must specify a correlation name for
results.

When you specify a table reference variable in a statement, the table is looked up immediately before the
statement is executed.

Table reference variables can only accessed by their creator.

Creating a table reference variable does not create a dependence between the variable and the underlying table,
and DDL statements can still be performed on tables referenced by a table reference variable.

If a table is dropped, then any table reference variables that refer to it are invalidated; an attempt to use an invalid
table reference variable returns an error.

When executing a statement that acts on a table specified by using a table reference variable, you need the
appropriate privileges on the underlying table referenced by the variable.

Restrictions on the use of table reference variables:

● Table reference variables cannot be used in a SELECT or DML statement if the variable resolves to the NULL
value.
● Table reference variables cannot be used to specify tables in DDL statements.
● Table reference variables cannot be used as columns in base tables, temporary tables, or views.
● Table reference variables cannot be used in a top-level SELECT block or query expression that is returned to a
client.
● Table reference variables cannot be combined with other types of variables in built-in functions that require a
common super-type for the parameters.
● Table reference variables cannot be ordered or used as part of calculations or comparisons except for
equality and inequality.

The table reference variable functionality overlaps with indirect identifier functionality; both are ways of indirectly
referring to a table. However, a table reference is resolved at creation time and remains a valid reference, whereas
an indirect reference is resolved when the statement that references it is executed and therefore may not be a
valid reference.

Additionally, a table reference can provide access to a table that is not accessible in the current context, whereas
an indirect identifier cannot. For example, suppose your procedure creates, and then refers to, a local table that
has the same name as a base table. Now let's say you need to refer to the base table from within the procedure.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 183
An indirect identifier for the table would resolve to the local table, which is not what you want. To precisely identify
the base table instead, use a table reference variable. For example:

CREATE OR REPLACE PROCEDURE PROC1()


BEGIN
DECLARE LOCAL TEMPORARY TABLE myTab (x INTEGER, y INTEGER);
DECLARE tab_ref TABLE REF = TABLE REF (myTab);
INSERT INTO myTab VALUES (1,100), (2,200), (3,300);
SELECT * FROM PROC2( tab_ref );
END;
CREATE OR REPLACE PROCEDURE PROC2( IN @tab_ref TABLE REF )
RESULT (v1 LONG VARCHAR, v2 INTEGER)
BEGIN
DECLARE LOCAL TEMPORARY TABLE myTab ( pk INTEGER, val LONG VARCHAR );
INSERT INTO myTab VALUES( 1, 'apple'), (3, 'pear'), (10, 'banana');
SELECT val,T2.y FROM myTab T1 JOIN TABLE REF( @tab_ref ) AS T2 ON T2.x = T1.pk;
END;
CALL PROC1;

Table 2: Result:

v1 v2

apple 100

pear 300

The myTab table in PROC2 shadows (hides) myTab that was created in PROC1, so the only table accessible by
using the name myTab in PROC2 would be the locally declared myTab. Using a table reference (TABLE
REF( @tab_ref )) more precisely identifies the object being joined to (in this example, the table created in
PROC1.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following example declares a table reference variable, @ref, sets it to the GROUPO.Employees table
reference, and then queries the table using the table reference variable:

DECLARE @ref TABLE REF = TABLE REF ( GROUPO.Employees )


SELECT * FROM TABLE REF ( @ref ) AS T;

The following example creates a table reference variable called @tableDefinition and sets it to the
GROUPO.Employees table reference, and then selects from the table using the table reference variable:

CREATE VARIABLE @tableDefinition TABLE REF;


SET @tableDefinition = TABLE REF ( GROUPO.Employees );
SELECT * FROM TABLE REF ( @tableDefinition ) AS T;

SQL Anywhere - SQL Reference


184 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
The following code snippet declares a variable named @myTableRefVariable1 with the TABLE REF data type
and sets it to the GROUPO.Employees table reference:

DECLARE @myTableRefVariable1 TABLE REF;


SET @myTableRefVariable1 = TABLE REF ( GROUPO.Employees );

The following example creates a TABLE REF variable, sets it to the GROUPO.Employees table, and then queries
the table reference variable for employees with birthdays in the month of February:

CREATE VARIABLE @myTableRefVariable2 TABLE REF;


SET @myTableRefVariable2 = TABLE REF ( GROUPO.Employees );
SELECT T.surname, T.givenname, T.birthdate FROM TABLE REF
( @myTableRefVariable2 ) AS T
WHERE MONTH( T.birthdate ) = 2;

Table 3: Results
surname givenname birthdate

Davidson Jo Ann 1957-02-17

Samuels Peter 1968-02-28

Barker Joseph 1969-02-14

Sterling Paul 1950-02-27

The following example shows a table reference variable (@myTableRefVariable3) being used in several
statements to update the GROUPO.Employees table. Notice that a correlation name (T, in this example) is
required when specifying a table using a table reference variable in a DML statement:

CREATE VARIABLE @myTableRefVariable3 TABLE REF;


SET @myTableRefVariable3 = TABLE REF ( GROUPO.Employees );
UPDATE TABLE REF ( @myTableRefVariable3 ) AS T SET T.GivenName =
REPLACE( GivenName, 'Fran', 'Francis' );
DELETE FROM TABLE REF ( @myTableRefVariable3 ) AS T WHERE Surname = 'Holmes';
SELECT * FROM TABLE REF ( @myTableRefVariable3 ) AS T;

The following example shows how you can use table reference variables in a procedure:

CREATE OR REPLACE PROCEDURE leapday_births( IN @tab TABLE REF )


RESULT ( Surname person_name_t, GivenName person_name_t, Birthdate TIMESTAMP)
BEGIN
SELECT Surname, GivenName, Birthdate FROM TABLE REF ( @tab ) AS T
WHERE MONTH( Birthdate ) = 02 AND DAY( Birthdate ) = 29;
END;
CREATE VARIABLE @myTableRefVariable4 TABLE REF;
SET @myTableRefVariable4 = TABLE REF ( GROUPO.Employees );
CALL leapday_births(@myTableRefVariable4);

Related Information

SQL variables [page 120]


Identifiers [page 6]
Indirect identifiers [page 8]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 185
1.2.9 Spatial data types

Many spatial data types are supported. The documentation for these data types are located with the spatial SQL
API documentation.

1.2.10 Domains

Domains are aliases for built-in data types, including precision and scale values where applicable, and optionally
including DEFAULT values and CHECK conditions. Some domains, such as the monetary data types, are
predefined, but you can add more of your own.

Domains, also called user-defined data types, allow columns throughout a database to be automatically defined
on the same data type, with the same NULL or NOT NULL condition, with the same DEFAULT setting, and with the
same CHECK condition. Domains encourage consistency throughout the database and can eliminate some types
of errors.

Simple domains

Domains are created using the CREATE DOMAIN statement.

The following statement creates a data type named street_address, which is a 35-character string.

CREATE DOMAIN street_address CHAR( 35 );

CREATE DATATYPE can be used as an alternative to CREATE DOMAIN, but is not recommended.

You must have the CREATE DATATYPE or CREATE ANY OBJECT system privilege to create domains. Once a data
type is created, the user ID that executed the CREATE DOMAIN statement is the owner of that data type. Any user
can use the data type. Unlike with other database objects, the owner name is never used to prefix the data type
name.

The street_address data type can be used in exactly the same way as any other data type when defining columns.
For example, the following table with two columns has the second column as a street_address column:

CREATE TABLE twocol (


ID INT,
street street_address
);

You can also drop a domain:

DROP DOMAIN street_address;

This statement can be executed only if the data type is not used in any table in the database. If you attempt to
drop a domain that is in use, an error message appears.

SQL Anywhere - SQL Reference


186 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Constraints and defaults with domains

Many of the attributes associated with columns, such as allowing NULL values, having a DEFAULT value, and so
on, can be built into a domain. Any column that is defined on the data type automatically inherits the NULL setting,
CHECK condition, and DEFAULT values. This allows uniformity to be built into columns with a similar meaning
throughout a database.

For example, many primary key columns in the SQL Anywhere sample database are integer columns holding ID
numbers. The following statement creates a data type that can be useful for such columns:

CREATE DOMAIN ID INT


NOT NULL
DEFAULT AUTOINCREMENT
CHECK( @col > 0 );

By default, a column created using the id data type does not allow NULLs, defaults to an auto-incremented value,
and must hold a positive number. Any identifier could be used instead of col in the @col variable.

The attributes of a data type can be overridden by explicitly providing attributes for the column. A column created
using the id data type with NULL values explicitly allowed does allow NULLs, regardless of the setting in the id data
type.

Compatibility

Named constraints and defaults

Domains are created with a base data type, and optionally a NULL or NOT NULL condition, a default value,
and a CHECK condition. Named constraints and named defaults are not supported.
Creating data types

You can use the sp_addtype system procedure to add a domain, or you can use the CREATE DOMAIN
statement.

Related Information

CREATE DOMAIN statement [page 798]


DROP DOMAIN statement [page 1039]

1.2.11 Data type comparisons

When a comparison (such as =) is performed between arguments with different data types, one or more
arguments must be converted so that the comparison operation is done using one data type.

Some rules may lead to conversions that fail, or lead to unexpected results from the comparison. In these cases,
you should explicitly convert one of the arguments using CAST or CONVERT.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 187
You can override these conversion rules by explicitly casting arguments to another type. For example, to compare
a DATE and a CHAR as a CHAR, explicitly cast the DATE to a CHAR.

In this section:

Lossy conversion and substitution characters [page 188]


When a character cannot be represented in the character set into which it is being converted, a
substitution character is used instead. Conversions of this type are considered lossy; the original
character is lost if it cannot be represented in the destination character set.

Comparisons between CHAR and NCHAR [page 189]


When a comparison is performed between a value of CHAR type (CHAR, VARCHAR, LONG VARCHAR)
and a value of NCHAR type (NCHAR, NVARCHAR, LONG NVARCHAR), the database server uses inference
rules to determine the type in which the comparison should be performed.

Comparisons between numeric data types [page 190]


The database server uses the rules when comparing numeric data types. The rules are examined in the
order listed, and the first rule that applies is used.

Comparisons of dates and times [page 191]


The table below summarizes the conversions that are implicit when comparing certain data types with
date, time, or date-time data types.

Comparisons of composite types [page 192]


Array elements are compared starting from the first element.

Transact-SQL string to date/time conversions [page 193]


If a string containing only a time value (no date) is converted to a date/time data type, the database server
uses the current date.

Other comparisons [page 193]


There are other data type comparisons that take place.

Related Information

CAST function [Data type conversion] [page 265]

1.2.11.1 Lossy conversion and substitution characters

When a character cannot be represented in the character set into which it is being converted, a substitution
character is used instead. Conversions of this type are considered lossy; the original character is lost if it cannot
be represented in the destination character set.

Also, not only may different character sets have a different substitution character, but the substitution character
for one character set can be a non-substitution character in another character set. This is important to
understand when multiple conversions are performed on a character because the final character may not appear
as the expected substitution character of the destination character set.

For example, suppose that the client character set is Windows-1252, and the database character set is
ISO_8859-1:1987, the U.S. default for some versions of Unix. Then, suppose a non-Unicode client application (for

SQL Anywhere - SQL Reference


188 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
example, Embedded SQL) attempts to insert the euro symbol into a CHAR, VARCHAR, or LONG VARCHAR
column. Since the character does not exist in the CHAR character set, the substitution character for
ISO_8859-1:1987, 0x1A, is inserted.

Now, if this same ISO_8859-1:1987 substitution character is then fetched as Unicode (for example, by doing a
SELECT * FROM t into a SQL_C_WCHAR bound column in ODBC), this character becomes the Unicode code
point U+001A. (In Unicode the code point U+001A is the record separator control character.) However, the
substitution character for Unicode is the code point U+FFFD. This example illustrates that even if your data
contains substitution characters, those characters, due to multiple conversions, may not be converted to the
substitution character of the destination character set.

Therefore, it is important to understand and test how substitution characters are used when converting between
multiple character sets.

The on_charset_conversion_failure option can help determine the behavior during conversion when a character
cannot be represented in the destination character set.

Related Information

Data type conversions [page 194]


Comparisons between CHAR and NCHAR [page 189]

1.2.11.2 Comparisons between CHAR and NCHAR

When a comparison is performed between a value of CHAR type (CHAR, VARCHAR, LONG VARCHAR) and a value
of NCHAR type (NCHAR, NVARCHAR, LONG NVARCHAR), the database server uses inference rules to determine
the type in which the comparison should be performed.

Generally, if one value is based on a column reference and the other is not, the comparison is performed in the
type of the value containing the column reference.

The inference rules revolve around whether a value is based on a column reference. In the case where one value is
a variable, a host variable, a literal constant, or a complex expression not based on a column reference and the
other value is based on a column reference, then the constant-based value is implicitly cast to the type of the
column-based value.

Following are the inference rules, in the order in which they are applied:

● If the NCHAR value is based on a column reference, the CHAR value is implicitly cast to NCHAR, and the
comparison is done as NCHAR. This includes the case where both the NCHAR and CHAR value are based on
column references.
● Else if the NCHAR value is not based on a column reference, and the CHAR value is based on a column
reference, the NCHAR value is implicitly cast to CHAR, and the comparison is done as CHAR.
It is important to consider the setting for the on_charset_conversion_failure option if you anticipate NCHAR to
CHAR conversions since this option controls behavior if an NCHAR character cannot be represented in the
CHAR character set.
● Else if neither value is based on a column reference, then the CHAR value is implicitly cast to NCHAR and the
comparison is done as NCHAR.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 189
Example
The condition Employees.GivenName = N'Susan' compares a CHAR column (Employees.GivenName) to
the literal N'Susan'. The value N'Susan' is cast to CHAR, and the comparison is performed as if it had been
written as:

Employees.GivenName = CAST( N'Susan' AS CHAR );

Alternatively, the condition Employees.GivenName = T.nchar_column would find that the value
T.nchar_column cannot be cast to CHAR. The comparison would be performed as if it were written as follows,
and an index on Employees.GivenName cannot be used:

CAST( Employees.GivenName AS NCHAR ) = T.nchar_column;

Related Information

NCHAR to CHAR conversions [page 195]


NCHAR to CHAR conversions [page 195]
Lossy conversion and substitution characters [page 188]
CAST function [Data type conversion] [page 265]
CONVERT function [Data type conversion] [page 285]
CAST function [Data type conversion] [page 265]

1.2.11.3 Comparisons between numeric data types

The database server uses the rules when comparing numeric data types. The rules are examined in the order
listed, and the first rule that applies is used.

1. If one argument is TINYINT and the other is INTEGER, convert both to INTEGER and compare.
2. If one argument is TINYINT and the other is SMALLINT, convert both to SMALLINT and compare.
3. If one argument is UNSIGNED SMALLINT and the other is INTEGER, convert both to INTEGER and compare.
4. If the data types of the arguments have a common super type, convert to the common super type and
compare. The super types are the final data type in each of the following lists:
○ BIT > TINYINT > UNSIGNED SMALLINT > UNSIGNED INTEGER > UNSIGNED BIGINT > NUMERIC
○ SMALLINT > INTEGER > BIGINT > NUMERIC
○ REAL > DOUBLE
○ CHAR > LONG VARCHAR
○ BINARY > LONG BINARY
For example, if the two arguments are of types BIT and TINYINT, they are converted to NUMERIC.

SQL Anywhere - SQL Reference


190 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.2.11.4 Comparisons of dates and times

The table below summarizes the conversions that are implicit when comparing certain data types with date, time,
or date-time data types.

Data type Data type Conversion

CHAR DATE CHAR cast to TIMESTAMP; DATE cast to


TIMESTAMP

CHAR TIME CHAR cast to TIME

CHAR TIMESTAMP CHAR cast to TIMESTAMP

CHAR TIMESTAMP WITH TIME ZONE CHAR cast to TIMESTAMP WITH TIME
ZONE

DATE TIME illegal

DATE TIMESTAMP DATE cast to TIMESTAMP

DATE TIMESTAMP WITH TIME ZONE DATE cast to TIMESTAMP WITH TIME
ZONE

DATE SMALLINT, INTEGER, BIGINT, and NU­ SMALLINT, INTEGER, BIGINT, and NU­
MERIC MERIC value treated as a date string and
cast to TIMESTAMP; DATE cast to TIME­
STAMP

DATE REAL, FLOAT, and DOUBLE REAL, FLOAT, and DOUBLE treated as a
number of days since 0000-02-29 and
cast to TIMESTAMP; DATE cast to TIME­
STAMP

TIME TIMESTAMP TIMESTAMP cast to TIME

TIME TIMESTAMP WITH TIME ZONE illegal

TIMESTAMP TIMESTAMP WITH TIME ZONE TIMESTAMP cast to TIMESTAMP WITH


TIME ZONE

TIMESTAMP SMALLINT, INTEGER, BIGINT, and NU­ SMALLINT, INTEGER, BIGINT, and NU­
MERIC MERIC value treated as a date string and
cast to TIMESTAMP

TIMESTAMP REAL, FLOAT, and DOUBLE REAL, FLOAT, and DOUBLE treated as a
number of days since 0000-02-29 and
cast to TIMESTAMP

The following points expand on the information presented in the table above.

1. Only values of type TIME, TIMESTAMP, and CHAR can be compared to a value of type TIME. Comparison with
values of other data types results in a conversion error. When comparing a time value and a value of another
type, the comparison data type is TIME.
2. When comparing a TIMESTAMP, SMALLINT, INTEGER, BIGINT, NUMERIC, REAL, FLOAT, or DOUBLE value to
a DATE value, the comparison data type is always TIMESTAMP.
3. When comparing a TIMESTAMP WITH TIME ZONE value to a DATE value, the comparison data type is
TIMESTAMP WITH TIME ZONE.
4. When a time value is cast to a TIMESTAMP, the result is formed by combining the current date with the time
value.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 191
5. Exact numeric values of type SMALLINT, INTEGER, BIGINT, and NUMERIC can be converted to date values.
The conversion is performed by treating the number as a string. For example, the integer value 20100401
represents the first day of April in 2010.
6. The unsigned exact numeric types BIT, TINYINT, UNSIGNED SMALLINT, UNSIGNED INTEGER, and
UNSIGNED BIGINT cannot be converted to date values.
7. Approximate numeric values of type REAL, FLOAT, and DOUBLE can be converted to dates by treating the
number as the number of days since the fictional date 0000-02-29. For example, 307 represents 0001-01-01
and 734169 represents 2010-04-01.

Related Information

Date and time data types [page 155]

1.2.11.5 Comparisons of composite types

Array elements are compared starting from the first element.

When a difference is found, the comparison stops and the result of the comparison between the most recently
compared elements is returned. If all of the elements compare equal, then the arrays are equal. The comparisons
performed are equivalent to those performed on expressions that are not held in arrays. If one array is shorter
than another, and all elements of the shorter array are equal to the same elements of the longer array, the shorter
array is considered less than the longer array.

When comparing arrays, the arrays must hold values with union-compatible data types. Duplicate elimination and
GROUP BY are also supported over array expressions. For example, with the following array comparison, the
query returns 1:

SELECT IF ARRAY(3,4,5) > ARRAY(2,3,4) THEN 1 ELSE 0 ENDIF;

Row types can be compared, used in joins, duplicate elimination, and grouping. Consider two row types similar to
the row expression sample above:

BEGIN
DECLARE test1 ROW(x INT, w ROW(y INT, z INT));
DECLARE test2 ROW(a INT, b ROW(c INT, d CHAR(3)));
SET test1 = ROW(3, ROW(6,7));
SET test2 = ROW(3, ROW(8,'7'));
SELECT (IF (test1 > test2) THEN 1 ELSE 0 ENDIF) AS RESULT FROM SYS.DUMMY;
END

Two row expressions can be compared only if their structures match. However, while the row expressions must
have the same structure, the names of the attributes of a row type do not need to be identical, and the data types
of the individual leaf values do not need to be identical, only union compatible.

All ROW comparisons other than equality and inequality operations result in UNKNOWN.

SQL Anywhere - SQL Reference


192 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.2.11.6 Transact-SQL string to date/time conversions

If a string containing only a time value (no date) is converted to a date/time data type, the database server uses
the current date.

If the fraction portion of a time is less than 3 digits, the database server interprets the value the same way
regardless of the whether it is preceded by a period or a colon: one digit means tenths, two digits mean
hundredths, and three digits mean thousandths.

Example
The database server converts the milliseconds value in the same manner regardless of the separator.

12:34:56.7 to 12:34:56.700
12:34:56:7 to 12:34:56.700
12.34.56.78 to 12:34:56.780
12.34.56:78 to 12:34:56.780
12:34:56.789 to 12:34:56.789
12:34:56:789 to 12:34:56.789

1.2.11.7 Other comparisons

There are other data type comparisons that take place.

1. If the data types are a mixture of CHAR (such as CHAR, VARCHAR, LONG VARCHAR, and so on, but not
NCHAR types), convert to LONG VARCHAR and compare.
2. If the data type of any argument is UNIQUEIDENTIFIER, convert to UNIQUEIDENTIFIER and compare.
3. If the data type of any argument is a bit array (VARBIT or LONG VARBIT), convert to LONG VARBIT and
compare.
4. If one argument has CHARACTER data type and the other has BINARY data type, convert to BINARY and
compare.
5. If one argument is a CHAR type, and the other argument is an NCHAR type, use predefined inference rules.
6. If no rule exists, convert to NUMERIC and compare.
For example, if the two arguments have REAL and CHAR data types, they are both converted to NUMERIC.

Because of the characteristics of the values being stored, some data types such as ARRAY and TABLE REF may
not return expected results when used in comparisons, even when being compared against values of the same
type. In the case of the TABLE REF data type, which is only supported for variables, two values of type TABLE REF
are considered equal if they contain an identical value and have the same owner.

Related Information

Comparisons between CHAR and NCHAR [page 189]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 193
1.2.12 Data type conversions

Type conversions can happen automatically, or they can be explicitly requested using the CAST or CONVERT
function. The following functions can also be used to force type conversions:

DATE function

Converts the expression into a DATE, and removes any hours, minutes or seconds. Conversion errors can be
reported.
DATETIME function

Converts the expression into a TIMESTAMP, and removes any time zone. Conversion errors can be reported.
STRING function

This function is equivalent to CAST(value AS LONG VARCHAR).


VALUE+0.0

Equivalent to CAST( value AS DECIMAL ).

The following list is a high-level view of automatic data type conversions:

● If a string is used in a numeric expression or as an argument to a function that expects a numeric argument,
the string is converted to a number.
● If a number is used in a string expression or as a string function argument, it is converted to a string before
being used.
● All date constants are specified as strings. The string is automatically converted to a date before use.

Some data types, such as the TABLE REF data type (for use only with variables), cannot be converted to or from
another data type.

There are certain cases where the automatic database conversions are not appropriate. For example, the
automatic data type conversion fails in the example below.

'12/31/90' + 5
'a' > 0

In this section:

NCHAR to CHAR conversions [page 195]


NCHAR to CHAR conversions can occur as part of a comparison of CHAR and NCHAR data, or when
specifically requested.

NULL constant conversions to NUMERIC and string types [page 195]


When converting a NULL constant to a NUMERIC, or to a string type such as CHAR, VARCHAR, LONG
VARCHAR, BINARY, VARBINARY, and LONG BINARY the size is set to 0. For example:

Bit array conversions [page 196]


You can convert to and from bit arrays.

Numeric set conversions [page 198]


When converting a DOUBLE type to a NUMERIC type, precision is maintained for the first 15 significant
digits.

Java and SQL data type conversions [page 198]

SQL Anywhere - SQL Reference


194 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Data type conversion between Java types and SQL types is required for both Java stored procedures and
JDBC applications. Java to SQL and SQL to Java data type conversions are carried out according to the
JDBC standard. The conversions are described in the following tables.

Related Information

Data type conversion functions [page 205]


DATE function [Date and time] [page 304]
DATETIME function [Date and time] [page 313]
STRING function [String] [page 550]
CAST function [Data type conversion] [page 265]

1.2.12.1 NCHAR to CHAR conversions

NCHAR to CHAR conversions can occur as part of a comparison of CHAR and NCHAR data, or when specifically
requested.

This type of conversion is lossy because depending on the CHAR character set, there can be some NCHAR
characters that cannot be represented in the CHAR type. When an NCHAR character cannot be converted to
CHAR, a substitution character from the CHAR character set is used instead. For single-byte character sets, this
is usually hex 1A.

Depending on the setting of the on_charset_conversion_failure option, when a character cannot be converted, one
of the following can happen:

● a substitute character is used, and no warning is issued


● a substitute character is used, and a warning is issued
● an error is returned

Therefore, it is important to consider this option when converting from NCHAR to CHAR.

Related Information

Comparisons between CHAR and NCHAR [page 189]

1.2.12.2 NULL constant conversions to NUMERIC and string


types

When converting a NULL constant to a NUMERIC, or to a string type such as CHAR, VARCHAR, LONG VARCHAR,
BINARY, VARBINARY, and LONG BINARY the size is set to 0. For example:

SELECT CAST( NULL AS CHAR ) returns CHAR(0)

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 195
SELECT CAST( NULL AS NUMERIC ) returns NUMERIC(1,0)

1.2.12.3 Bit array conversions

You can convert to and from bit arrays.

Converting integers to bit arrays

When converting an integer to a bit array, the length of the bit array is the number of bits in the integer type, and
the bit array's value is the binary representation. The most significant bit of the integer becomes the first bit of the
array.

Example
SELECT CAST( CAST( 1 AS BIT ) AS VARBIT ) returns a VARBIT(1) containing 1.

SELECT CAST( CAST( 8 AS TINYINT ) AS VARBIT ) returns a VARBIT(8) containing 00001000.

SELECT CAST( CAST( 194 AS INTEGER ) AS VARBIT ) returns a VARBIT(32) containing


00000000000000000000000011000010.

Converting binary to bit arrays

When converting a binary type of length n to a bit array, the length of the array is n * 8 bits. The first 8 bits of the
bit array become the first byte of the binary value. The most significant bit of the binary value becomes the first bit
in the array. The next 8 bits of the bit array become the second byte of the binary value, and so on.

Example
SELECT CAST( 0x8181 AS VARBIT ) returns a VARBIT(16) containing 1000000110000001.

Converting characters to bit arrays

When converting a character data type of length n to a bit array, the length of the array is n bits. Each character
must be either '0' or '1' and the corresponding bit of the array is assigned the value 0 or 1.

Example
SELECT CAST( '001100' AS VARBIT ) returns a VARBIT(6) containing 001100.

SQL Anywhere - SQL Reference


196 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Converting bit arrays to integers

When converting a bit array to an integer data type, the bit array's binary value is interpreted according to the
storage format of the integer type, using the most significant bit first.

Example
SELECT CAST( CAST( '11000010' AS VARBIT ) AS INTEGER ) returns 194 (110000102 = 0xC2 = 194).

Converting bit arrays to binary

When converting a bit array to a binary, the first 8 bits of the array become the first byte of the binary value. The
first bit of the array becomes the most significant bit of the binary value. The next 8 bits are used as the second
byte, and so on. If the length of the bit array is not a multiple of 8, then extra zeros are used to fill the least
significant bits of the last byte of the binary value.

Example
SELECT CAST( CAST( '1111' AS VARBIT ) AS BINARY ) returns 0xF0 (11112 becomes 111100002 =
0xF0).

SELECT CAST( CAST( '0011000000110001' AS VARBIT ) AS BINARY ) returns 0x3031


(00110000001100012 = 0x3031).

Converting bit arrays to characters

When converting a bit array of length n bits to a character data type, the length of the result is n characters. Each
character in the result is either '0' or '1', corresponding to the bit in the array.

Example
SELECT CAST( CAST( '01110' AS VARBIT ) AS VARCHAR ) returns the character string '01110'.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 197
1.2.12.4 Numeric set conversions

When converting a DOUBLE type to a NUMERIC type, precision is maintained for the first 15 significant digits.

Related Information

CAST function [Data type conversion] [page 265]


CONVERT function [Data type conversion] [page 285]

1.2.12.5 Java and SQL data type conversions

Data type conversion between Java types and SQL types is required for both Java stored procedures and JDBC
applications. Java to SQL and SQL to Java data type conversions are carried out according to the JDBC standard.
The conversions are described in the following tables.

In this section:

Java to SQL data type conversions [page 198]


Data type conversion between Java types and SQL types is required for both Java stored procedures and
JDBC applications.

SQL to Java data type conversions [page 199]


Data type conversion between SQL types and Java types follow a specific mapping.

1.2.12.5.1 Java to SQL data type conversions

Data type conversion between Java types and SQL types is required for both Java stored procedures and JDBC
applications.

Java type SQL type

String CHAR

String VARCHAR

String TEXT

java.math.BigDecimal NUMERIC

java.math.BigDecimal MONEY

java.math.BigDecimal SMALLMONEY

boolean BIT

byte TINYINT

short SMALLINT

SQL Anywhere - SQL Reference


198 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Java type SQL type

int INTEGER

long BIGINT

float REAL

double DOUBLE

byte[ ] VARBINARY

byte[ ] IMAGE

java.sql.Date DATE

java.sql.Time TIME

java.sql.Timestamp TIMESTAMP

java.lang.Double DOUBLE

java.lang.Float REAL

java.lang.Integer INTEGER

java.lang.Long BIGINT

1.2.12.5.2 SQL to Java data type conversions

Data type conversion between SQL types and Java types follow a specific mapping.

SQL type Java type

CHAR String

VARCHAR String

TEXT String

NUMERIC java.math.BigDecimal

DECIMAL java.math.BigDecimal

MONEY java.math.BigDecimal

SMALLMONEY java.math.BigDecimal

UNSIGNED BIGINT java.math.BigDecimal (precision=20, scale=0)

BIT boolean

TINYINT byte

SMALLINT short

UNSIGNED SMALLINT int

INTEGER int

UNSIGNED INTEGER long

BIGINT long

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 199
SQL type Java type

REAL float

FLOAT double

DOUBLE double

BINARY byte[ ]

VARBINARY byte[ ]

LONG BINARY byte[ ]

IMAGE byte[ ]

DATE java.sql.Date

TIME java.sql.Time

TIMESTAMP java.sql.Timestamp

1.3 SQL functions

Functions are used to return information from the database. They can be called anywhere an expression is
allowed.

Unless otherwise specified in the documentation, NULL is returned for a function if any argument is NULL.

Functions use the same syntax conventions used by SQL statements.

In SQL Anywhere, if an argument is optional, then DEFAULT can be provided as an argument.

In this section:

Function types [page 201]


Functions can be grouped according to the type of data they operate on, or the context in which they are
used.

Functions [page 219]


Each function is listed, and the function type (numeric, character, and so on) is indicated next to it.

Related Information

Syntax conventions [page 613]

SQL Anywhere - SQL Reference


200 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.3.1 Function types
Functions can be grouped according to the type of data they operate on, or the context in which they are used.

Note
Unless otherwise stated, any SQL Anywhere function that receives NULL as a parameter returns NULL.

UltraLite: UltraLite supports a subset of the same functions documented for SQL Anywhere, and sometimes with
a few differences.

In this section:

Aggregate functions [page 202]


Aggregate functions summarize data over a group of rows from the database. The groups are formed
using the GROUP BY clause of the SELECT statement. Aggregate functions are allowed only in the
SELECT list and in the HAVING and ORDER BY clauses of a SELECT statement.

Composite functions [page 203]


Composite functions allow you to perform tasks on arrays.

Bit array functions [page 204]


Bit array functions allow you to perform tasks on bit arrays.

Ranking functions [page 205]


Ranking functions let you compute a rank value for each row in a result set based on an ordering specified
in the query.

Data type conversion functions [page 205]


Data type conversion functions are used to convert arguments from one data type to another, or to test
whether they can be converted.

Date and time functions [page 206]


Date and time functions perform operations on DATE, TIME, TIMESTAMP, and TIMESTAMP WITH TIME
ZONE data types.

Support for user-defined functions [page 209]


A user-defined function, or UDF, is a function created by the user of a program or environment. User-
defined functions are in contrast to functions that are built in to the program or environment.

Miscellaneous functions [page 211]


Miscellaneous functions perform operations on arithmetic, string, or date/time expressions, including the
return values of other functions.

Numeric functions [page 212]


Numeric functions perform mathematical operations on numerical data types or return numeric
information.

Web services functions [page 213]


HTTP functions assist the handling of HTTP requests within web services. Likewise, SOAP functions assist
the handling of SOAP requests within web services.

String functions [page 214]


String functions perform conversion, extraction, or manipulation operations on strings, or return
information about strings.

System functions [page 217]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 201
System functions return system information.

Text and image functions [page 219]


Text and image functions operate on text and image data types. Only the TEXTPTR text and image
function is supported.

1.3.1.1 Aggregate functions

Aggregate functions summarize data over a group of rows from the database. The groups are formed using the
GROUP BY clause of the SELECT statement. Aggregate functions are allowed only in the SELECT list and in the
HAVING and ORDER BY clauses of a SELECT statement.

List of SQL Anywhere functions

The following aggregate functions are available:

ARRAY_AGG function [Aggregate]


AVG function [Aggregate]
BIT_AND function [Aggregate]
BIT_OR function [Aggregate]
BIT_XOR function [Aggregate]
COVAR_POP function [Aggregate]
COVAR_SAMP function [Aggregate]
COUNT function [Aggregate]
COUNT_BIG function [Aggregate]
CORR function [Aggregate]
FIRST_VALUE function [Aggregate]
GROUPING function [Aggregate]
LAST_VALUE function [Aggregate]
LIST function [Aggregate]
MAX function [Aggregate]
MEDIAN function [Aggregate]
MIN function [Aggregate]
REGR_AVGX function [Aggregate]
REGR_AVGY function [Aggregate]
REGR_COUNT function [Aggregate]
REGR_INTERCEPT function [Aggregate]
REGR_R2 function [Aggregate]
REGR_SLOPE function [Aggregate]
REGR_SXX function [Aggregate]
REGR_SXY function [Aggregate]
REGR_SYY function [Aggregate]
SET_BITS function [Aggregate]

SQL Anywhere - SQL Reference


202 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
STDDEV function [Aggregate]
STDDEV_POP function [Aggregate]
STDDEV_SAMP function [Aggregate]
SUM function [Aggregate]
VAR_POP function [Aggregate]
VAR_SAMP function [Aggregate]
VARIANCE function [Aggregate]
XMLAGG function [Aggregate]

List of UltraLite functions

The following aggregate functions are available:

AVG function [Aggregate] - UltraLite


COUNT function [Aggregate] - UltraLite
COUNT_UPLOAD_ROWS function [Aggregate] - UltraLite
LIST function [Aggregate] - UltraLite
MAX function [Aggregate] - UltraLite
MIN function [Aggregate] - UltraLite
SUM function [Aggregate] - UltraLite

1.3.1.2 Composite functions

Composite functions allow you to perform tasks on arrays.

List of functions

The following composite functions are available:

ARRAY constructor [Composite]


ROW constructor [Composite]
ARRAY_MAX_CARDINALITY function [Composite]
CARDINALITY function [Composite]
TRIM_ARRAY function [Composite]

Related Information

ARRAY_AGG function [Aggregate] [page 238]


UNNEST array operator [page 26]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 203
1.3.1.3 Bit array functions

Bit array functions allow you to perform tasks on bit arrays.

List of functions

The following bit array functions are available:

● BIT_AND function [Aggregate]


● BIT_OR function [Aggregate]
● BIT_XOR function [Aggregate]
● BIT_LENGTH function [Bit array]
● BIT_SUBSTR function [Bit array]
● COUNT_SET_BITS function [Bit array]
● GET_BIT function [Bit array]
● SET_BIT function [Bit array]
● SET_BITS function [Aggregate]

Related Information

Bitwise operators [page 31]


sa_get_bits system procedure [page 1516]
BIT_AND function [Aggregate] [page 251]
BIT_OR function [Aggregate] [page 253]
BIT_XOR function [Aggregate] [page 256]
BIT_LENGTH function [Bit array] [page 252]
BIT_SUBSTR function [Bit array] [page 254]
COUNT_SET_BITS function [Bit array] [page 294]
GET_BIT function [Bit array] [page 374]
SET_BIT function [Bit array] [page 525]
SET_BITS function [Aggregate] [page 527]

SQL Anywhere - SQL Reference


204 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.3.1.4 Ranking functions

Ranking functions let you compute a rank value for each row in a result set based on an ordering specified in the
query.

List of functions

The following rank functions are available:

CUME_DIST function [Ranking]


DENSE_RANK function [Ranking]
PERCENT_RANK function [Ranking]
RANK function [Ranking]

Related Information

CUME_DIST function [Ranking] [page 301]


DENSE_RANK function [Ranking] [page 334]
PERCENT_RANK function [Ranking] [page 468]
RANK function [Ranking] [page 482]

1.3.1.5 Data type conversion functions

Data type conversion functions are used to convert arguments from one data type to another, or to test whether
they can be converted.

List of SQL Anywhere functions

The following data type conversion functions are available:

BINTOHEX function [Data type conversion]


CAST function [Data type conversion]
CONVERT function [Data type conversion]
HEXTOBIN function [Data type conversion]
HEXTOINT function [Data type conversion]
INTTOHEX function [Data type conversion]
ISDATE function [Data type conversion]
ISNUMERIC function [Miscellaneous]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 205
TREAT function [Data type conversion]

List of UltraLite functions

The following data type conversion functions are available:

CAST function [Data type conversion] - UltraLite


CONVERT function [Data type conversion] - UltraLite
HEXTOINT function [Data type conversion] - UltraLite
INTTOHEX function [Data type conversion] - UltraLite
ISDATE function [Data type conversion] - UltraLite

Related Information

BINTOHEX function [Data type conversion] [page 250]


CAST function [Data type conversion] [page 265]
CONVERT function [Data type conversion] [page 285]
HEXTOBIN function [Data type conversion] [page 384]
HEXTOINT function [Data type conversion] [page 385]
INTTOHEX function [Data type conversion] [page 408]
ISDATE function [Data type conversion] [page 409]
ISNUMERIC function [Miscellaneous] [page 414]
TREAT function [Data type conversion] [page 573]

1.3.1.6 Date and time functions

Date and time functions perform operations on DATE, TIME, TIMESTAMP, and TIMESTAMP WITH TIME ZONE
data types.

SQL Anywhere includes compatibility support for Transact-SQL date and time types, including DATETIME and
SMALLDATETIME. These Transact-SQL data types are implemented as domains over the native TIMESTAMP
data type.

The following date and time functions are available for SQL Anywhere:

DATE function [Date and time]


DATEADD function [Date and time]
DATEDIFF function [Date and time]
DATEFORMAT function [Date and time]
DATENAME function [Date and time]
DATEPART function [Date and time]
DATETIME function [Date and time]

SQL Anywhere - SQL Reference


206 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
DAY function [Date and time]
DAYNAME function [Date and time]
DAYS function [Date and time]
DOW function [Date and time]
GETDATE function [Date and time]
HOUR function [Date and time]
HOURS function [Date and time]
MINUTE function [Date and time]
MINUTES function [Date and time]
MONTH function [Date and time]
MONTHNAME function [Date and time]
MONTHS function [Date and time]
NOW function [Date and time]
QUARTER function [Date and time]
SECOND function [Date and time]
SECONDS function [Date and time]
SWITCHOFFSET function [Date and time]
SYSDATETIMEOFFSET function [Date and time]
TODAY function [Date and time]
TODATETIMEOFFSET function [Date and time]
WEEKS function [Date and time]
YEAR function [Date and time]
YEARS function [Date and time]
YMD function [Date and time]

The following date and time functions are available for UltraLite:

DATE function [Date and time] - UltraLite


DATEADD function [Date and time] - UltraLite
DATEDIFF function [Date and time] - UltraLite
DATEFORMAT function [Date and time] - UltraLite
DATENAME function [Date and time] - UltraLite
DATEPART function [Date and time] - UltraLite
DATETIME function [Date and time] - UltraLite
DAY function [Date and time] - UltraLite
DAYNAME function [Date and time] - UltraLite
DAYS function [Date and time] - UltraLite
DOW function [Date and time] - UltraLite
GETDATE function [Date and time] - UltraLite
HOUR function [Date and time] - UltraLite
HOURS function [Date and time] - UltraLite
MINUTE function [Date and time] - UltraLite
MINUTES function [Date and time] - UltraLite
MONTH function [Date and time] - UltraLite
MONTHNAME function [Date and time] - UltraLite
MONTHS function [Date and time] - UltraLite

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 207
NOW function [Date and time] - UltraLite
QUARTER function [Date and time] - UltraLite
SECOND function [Date and time] - UltraLite
SECONDS function [Date and time] - UltraLite
SWITCHOFFSET function [Date and time] - UltraLite
TODAY function [Date and time] - UltraLite
TODATETIMEOFFSET function [Date and time] - UltraLite
WEEKS function [Date and time] - UltraLite
YEAR function [Date and time] - UltraLite
YEARS function [Date and time] - UltraLite
YMD function [Date and time] - UltraLite

In this section:

Specifying date parts [page 208]


Many of the date functions use dates built from date parts. The following table displays allowed values of
date parts.

1.3.1.6.1 Specifying date parts

Many of the date functions use dates built from date parts. The following table displays allowed values of date
parts.

When using date and time functions, you can specify a minus sign to subtract from a date or time. For example, to
get a timestamp from 31 days ago, you can execute the following:

SELECT DATEADD(day, -31, NOW());

Date part Abbreviation Values

Year YY 1-9999

Quarter QQ 1-4

Month MM 1-12

Week WK 1-54. Weeks begin on Sunday. A 54-week


year occurs in leap years that start on a
Saturday.

Day DD 1-31

Dayofyear DY 1-366

Weekday DW 1-7 (Sunday = 1, ..., Saturday = 7)

Hour HH 0-23

Minute MI 0-59

Second SS 0-59

Millisecond MS 0-999

SQL Anywhere - SQL Reference


208 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Date part Abbreviation Values

Microsecond MCS or US 0-999999

Calyearofweek CYR 1-9999. The year in which the week be­


gins. The week containing the first few
days of the year may have started in the
previous year, depending on the week­
day on which the year started. Years
starting on Monday through Thursday
have no days that are part of the previ­
ous year, but years starting on Friday
through Sunday start their first week on
the first Monday of the year.

Calweekofyear CWK 1-53. The week number within the year


that contains the specified date.

For more information about the ISO


week system and the ISO 8601 date and
time standard, see ISO week date .

Caldayofweek CDW 1-7. (Monday = 1, ..., Sunday = 7)

TZOffset TZ -840 to 840

Related Information

Date and time data types [page 155]


Functions [page 219]

1.3.1.7 Support for user-defined functions

A user-defined function, or UDF, is a function created by the user of a program or environment. User-defined
functions are in contrast to functions that are built in to the program or environment.

User-defined functions in SQL

You can implement your own functions in SQL by using the CREATE FUNCTION statement.

The RETURN statement inside the CREATE FUNCTION statement determines the data type of the function.

Once a SQL user-defined function is created, it can be used anywhere a built-in function of the same data type is
used.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 209
User-defined functions in Java and the CLR

Java classes provide a more powerful and flexible way of implementing user-defined functions, with the additional
advantage that they can be moved from the database server to a client application if desired. Any class method of
an installed Java class can be used as a user-defined function anywhere a built-in function of the same data type is
used. Instance methods are tied to particular instances of a class, and so have different behavior from standard
user-defined functions.

Support for CLR stored procedures and functions is included. A CLR stored procedure or function behaves the
same as a SQL stored procedure or function except that the code for the procedure or function is written in a
Microsoft .NET language such as Microsoft C# or Microsoft Visual Basic, and the execution of the procedure or
function takes place outside the database server (that is, within a separate Microsoft .NET executable). Only
Microsoft .NET version 2.0 is supported.

Deciding whether to create a user-defined function or procedure

Functions are similar to procedures. Deciding whether to create a function or a procedure depends on what you
want returned, and the object will be called. When deciding whether to create a UDF or a procedure, consider their
unique characteristics listed below.

Functions:

● can return a single value of arbitrary type, and allow you to declare the returned type using the RETURNS
clause
● can be used in most places an expression can be used
● allow you to define only IN parameters

Procedures:

● can return multiple values using INOUT or OUT parameters


● can return result sets
● can be referenced in the FROM clause of a query, or using a CALL statement, or using a Transact-SQL
EXECUTE statement
● can be called using named parameters

Related Information

CREATE FUNCTION statement [page 840]


Named parameters [page 124]

SQL Anywhere - SQL Reference


210 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.3.1.8 Miscellaneous functions

Miscellaneous functions perform operations on arithmetic, string, or date/time expressions, including the return
values of other functions.

List of SQL Anywhere functions

The following miscellaneous functions are available:

ARGN function [Miscellaneous]


COALESCE function [Miscellaneous]
CONFLICT function [Miscellaneous]
ERRORMSG function [Miscellaneous]
ESTIMATE function [Miscellaneous]
ESTIMATE_SOURCE function [Miscellaneous]
EXPERIENCE_ESTIMATE function [Miscellaneous]
EXPLANATION function [Miscellaneous]
EXPRTYPE function [Miscellaneous]
GET_IDENTITY function [Miscellaneous]
GRAPHICAL_PLAN function [Miscellaneous]
GREATER function [Miscellaneous]
IDENTITY function [Miscellaneous]
IFNULL function [Miscellaneous]
INDEX_ESTIMATE function [Miscellaneous]
ISNULL function [Miscellaneous]
LESSER function [Miscellaneous]
NEWID function [Miscellaneous]
NULLIF function [Miscellaneous]
NUMBER function [Miscellaneous]
PLAN function [Miscellaneous]
REWRITE function [Miscellaneous]
ROW_NUMBER function [Miscellaneous]
SQLDIALECT function [Miscellaneous]
SQLFLAGGER function [Miscellaneous]
ERROR_LINE function [Miscellaneous]
TRACEBACK function [Miscellaneous]
TRANSACTSQL function [Miscellaneous]
VAREXISTS function [Miscellaneous]
WATCOMSQL function [Miscellaneous]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 211
List of UltraLite functions

The following miscellaneous functions are available:

ARGN function [Miscellaneous]


COALESCE function [Miscellaneous]
EXPLANATION function [Miscellaneous]
GREATER function [Miscellaneous]
IFNULL function [Miscellaneous]
ISNULL function [Miscellaneous]
LESSER function [Miscellaneous]
NEWID function [Miscellaneous]
NULLIF function [Miscellaneous]

1.3.1.9 Numeric functions

Numeric functions perform mathematical operations on numerical data types or return numeric information.

List of SQL Anywhere functions

The following numeric functions are available:

ABS function [Numeric]


ACOS function [Numeric]
ASIN function [Numeric]
ATAN function [Numeric]
ATAN2 function [Numeric]
CEILING function [Numeric]
COS function [Numeric]
COT function [Numeric]
DEGREES function [Numeric]
EXP function [Numeric]
FLOOR function [Numeric]
LOG function [Numeric]
LOG10 function [Numeric]
MOD function [Numeric]
PI function [Numeric]
POWER function [Numeric]
RADIANS function [Numeric]
RAND function [Numeric]
REMAINDER function [Numeric]
ROUND function [Numeric]

SQL Anywhere - SQL Reference


212 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
SIGN function [Numeric]
SIN function [Numeric]
SQRT function [Numeric]
TAN function [Numeric]
TRUNCNUM function [Numeric]

List of UltraLite functions

The following numeric functions are available:

ABS function [Numeric]


ACOS function [Numeric]
ASIN function [Numeric]
ATAN function [Numeric]
ATAN2 function [Numeric]
CEILING function [Numeric]
COS function [Numeric]
COT function [Numeric]
DEGREES function [Numeric]
EXP function [Numeric]
FLOOR function [Numeric]
LOG function [Numeric]
LOG10 function [Numeric]
MOD function [Numeric]
PI function [Numeric]
POWER function [Numeric]
RADIANS function [Numeric]
REMAINDER function [Numeric]
ROUND function [Numeric]
SIGN function [Numeric]
SIN function [Numeric]
SQRT function [Numeric]
TAN function [Numeric]
TRUNCNUM function [Numeric]

1.3.1.10 Web services functions

HTTP functions assist the handling of HTTP requests within web services. Likewise, SOAP functions assist the
handling of SOAP requests within web services.

The following functions are available:

● HTML_DECODE function [Miscellaneous]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 213
● HTML_ENCODE function [Miscellaneous]
● HTTP_BODY function [Web service]
● HTTP_DECODE function [Web service]
● HTTP_ENCODE function [Web service]
● HTTP_HEADER function [Web service]
● HTTP_RESPONSE_HEADER function [Web service]
● HTTP_VARIABLE function [Web service]
● NEXT_HTTP_HEADER function [Web service]
● NEXT_HTTP_RESPONSE_HEADER function [Web service]
● NEXT_HTTP_VARIABLE function [Web service]
● NEXT_SOAP_HEADER function [SOAP]
● SOAP_HEADER function [SOAP]

There are also system procedures available for web services.

Related Information

Web services system procedures [page 1435]


HTML_DECODE function [Miscellaneous] [page 390]
HTML_ENCODE function [Miscellaneous] [page 392]
HTTP_BODY function [Web service] [page 393]
HTTP_DECODE function [Web service] [page 394]
HTTP_ENCODE function [Web service] [page 395]
HTTP_HEADER function [Web service] [page 397]
HTTP_RESPONSE_HEADER function [Web service] [page 399]
HTTP_VARIABLE function [Web service] [page 401]
NEXT_HTTP_HEADER function [Web service] [page 454]
NEXT_HTTP_RESPONSE_HEADER function [Web service] [page 456]
NEXT_HTTP_VARIABLE function [Web service] [page 457]
NEXT_SOAP_HEADER function [SOAP] [page 459]
SOAP_HEADER function [SOAP] [page 532]

1.3.1.11 String functions

String functions perform conversion, extraction, or manipulation operations on strings, or return information
about strings.

When working in a multibyte character set, check carefully whether the function being used returns information
concerning characters or bytes.

SQL Anywhere - SQL Reference


214 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
List of SQL Anywhere functions

The following string functions are available:

ASCII function [String]


BASE64_DECODE function [String]
BASE64_ENCODE function [String]
BYTE_LENGTH function [String]
BYTE_SUBSTR function [String]
CHAR function [String]
CHARINDEX function [String]
CHAR_LENGTH function [String]
COMPARE function [String]
COMPRESS function [String]
CSCONVERT function [String]
DECOMPRESS function [String]
DECRYPT function [String]
DIFFERENCE function [String]
ENCRYPT function [String]
HASH function [String]
INSERTSTR function [String]
LCASE function [String]
LEFT function [String]
LENGTH function [String]
LOCATE function [String]
LOWER function [String]
LTRIM function [String]
NCHAR function [String]
PATINDEX function [String]
READ_CLIENT_FILE function [String]
READ_SERVER_FILE function [String]
REGEXP_SUBSTR function [String]
REPEAT function [String]
REPLACE function [String]
REPLICATE function [String]
REVERSE function [String]
RIGHT function [String]
RTRIM function [String]
SIMILAR function [String]
SORTKEY function [String]
SOUNDEX function [String]
SPACE function [String]
STR function [String]
STRING function [String]
STRTOUUID function [String]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 215
STUFF function [String]
SUBSTRING function [String]
TO_CHAR function [String]
TO_NCHAR function [String]
TRIM function [String]
UCASE function [String]
UNICODE function [String]
UNISTR function [String]
UPPER function [String]
UUIDTOSTR function [String]
XMLCONCAT function [String]
XMLELEMENT function [String]
XMLFOREST function [String]
XMLGEN function [String]

List of UltraLite functions

The following string functions are available:

ASCII function [String]


BYTE_LENGTH function [String]
BYTE_SUBSTR function [String]
CHAR function [String]
CHARINDEX function [String]
CHAR_LENGTH function [String]
DIFFERENCE function [String]
INSERTSTR function [String]
LCASE function [String]
LEFT function [String]
LENGTH function [String]
LOCATE function [String]
LOWER function [String]
LTRIM function [String]
PATINDEX function [String]
REPEAT function [String]
REPLACE function [String]
REPLICATE function [String]
RIGHT function [String]
RTRIM function [String]
SIMILAR function [String]
SOUNDEX function [String]
SPACE function [String]
STR function [String]
STRING function [String]

SQL Anywhere - SQL Reference


216 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
STRTOUUID function [String]
STUFF function [String]
SUBSTRING function [String]
TRIM function [String]
UCASE function [String]
UPPER function [String]
UUIDTOSTR function [String]

1.3.1.12 System functions

System functions return system information.

List of functions

The following system functions are available:

CONNECTION_EXTENDED_PROPERTY function [String]


CONNECTION_PROPERTY function [System]
DATALENGTH function [System]
DB_ID function [System]
DB_NAME function [System]
DB_EXTENDED_PROPERTY function [System]
DB_PROPERTY function [System]
EVENT_CONDITION function [System]
EVENT_CONDITION_NAME function [System]
EVENT_PARAMETER function [System]
NEXT_CONNECTION function [System]
NEXT_DATABASE function [System]
PROPERTY function [System]
PROPERTY_DESCRIPTION function [System]
PROPERTY_NAME function [System]
PROPERTY_NUMBER function [System]
SUSER_ID function [System]
SUSER_NAME function [System]
TSEQUAL function [System] (deprecated)
USER_ID function [System]
USER_NAME function [System]
DB_PROPERTY function [System]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 217
UltraLite functions

DB_PROPERTY function [System]


ML_GET_SERVER_NOTIFICATION function [System]
SYNC_PROFILE_OPTION_VALUE function [System]

SQL Anywhere notes

● The db_id, db_name, and datalength functions are implemented as built-in functions.
● Some system functions are implemented as stored procedures.

System functions that are not described elsewhere are noted in the following table. These functions are
implemented as stored procedures.

Syntax: COL_LENGTH

COL_LENGTH( @object_name, @column_name )

Returns the INTEGER defined length of the specified column. @object_name can contain the owner, for
example, 'GROUPO.Customers'.
Syntax: COL_TERM

COL_NAME( @object_id, @column_id [, @database_id ] )

Returns the CHAR(128) column name.


Syntax: INDEX_COL

INDEX_COL ( @table_name, @index_id, @key_# [, @user_id ] )

Returns the CHAR(128) name of the indexed column. @table_name can contain the owner, for example,
'GROUPO.Customers'.
Syntax: OBJECT_ID

OBJECT_ID( @object_name )

Returns the INTEGER object ID. @object_name can contain the owner, for example, 'GROUPO.Customers'.
Syntax: OBJECT_NAME

OBJECT_NAME ( @object_id [, @database_id ] )

Returns the CHAR(128) object name.

SQL Anywhere - SQL Reference


218 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.3.1.13 Text and image functions

Text and image functions operate on text and image data types. Only the TEXTPTR text and image function is
supported.

1.3.2 Functions

Each function is listed, and the function type (numeric, character, and so on) is indicated next to it.

In this section:

ABS function [Numeric] [page 232]


Returns the absolute value of a numeric expression.

ACOS function [Numeric] [page 233]


Returns the arc-cosine, in radians, of a numeric expression.

ARGN function [Miscellaneous] [page 234]


Returns a selected argument from a list of arguments.

ARRAY constructor [Composite] [page 235]


Returns elements of a specific data type.

ARRAY_AGG function [Aggregate] [page 238]


Creates an unbounded, single-dimensional array from the specified expression for each group where the
array element type is identical to the specified expression.

ARRAY_MAX_CARDINALITY function [Composite] [page 240]


Returns the maximal number of elements in the array.

ASCII function [String] [page 241]


Returns the integer ASCII value of the first byte in a string-expression.

ASIN function [Numeric] [page 242]


Returns the arc-sine, in radians, of a number.

ATAN function [Numeric] [page 243]


Returns the arc-tangent, in radians, of a number.

ATAN2 function [Numeric] [page 244]


Returns the arc-tangent, in radians, of the ratio of two numbers.

AVG function [Aggregate] [page 246]


Computes the average, for a set of rows, of a numeric expression or of a set of unique values.

BASE64_DECODE function [String] [page 248]


Decodes data using the MIME base64 format and returns the string as a LONG VARCHAR.

BASE64_ENCODE function [String] [page 249]


Encodes data using the MIME base64 format and returns it as a 7-bit ASCII string.

BINTOHEX function [Data type conversion] [page 250]


Returns the hexadecimal equivalent of a binary string.

BIT_AND function [Aggregate] [page 251]


Returns the bit-wise AND of the specified expression for each group of rows.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 219
BIT_LENGTH function [Bit array] [page 252]
Returns the number of bits stored in the array.

BIT_OR function [Aggregate] [page 253]


Returns the bit-wise OR of the specified expression for each group of rows.

BIT_SUBSTR function [Bit array] [page 254]


Returns a sub-array of a bit array.

BIT_XOR function [Aggregate] [page 256]


Returns the bit-wise XOR of the specified expression for each group of rows.

BYTE_INSERTSTR function [String] [page 257]


Inserts a string into another string at a position specified in bytes.

BYTE_LENGTH function [String] [page 258]


Returns the number of bytes in a string.

BYTE_LOCATE function [page 259]


Returns the position of one BYTE string within another.

BYTE_REPLACE function [page 261]


Replaces a string with another string, and returns the new results.

BYTE_STUFF function [String] [page 262]


Deletes multiple bytes from one string and replaces them with different bytes.

BYTE_SUBSTR function [String] [page 263]


Returns a substring of a string. The substring is calculated using bytes, not characters.

CARDINALITY function [Composite] [page 264]


Returns the highest number of any array element that has been assigned a value, including NULL.

CAST function [Data type conversion] [page 265]


Returns the value of an expression converted to a supplied data type.

CEILING function [Numeric] [page 269]


Returns the first integer that is greater or equal to a given value. For positive numbers, this is known as
rounding up.

CHAR function [String] [page 270]


Returns the character with the ASCII value of a number.

CHAR_LENGTH function [String] [page 271]


Returns the number of characters in a string.

CHARINDEX function [String] [page 272]


Returns the position of one string in another.

COALESCE function [Miscellaneous] [page 274]


Returns the first non-NULL expression from a list. This function is identical to the ISNULL function.

COMPARE function [String] [page 275]


Allows you to compare two character strings based on alternate collation rules.

COMPRESS function [String] [page 277]


Compresses the string and returns a value of type LONG BINARY.

CONFLICT function [Miscellaneous] [page 278]


Indicates if a column is a source of conflict for an UPDATE being performed against a consolidated
database in a SQL Remote environment.

SQL Anywhere - SQL Reference


220 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
CONNECTION_EXTENDED_PROPERTY function [String] [page 281]
Returns the value of the given property. Allows an optional property-specific string parameter to be
specified.

CONNECTION_PROPERTY function [System] [page 283]


Returns the value of a given connection property as a string.

CONVERT function [Data type conversion] [page 285]


Returns an expression converted to a supplied data type.

CORR function [Aggregate] [page 287]


Returns the correlation coefficient of a set of number pairs.

COS function [Numeric] [page 289]


Returns the cosine of the angle in radians given by its argument.

COT function [Numeric] [page 290]


Returns the cotangent of the angle in radians given by its argument.

COUNT function [Aggregate] [page 291]


Counts the number of rows in a group depending on the specified parameters.

COUNT_BIG function [Aggregate] [page 293]


Counts the number of rows in a group depending on the specified parameters.

COUNT_SET_BITS function [Bit array] [page 294]


Returns a count of the number of bits set to 1 (TRUE) in the array.

COVAR_POP function [Aggregate] [page 295]


Returns the population covariance of a set of number pairs.

COVAR_SAMP function [Aggregate] [page 297]


Returns the sample covariance of a set of number pairs.

CSCONVERT function [String] [page 298]


Converts strings between character sets.

CUME_DIST function [Ranking] [page 301]


Computes the relative position of one value among a group of rows.

DATALENGTH function [System] [page 302]


Returns the length, in bytes, of the underlying storage for the result of an expression.

DATE function [Date and time] [page 304]


Converts the expression into a date, and removes any hours, minutes, or seconds.

DATEADD function [Date and time] [page 305]


Returns a TIMESTAMP or TIMESTAMP WITH TIME ZONE value produced by adding a date part to its
argument.

DATEDIFF function [Date and time] [page 306]


Returns the interval between two dates.

DATEFORMAT function [Date and time] [page 309]


Returns a string representing a date expression in the specified format.

DATENAME function [Date and time] [page 310]


Returns the name of the specified part (such as the month June) of a TIMESTAMP or TIMESTAMP WITH
TIME ZONE value, as a character string.

DATEPART function [Date and time] [page 311]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 221
Returns a portion of a TIMESTAMP or TIMESTAMP WITH TIME ZONE value.

DATETIME function [Date and time] [page 313]


Converts an expression into a TIMESTAMP value.

DAY function [Date and time] [page 314]


Returns the day of the month of its argument as an integer between 1 and 31.

DAYNAME function [Date and time] [page 315]


Returns the name of the day of the week from a date.

DAYS function [Date and time] [page 316]


Manipulates a TIMESTAMP or returns the number of days between two TIMESTAMP values.

DB_EXTENDED_PROPERTY function [System] [page 318]


Returns the value of the given property. Allows an optional property-specific string parameter to be
specified.

DB_ID function [System] [page 323]


Returns the database ID number.

DB_NAME function [System] [page 324]


Returns the name of a database with a given ID number.

DB_PROPERTY function [System] [page 325]


Returns the value of the specified database property.

DECOMPRESS function [String] [page 327]


Decompresses the string and returns a LONG BINARY value.

DECRYPT function [String] [page 329]


Decrypts the string using the supplied key and returns a LONG BINARY value.

DEGREES function [Numeric] [page 333]


Converts a number from radians to degrees.

DENSE_RANK function [Ranking] [page 334]


Calculates the rank of a value in a partition. For tied values, the DENSE_RANK function does not leave
gaps in the ranking sequence.

DIFFERENCE function [String] [page 336]


Returns the difference in the SOUNDEX values between the two string expressions.

DOW function [Date and time] [page 337]


Returns a number from 1 to 7 representing the day of the week of a date, where Sunday=1, Monday=2, and
so on.

ENCRYPT function [String] [page 338]


Encrypts the specified value using the supplied encryption key and returns a LONG BINARY value.

ERROR_LINE function [Miscellaneous] [page 342]


Returns the line number of the procedure or batch where the error occurred that invoked the CATCH
block of a TRY...CATCH statement.

ERROR_MESSAGE function [Miscellaneous] [page 343]


Returns the message text of the error that invoked the CATCH block of a TRY...CATCH statement.

ERROR_PROCEDURE function [Miscellaneous] [page 344]


Returns the name of the procedure within which the error that caused the exception handler to run
occurred.

SQL Anywhere - SQL Reference


222 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
ERROR_SQLCODE function [Miscellaneous] [page 346]
Returns the SQLCODE of the error that invoked the error handler.

ERROR_SQLSTATE function [Miscellaneous] [page 347]


Returns the SQLSTATE of the error that invoked the error handler.

ERROR_STACK_TRACE function [Miscellaneous] [page 349]


Returns a calling sequence stack trace for the error that invoked the error handler.

ERRORMSG function [Miscellaneous] [page 351]


Provides the error message for the current error, or for a specified SQLSTATE or SQLCODE value.

ESTIMATE function [Miscellaneous] [page 352]


Returns selectivity estimates as a percentage calculated by the query optimizer, based on specified
parameters.

ESTIMATE_SOURCE function [Miscellaneous] [page 353]


Provides the source for selectivity estimates used by the query optimizer.

EVENT_CONDITION function [System] [page 355]


Specifies when an event handler is triggered.

EVENT_CONDITION_NAME function [System] [page 357]


Lists the possible parameters for EVENT_CONDITION.

EVENT_PARAMETER function [System] [page 358]


Provides context information for event handlers.

EXP function [Numeric] [page 361]


Returns the result of the base of natural logarithms e raised to the power of the given argument.

EXPERIENCE_ESTIMATE function [Miscellaneous] [page 362]


Returns selectivity estimates as a percentage calculated by the query optimizer, based on specified
parameters.

EXPLANATION function [Miscellaneous] [page 364]


Returns the optimization strategy of a SQL statement as a plain text string.

EXPRTYPE function [Miscellaneous] [page 365]


Returns a string that identifies the data type of an expression.

EXTENDED_PROPERTY function [System] [page 367]


Returns the value of the given database server property. Allows an optional property-specific string
parameter to be specified.

EXTRACT function [Date and time] [page 369]


Returns a date part from a TIMESTAMP expression.

FIRST_VALUE function [Aggregate] [page 370]


Returns values from the first row of a window.

FLOOR function [Numeric] [page 373]


Returns the largest integer not greater than the given number.

GET_BIT function [Bit array] [page 374]


Returns the value (1 or 0) of a specified bit in a bit array.

GET_IDENTITY function [Miscellaneous] [page 375]


Allocates values to an AUTOINCREMENT column. This is an alternative to using AUTOINCREMENT to
generate numbers.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 223
GETDATE function [Date and time] [page 377]
Returns the current year, month, day, hour, minute, second, and fraction of a second.

GRAPHICAL_PLAN function [Miscellaneous] [page 378]


Returns the plan optimization strategy of a SQL statement in XML format, as a string.

GREATER function [Miscellaneous] [page 380]


Returns the greater of two parameter values.

GROUPING function [Aggregate] [page 381]


Identifies whether a column in a GROUP BY operation result set is NULL because it is part of a subtotal
row, or NULL because of the underlying data.

HASH function [String] [page 382]


Returns the specified value in hashed form.

HEXTOBIN function [Data type conversion] [page 384]


Returns the LONG BINARY equivalent of a hexadecimal string.

HEXTOINT function [Data type conversion] [page 385]


Returns the decimal integer equivalent of a hexadecimal string.

HOUR function [Date and time] [page 387]


Returns the hour component of a TIMESTAMP value.

HOURS function [Date and time] [page 388]


Manipulates a TIMESTAMP or returns the number of hours between two TIMESTAMP values.

HTML_DECODE function [Miscellaneous] [page 390]


Decodes special character entities that appear in HTML literal strings.

HTML_ENCODE function [Miscellaneous] [page 392]


Encodes special characters within strings to be inserted into HTML documents.

HTTP_BODY function [Web service] [page 393]


Returns the body of the HTTP request in binary form. For example, in a POST request, this is the raw
POST data.

HTTP_DECODE function [Web service] [page 394]


Decodes HTTP encoded strings. This is also known as URL decoding.

HTTP_ENCODE function [Web service] [page 395]


Encodes strings for use with HTTP. This is also known as URL encoding.

HTTP_HEADER function [Web service] [page 397]


Returns the value of an HTTP request header.

HTTP_RESPONSE_HEADER function [Web service] [page 399]


Returns the value of an HTTP response header.

HTTP_VARIABLE function [Web service] [page 401]


Returns the value of an HTTP variable.

IDENTITY function [Miscellaneous] [page 403]


Generates integer values, starting at 1, for each successive row in a query.

IFNULL function [Miscellaneous] [page 404]


Evaluates whether one expression is NULL and returns a value.

INDEX_ESTIMATE function [Miscellaneous] [page 406]

SQL Anywhere - SQL Reference


224 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Returns selectivity estimates from the index as a percentage calculated by the query optimizer, based on
specified parameters.

INSERTSTR function [String] [page 407]


Inserts a string into another string at a specified position.

INTTOHEX function [Data type conversion] [page 408]


Returns a string containing the hexadecimal equivalent of an integer.

ISDATE function [Data type conversion] [page 409]


Tests if a string argument can be converted to a date.

ISENCRYPTED function [System] [page 411]


Determines if a string is encrypted using the ENCRYPT function and the specified key.

ISNULL function [Miscellaneous] [page 413]


Returns the first non-NULL expression from a list. This function is identical to the COALESCE function.

ISNUMERIC function [Miscellaneous] [page 414]


Determines if a string argument is a valid number.

LAST_VALUE function [Aggregate] [page 415]


Returns values from the last row of a window.

LCASE function [String] [page 417]


Converts all characters in a string to lowercase.

LEFT function [String] [page 418]


Returns multiple characters from the beginning of a string.

LENGTH function [String] [page 420]


Returns the number of characters in the specified string.

LESSER function [Miscellaneous] [page 421]


Returns the lesser of two parameter values.

LIST function [Aggregate] [page 422]


Returns a delimited list of values for every row in a group.

LOCATE function [String] [page 426]


Returns the position of one string within another.

LOG function [Numeric] [page 427]


Returns the natural logarithm of a number.

LOG10 function [Numeric] [page 429]


Returns the base 10 logarithm of a number.

LOWER function [String] [page 430]


Converts all characters in a string to lowercase.

LTRIM function [String] [page 431]


Removes leading blanks from the string.

MAX function [Aggregate] [page 432]


Returns the maximum expression value found in each group of rows.

MEDIAN function [Aggregate] [page 434]


Computes the median of a numeric expression for a set of rows.

MICROSECOND function [Date and time] [page 436]


Returns the microsecond component of a TIMESTAMP expression.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 225
MILLISECOND function [Date and time] [page 437]
Returns the millisecond component of a TIMESTAMP expression.

MIN function [Aggregate] [page 438]


Returns the minimum expression value found in each group of rows.

MINUTE function [Date and time] [page 440]


Returns the minute component of a TIMESTAMP value.

MINUTES function [Date and time] [page 441]


Manipulates a TIMESTAMP or returns the number of minute boundaries between two TIMESTAMP values.

MOD function [Numeric] [page 443]


Returns the remainder when one whole number is divided by another.

MONTH function [Date and time] [page 444]


Returns the month of the given date.

MONTHNAME function [Date and time] [page 445]


Returns the name of the month from a date.

MONTHS function [Date and time] [page 447]


Manipulates a TIMESTAMP or returns the number of month boundaries between two TIMESTAMP values.

NCHAR function [String] [page 449]


Returns an NCHAR string containing one character whose Unicode code point is given in the parameter,
or NULL if the value is not a valid code point value.

NEWID function [Miscellaneous] [page 450]


Generates a UUID (Universally Unique Identifier) value. A UUID is the same as a GUID (Globally Unique
Identifier).

NEXT_CONNECTION function [System] [page 451]


Returns an identifying number for the next connection.

NEXT_DATABASE function [System] [page 453]


Returns an identifying number for a database.

NEXT_HTTP_HEADER function [Web service] [page 454]


Returns the next HTTP header name.

NEXT_HTTP_RESPONSE_HEADER function [Web service] [page 456]


Returns the next HTTP response header name.

NEXT_HTTP_VARIABLE function [Web service] [page 457]


Returns the next HTTP variable name.

NEXT_SOAP_HEADER function [SOAP] [page 459]


Returns the next header key in a SOAP request header.

NOW function [Date and time] [page 460]


Returns the current date and time as a TIMESTAMP value. The accuracy is limited by the accuracy of the
system clock.

NULLIF function [Miscellaneous] [page 462]


Provides an abbreviated CASE expression by comparing expressions.

NUMBER function [Miscellaneous] [page 463]


Generates numbers starting at 1 for each successive row in the results of the query. The NUMBER
function is primarily intended for use in SELECT lists.

SQL Anywhere - SQL Reference


226 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
PATINDEX function [String] [page 465]
Returns an integer representing the starting position of the first occurrence of a pattern in a string.

PERCENT_RANK function [Ranking] [page 468]


For any row X, defined by the function's arguments and ORDER BY specification, the PERCENT_RANK
function determines the rank of row X - 1, divided by the number of rows in the group.

PI function [Numeric] [page 469]


Returns the numeric value PI.

PLAN function [Miscellaneous] [page 470]


Returns the long plan optimization strategy of a SQL statement, as a string.

POWER function [Numeric] [page 471]


Calculates one number raised to the power of another.

PROPERTY function [System] [page 472]


Returns the value of the specified database server property as a string.

PROPERTY_DESCRIPTION function [System] [page 474]


Returns a description of a property.

PROPERTY_IS_TRACKABLE function [System] [page 475]


Returns whether or not you can maintain historical data for the specified database server property by
storing its tracked values.

PROPERTY_NAME function [System] [page 476]


Returns the name of the property with the supplied property ID for the specified connection level.

PROPERTY_NUMBER function [System] [page 477]


Returns the property number of the property with the supplied property-name.

QUARTER function [Date and time] [page 478]


Returns a number indicating the quarter of the year from the supplied TIMESTAMP expression.

RADIANS function [Numeric] [page 479]


Converts a number from degrees to radians.

RAND function [Numeric] [page 480]


Returns a random number in the interval 0 to 1, with an optional seed.

RANK function [Ranking] [page 482]


Calculates the value of a rank in a group of values. For ties, the RANK function leaves a gap in the ranking
sequence.

READ_CLIENT_FILE function [String] [page 483]


Reads data from the specified file on the client computer.

READ_SERVER_FILE function [String] [page 485]


Reads data from the specified file on the server and returns the full or partial contents of the file as a
LONG BINARY value.

REGEXP_SUBSTR function [String] [page 487]


Extracts substrings from strings using regular expressions.

REGR_AVGX function [Aggregate] [page 489]


Computes the average of the independent variable of the regression line.

REGR_AVGY function [Aggregate] [page 490]


Computes the average of the dependent variable of the regression line.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 227
REGR_COUNT function [Aggregate] [page 492]
Returns an integer that represents the number of non-NULL number pairs used to fit the regression line.

REGR_INTERCEPT function [Aggregate] [page 493]


Computes the y-intercept of the linear regression line that best fits the dependent and independent
variables.

REGR_R2 function [Aggregate] [page 495]


Computes the coefficient of determination (also referred to as R-squared or the goodness of fit statistic)
for the regression line.

REGR_SLOPE function [Aggregate] [page 496]


Computes the slope of the linear regression line fitted to non-NULL pairs.

REGR_SXX function [Aggregate] [page 498]


Returns the sum of squares of the independent expressions used in a linear regression model. The
REGR_SXX function can be used to evaluate the statistical validity of a regression model.

REGR_SXY function [Aggregate] [page 499]


Returns the sum of products of the dependent and independent variables. The REGR_SXY function can be
used to evaluate the statistical validity of a regression model.

REGR_SYY function [Aggregate] [page 501]


Returns values that can evaluate the statistical validity of a regression model.

REMAINDER function [Numeric] [page 502]


Returns the remainder when one whole number is divided by another.

REPEAT function [String] [page 503]


Concatenates a string a specified number of times.

REPLACE function [String] [page 505]


Replaces a string with another string, and returns the new results.

REPLICATE function [String] [page 506]


Concatenates a string a specified number of times.

REVERSE function [String] [page 508]


Returns the reverse of a character expression.

REWRITE function [Miscellaneous] [page 509]


Returns a rewritten SELECT, UPDATE, or DELETE statement.

RIGHT function [String] [page 511]


Returns the rightmost characters of a string.

ROUND function [Numeric] [page 512]


Rounds the numeric-expression to the specified integer-expression amount of places after the
decimal point.

ROW constructor [Composite] [page 513]


Returns a sequence of ( field name data type, ... ) pairs named fields.

ROW_NUMBER function [Miscellaneous] [page 515]


Assigns a unique number to each row. Use this function instead of the NUMBER function.

ROWID function [Miscellaneous] [page 517]


Returns an UNSIGNED BIGINT value that uniquely identifies a row within a table.

RTRIM function [String] [page 518]

SQL Anywhere - SQL Reference


228 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Removes trailing blanks from the string.

SECOND function [Date and time] [page 520]


Returns the seconds value of the TIMESTAMP argument.

SECONDS function [Date and time] [page 521]


Manipulates a TIMESTAMP or returns the number of second boundaries between two TIMESTAMP values.

SECURE_SIGN_MESSAGE function [String] [page 523]


Digitally signs a message.

SECURE_VERIFY_MESSAGE function [String] [page 524]


Digitally verifies a message.

SET_BIT function [Bit array] [page 525]


Sets the value of a specific bit in a bit array.

SET_BITS function [Aggregate] [page 527]


Creates a bit array where specific bits, corresponding to values from a set of rows, are set to 1 (TRUE).

SIGN function [Numeric] [page 528]


Returns the sign (positive or negative) of the given number.

SIMILAR function [String] [page 529]


Returns a number indicating the similarity between two strings.

SIN function [Numeric] [page 530]


Returns the sine of a number.

SOAP_HEADER function [SOAP] [page 532]


Returns a SOAP header entry, or an attribute value for a header entry of the SOAP request.

SORTKEY function [String] [page 534]


Generates sort key values. That is, values that can be used to sort character strings based on alternate
collation rules.

SOUNDEX function [String] [page 536]


Returns a number representing the sound of a string.

SPACE function [String] [page 538]


Returns a specified number of spaces.

SQLDIALECT function [Miscellaneous] [page 539]


Returns either Watcom SQL or Transact-SQL, to indicate the SQL dialect of a statement.

SQLFLAGGER function [Miscellaneous] [page 540]


Returns the conformity of a given SQL statement to a specified standard such as the ANSI/ISO SQL
Standard.

SQRT function [Numeric] [page 541]


Returns the square root of a number.

STACK_TRACE function [Miscellaneous] [page 542]


Returns information about the stack trace for the current statement.

STDDEV function [Aggregate] [page 545]


An alias for STDDEV_SAMP.

STDDEV_POP function [Aggregate] [page 545]


Computes the standard deviation of a population consisting of a numeric-expression, as a DOUBLE.

STDDEV_SAMP function [Aggregate] [page 547]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 229
Computes the standard deviation of a sample consisting of a numeric-expression, as a DOUBLE.

STR function [String] [page 549]


Returns the string equivalent of a number.

STRING function [String] [page 550]


Concatenates one or more strings into one large string.

STRTOUUID function [String] [page 552]


Converts a string value to a unique identifier (UUID or GUID) value.

STUFF function [String] [page 553]


Deletes multiple characters from one string and replaces them with another string.

SUBSTRING function [String] [page 554]


Returns a substring of a string.

SUM function [Aggregate] [page 557]


Returns the total of the specified expression for each group of rows.

SUSER_ID function [System] [page 559]


Returns the numeric user ID for the specified user name.

SUSER_NAME function [System] [page 560]


Returns the user name for the specified user ID.

SWITCHOFFSET function [Date and time] [page 561]


Returns a TIMESTAMP WITH TIME ZONE value that is converted from its original time zone offset to the
specified time zone offset.

SYSDATETIMEOFFSET function [Date and time] [page 562]


Returns the current date, time, and time zone offset of the database server using the system clock.

TAN function [Numeric] [page 563]


Returns the tangent of a number.

TEXTPTR function [Text and image] [page 564]


Returns a 16-byte binary pointer to the specified column. This feature is provided solely for compatibility
with Transact-SQL and its use is not recommended.

TO_CHAR function [String] [page 565]


Converts character data from any supported character set into the CHAR character set for the database.

TO_NCHAR function [String] [page 567]


Converts character data from any supported character set into the NCHAR character set.

TODATETIMEOFFSET function [Date and time] [page 568]


Converts a TIMESTAMP value to a TIME STAMP WITH TIME ZONE value using the specified time zone
offset.

TODAY function [Date and time] [page 569]


Returns the current date as a DATE value.

TRACEBACK function [Miscellaneous] [page 570]


Returns statements on the stack of the most recent exception (error) that occurred during a stored
procedure, trigger, or custom function execution.

TRACED_PLAN function [Miscellaneous] (deprecated) [page 571]


The diagnostic tracing feature is deprecated. Use the SQL Anywhere Profiler to diagnose issues in your
database. This function is used by SQL Central to generate a graphical plan for a query using tracing data.

SQL Anywhere - SQL Reference


230 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
TRANSACTSQL function [Miscellaneous] [page 572]
Rewrites a Watcom SQL statement in the Transact-SQL dialect.

TREAT function [Data type conversion] [page 573]


Changes the declared type of a geometry expression to a subtype. This function is for use with spatial
data.

TRIM function [String] [page 575]


Removes leading and trailing blanks from a string.

TRIM_ARRAY function [Composite] [page 576]


Returns an implicitly bounded array that consists of a specified number of elements in an array.

TRUNCNUM function [Numeric] [page 577]


Truncates a number at a specified number of places after the decimal point.

TSEQUAL function [System] (deprecated) [page 579]


Compares two TIMESTAMP values and returns whether they are the same.

UCASE function [String] [page 580]


Converts all characters in a string to uppercase.

UNICODE function [String] [page 581]


Returns an integer containing the Unicode code point of the first character in the string, or NULL if the first
character is not a valid encoding.

UNISTR function [String] [page 582]


Converts a string containing characters and Unicode escape sequences to an NCHAR string.

UPPER function [String] [page 584]


Converts all characters in a string to uppercase.

USER_ID function [System] [page 585]


Returns the numeric user ID for the specified user name.

USER_NAME function [System] [page 586]


Returns the user name for the specified user ID.

UUIDTOSTR function [String] [page 587]


Converts a unique identifier value (UUID, also known as GUID) to a string value.

VAR_POP function [Aggregate] [page 589]


Computes the statistical variance of a population consisting of a numeric-expression, as a DOUBLE.

VAR_SAMP function [Aggregate] [page 591]


Computes the statistical variance of a sample consisting of a numeric-expression, as a DOUBLE.

VAREXISTS function [Miscellaneous] [page 593]


Returns 1 if a user-defined variable exists with the specified name. Returns 0 if no such variable exists.

VARIANCE function [Aggregate] [page 594]


An alias for VAR_SAMP.

WATCOMSQL function [Miscellaneous] [page 594]


Rewrites a Transact-SQL statement in the Watcom SQL dialect. This can be useful when converting
existing Adaptive Server Enterprise stored procedures into Watcom SQL syntax.

WEEKS function [Date and time] [page 595]


Manipulates a TIMESTAMP or returns the number of weeks between two TIMESTAMP values.

WRITE_CLIENT_FILE function [String] [page 597]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 231
Creates and writes to a file on the client computer.

XMLAGG function [Aggregate] [page 599]


Generates a forest of XML elements from a collection of XML values.

XMLCONCAT function [String] [page 600]


Produces a forest of XML elements.

XMLELEMENT function [String] [page 602]


Produces an XML element within a query.

XMLFOREST function [String] [page 604]


Generates a forest of XML elements.

XMLGEN function [String] [page 606]


Generates an XML value based on an XQuery constructor.

YEAR function [Date and time] [page 607]


Returns the year component of the TIMESTAMP argument.

YEARS function [Date and time] [page 608]


Manipulates a TIMESTAMP or returns the number of years between two TIMESTAMP values.

YMD function [Date and time] [page 610]


Returns a date value corresponding to the given year, month, and day of the month. Arguments are
INTEGER values from -32768 to 32767.

Related Information

Function types [page 201]

1.3.2.1 ABS function [Numeric]

Returns the absolute value of a numeric expression.

Syntax

ABS( numeric-expression )

Parameters

numeric-expression

The number whose absolute value is to be returned.

SQL Anywhere - SQL Reference


232 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Returns

An absolute value of the numeric expression.

Numeric-expression data type Returns

INT INT

FLOAT FLOAT

DOUBLE DOUBLE

NUMERIC NUMERIC

Standards

ANSI/ISO SQL Standard

Part of optional Language Feature T441.

Example
The following statement returns the value 66:

SELECT ABS( -66 );

1.3.2.2 ACOS function [Numeric]

Returns the arc-cosine, in radians, of a numeric expression.

Syntax

ACOS( numeric-expression )

Parameters

numeric-expression

The cosine of the angle.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 233
Returns

DOUBLE

Remarks

This function converts its argument to DOUBLE, and performs the computation in double-precision floating-point
arithmetic.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the arc-cosine value for 0.52:

SELECT ACOS( 0.52 );

Related Information

ASIN function [Numeric] [page 242]


ATAN function [Numeric] [page 243]
ATAN2 function [Numeric] [page 244]
COS function [Numeric] [page 289]

1.3.2.3 ARGN function [Miscellaneous]

Returns a selected argument from a list of arguments.

Syntax

ARGN( integer-expression, expression [ ,...] )

SQL Anywhere - SQL Reference


234 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Parameters

integer-expression

The position of an argument within the list of expressions.


expression

An expression of any data type passed into the function. All supplied expressions must be of the same data
type.

Returns

Using the value of the integer-expression as n, returns the nth argument (starting at 1) from the remaining list
of arguments.

Remarks

While the expressions can be of any data type, they must all be of the same data type. The integer expression
must be from one to the number of expressions in the list or NULL is returned. Multiple expressions are separated
by a comma.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the value 6:

SELECT ARGN( 6, 1,2,3,4,5,6 );

1.3.2.4 ARRAY constructor [Composite]

Returns elements of a specific data type.

Syntax

ARRAY(
expression [, expression ... ]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 235
| single-column-query-expression
)

Parameters

expression

An element expression in the ROW type.


single-column-query-expression

A query statement that returns a single column.

Returns

Array value

Remarks

All expressions must be union compatible.

All elements are initialized to NULL, and remain NULL until a value is explicitly or implicitly placed within a
particular array element.

An ARRAY type can contain other ARRAY or ROW values or be part of a ROW type.

The FETCH statement supports the transfer of values into an array. You can fetch values into an array for
individual expressions, for entire arrays, or for portions of arrays.

Specific values or vectors of values can be dereferenced by using double square brackets.

Standards

ANSI/ISO SQL Standard

Not in the standard.


Oracle

VARRAY can be used as a synonym of ARRAY.

Example
The following example illustrates how to construct an array:

SELECT FIRST f[[2]] FROM ( SELECT ARRAY( ID,Quantity ) FROM GROUPO.Products )

SQL Anywhere - SQL Reference


236 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
AS dt( f ) ORDER BY f[[1]] ASC;

In this example, for each row of the Products table the ARRAY constructor builds an ARRAY type with two
elements: the column ID and the value of the Quantity column, both of which are integers. The result is ordered
by the first element of the array in each row, and the result returned is the second element from the array with
the smallest first element (the Product ID of 300). You can also construct an array directly from a single-
column query expression.

The following example illustrates an alternative way of constructing an array:

SELECT * FROM GROUPO.SalesOrders S WHERE ARRAY( SELECT P.ID FROM


GROUPO.Products P JOIN GROUPO.SalesOrderItems SI ON( P.ID = SI.ProductID )AND
SI.ID = S.ID
ORDER BY P.ID )< ARRAY ( SELECT ID FROM GROUPO.Products ORDER BY ID );

In the following example, the query's SELECT list uses three arrays: one produces a GROUP BY expression, and
the MAX function uses the others. Each ARRAY type is de-referenced for a specific element before the result is
returned to the client:

SELECT FIRST ARRAY( Quantity )[[1]], MAX( ARRAY( ID,Quantity ) )[[1]],


MAX( ARRAY( name,name ))[[2]] FROM Products GROUP BY ARRAY( Quantity )
ORDER BY 1;

The following example illustrates how to use the FETCH statement to transfer values into an array:

BEGIN
DECLARE product_orders ARRAY(10) OF ARRAY OF INTEGER;
DECLARE products ARRAY(10) OF INTEGER;
DECLARE greatest_orders INTEGER = 0;
DECLARE i INTEGER = 1;
DECLARE curs CURSOR FOR
SELECT ProductID,
ARRAY_AGG( Quantity ) AS Quantities
FROM GROUPO.SalesOrderItems
GROUP BY ProductID
ORDER BY ProductID;
OPEN curs;
lp: LOOP
FETCH NEXT curs INTO products[[i]], product_orders[[i]];
IF SQLCODE <> 0 THEN LEAVE lp; END IF;
IF i = 1 THEN
SET greatest_orders = 1;
ELSE
IF CARDINALITY( product_orders[[greatest_orders]] )
< CARDINALITY( product_orders[[i]] ) THEN
SET greatest_orders = i;
END IF;
END IF;
SET i = i + 1;
END LOOP;
IF greatest_orders >= 1 THEN
SELECT * FROM GROUPO.Products WHERE ID = products[[greatest_orders]];
END IF;
END;

The following example uses the ARRAY constructor to initialize an array to a list of constants. The second
element of the day-of-the-week array is selected.

BEGIN
DECLARE @dow ARRAY( 7 ) OF CHAR(3) = ARRAY( 'Sun', 'Mon', 'Tue', 'Wed', 'Thu',
'Fri', 'Sat' );
SELECT @dow[[2]];

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 237
END

Related Information

ROW and ARRAY composite data types [page 180]


Composite functions [page 203]
Comparisons of composite types [page 192]
FETCH statement [ESQL] [SP] [page 1105]

1.3.2.5 ARRAY_AGG function [Aggregate]

Creates an unbounded, single-dimensional array from the specified expression for each group where the array
element type is identical to the specified expression.

Syntax

ARRAY_AGG( expression
[ ORDER BY order-by-expression [ ASC | DESC ], ... ] )

Parameters

expression

The expression to base the array on. The array is created with the first element having the value of the first
group from expression, the second element having the value of the second group, and so on.
order-by-expression

Determines the order of the rows returned by expression. If order-by-expression is not specified, the
order of the returned rows is not deterministic.

order-by-expression

Order the items returned by the function. There is no comma preceding this argument, which makes it easy to
use in the case where no delimiter-string is supplied.

order-by-expression cannot be an integer literal. However, it can be a variable that contains an integer
literal.

When an ORDER BY clause contains constants, they are interpreted by the optimizer and then replaced by an
equivalent ORDER BY clause. For example, the optimizer interprets ORDER BY 'a' as ORDER BY expression.

SQL Anywhere - SQL Reference


238 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
A query block containing more than one aggregate function with valid ORDER BY clauses can be executed if
the ORDER BY clauses can be logically combined into a single ORDER BY clause. For example, the following
clauses:

ORDER BY expression1, 'a', expression2

ORDER BY expression1, 'b', expression2, 'c', expression3

are subsumed by the clause:

ORDER BY expression1, expression2, expression3

Returns

ARRAY

Remarks

Array elements are filled from the input beginning with the first element.

ARRAY_AGG does not ignore NULL values in its input. NULL values are stored in the array as separate elements
like any other value. If the group is empty, the result of the ARRAY_AGG function contains a NULL element for that
group.

ARRAY_AGG cannot be used as a window function, but it can be used as an input to a window function.

The UNNEST array operator can be used to create a series of rows from an array to process each array element
with other relational expressions.

Standards

ANSI/ISO SQL Standard

Feature S098.

Example
The following statements illustrate how to generate an array that contains the list of all product colors. This
array could then be passed as a parameter to a procedure that checks whether there were any non-standard
colors in the table, for example.

CREATE VARIABLE color_list ARRAY OF LONG VARCHAR;


SELECT ARRAY_AGG(DISTINCT Color) INTO color_list FROM Products;

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 239
Related Information

UNNEST array operator [page 26]


LIST function [Aggregate] [page 422]

1.3.2.6 ARRAY_MAX_CARDINALITY function [Composite]

Returns the maximal number of elements in the array.

Syntax

ARRAY_MAX_CARDINALITY( array-expression )

Parameters

array-expression

The array expression to evaluate.

If array-expression is NULL, then ARRAY_MAX_CARDINALITY returns NULL.

Returns

INTEGER

Remarks

The cardinality of the collection is the number of elements in the collection.

For an unbounded array, ARRAY_MAX_CARDINALITY returns the maximum size limit of a supported array. For a
bounded array or an array composed via a constructor, ARRAY_MAX_CARDINALITY returns the maximum
explicitly or implicitly declared size of the array.

Standards

ANSI/ISO SQL Standard

Feature S403.

SQL Anywhere - SQL Reference


240 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Related Information

ARRAY_AGG function [Aggregate] [page 238]


CARDINALITY function [Composite] [page 264]
TRIM_ARRAY function [Composite] [page 576]

1.3.2.7 ASCII function [String]

Returns the integer ASCII value of the first byte in a string-expression.

Syntax

ASCII( string-expression )

Parameters

string-expression

The string.

Returns

SMALLINT

Remarks

If the string is empty, then ASCII returns zero. Literal strings must be enclosed in quotes. If the database
character set is multibyte and the first character of the parameter string consists of more than one byte, the
result is NULL.

Standards

ANSI/ISO SQL Standard

Not in the standard.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 241
Example
The following statement returns the value 90:

SELECT ASCII( 'Z' );

Related Information

String functions [page 214]


CHAR function [String] [page 270]

1.3.2.8 ASIN function [Numeric]

Returns the arc-sine, in radians, of a number.

Syntax

ASIN( numeric-expression )

Parameters

numeric-expression

The sine of the angle.

Returns

DOUBLE

Remarks

The SIN and ASIN functions are inverse operations.

This function converts its argument to DOUBLE, and performs the computation in double-precision floating-point
arithmetic.

SQL Anywhere - SQL Reference


242 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the arc-sine value for 0.52:

SELECT ASIN( 0.52 );

Related Information

ACOS function [Numeric] [page 233]


ATAN function [Numeric] [page 243]
ATAN2 function [Numeric] [page 244]
SIN function [Numeric] [page 530]

1.3.2.9 ATAN function [Numeric]

Returns the arc-tangent, in radians, of a number.

Syntax

ATAN( numeric-expression )

Parameters

numeric-expression

The tangent of the angle.

Returns

DOUBLE

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 243
Remarks

This function converts its argument to DOUBLE, and performs the computation in double-precision floating-point
arithmetic.

The ATAN and TAN functions are inverse operations.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the arc-tangent value for 0.52:

SELECT ATAN( 0.52 );

Related Information

ACOS function [Numeric] [page 233]


ASIN function [Numeric] [page 242]
ATAN2 function [Numeric] [page 244]
TAN function [Numeric] [page 563]

1.3.2.10 ATAN2 function [Numeric]

Returns the arc-tangent, in radians, of the ratio of two numbers.

Syntax

{ ATN2 | ATAN2 }( numeric-expression-1, numeric-expression-2 )

Parameters

numeric-expression-1

The numerator in the ratio whose arc-tangent is calculated.

SQL Anywhere - SQL Reference


244 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
numeric-expression-2

The denominator in the ratio whose arc-tangent is calculated.

Returns

DOUBLE

Remarks

This function converts its arguments to DOUBLE, and performs the computation in double-precision floating-
point arithmetic.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the arc-tangent value for the ratio 0.52 to 0.60:

SELECT ATAN2( 0.52, 0.60 );

Related Information

ACOS function [Numeric] [page 233]


ASIN function [Numeric] [page 242]
ATAN function [Numeric] [page 243]
TAN function [Numeric] [page 563]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 245
1.3.2.11 AVG function [Aggregate]

Computes the average, for a set of rows, of a numeric expression or of a set of unique values.

Syntax
Numeric expressions

AVG( [ ALL | DISTINCT ] numeric-expression )

Window function

AVG( [ ALL ] numeric-expression) OVER ( window-spec )

window-spec : see the Remarks section below

UltraLite - numeric expressions

AVG( [ DISTINCT ] numeric-expression )

Parameters

[ ALL ] numeric-expression

The expression whose average is calculated over the rows in each group.
DISTINCT clause

Computes the average of the unique numeric values in each group.

Returns

Returns the NULL value for a group containing no rows.

Returns DOUBLE if the argument is DOUBLE, otherwise NUMERIC.

Remarks

This average does not include rows where the numeric-expression is the NULL value.

This function can generate an overflow error, resulting in an error being returned. You can use the CAST function
on numeric-expression to avoid the overflow error.

Specifying this function with window-spec represents usage as a window function in a SELECT statement. As
such, elements of window-spec can be specified either in the function syntax (inline), or with a WINDOW clause
in the SELECT statement.

SQL Anywhere - SQL Reference


246 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Standards

ANSI/ISO SQL Standard

Core Feature. The numeric-expression syntax is a Core Feature of the Standard, while window-spec
syntax comprises part of optional Language Feature T611, "Basic OLAP operations". The ability to specify
DISTINCT over an expression that is not a column reference comprises part of optional Language feature
F561, "Full value expressions". The software also supports Language Feature F441, "Extended set function
support", which permits operands of aggregate functions to be arbitrary expressions possibly including outer
references to expressions in other query blocks that are not column references. The software does not
support optional Language Feature F442, "Mixed column references in set functions", and it also does not
permit the arguments of an aggregate function to include both a column reference from the query block
containing the AVG function, combined with an outer reference.

Example
The following statement returns the value 49988.623200 when connected to the SQL Anywhere 17 Demo:

SELECT AVG( Salary ) FROM Employees;

The following statement returns the average product price from the Products table when connected to the SQL
Anywhere 17 Demo database:

SELECT AVG( DISTINCT UnitPrice ) FROM Products;

The following statement returns an error with SQLSTATE 42W68 because the arguments of AVG contain both
a quantified expression from the subquery, and an outer reference (p.Quantity) from the outer SELECT block
when connected to the SQL Anywhere 17 Demo:

SELECT * from GROUPO.Products as p


WHERE p.Quantity > ( SELECT AVG( 0.5 * p.Quantity + 0.5 * s.Quantity )
from GROUPO.SalesOrderItems as s
WHERE s.ProductID = p.ProductID )

Related Information

CAST function [Data type conversion] [page 265]


SUM function [Aggregate] [page 557]
COUNT function [Aggregate] [page 291]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 247
1.3.2.12 BASE64_DECODE function [String]

Decodes data using the MIME base64 format and returns the string as a LONG VARCHAR.

Syntax

BASE64_DECODE( string-expression )

Parameters

string-expression

The string that is to be decoded. The string must be base64-encoded.

Returns

LONG VARCHAR

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following inserts an image into an image table from an Embedded SQL program. The input data (host
variable) must be base64 encoded:

EXEC SQL INSERT INTO images ( image_data ) VALUES ( BASE64_DECODE ( :img ) );

Related Information

String functions [page 214]


BASE64_ENCODE function [String] [page 249]

SQL Anywhere - SQL Reference


248 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.3.2.13 BASE64_ENCODE function [String]

Encodes data using the MIME base64 format and returns it as a 7-bit ASCII string.

Syntax

BASE64_ENCODE( string-expression )

Parameters

string-expression

The string that is to be encoded.

Returns

LONG VARCHAR

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following retrieves data from a fictitious table containing images and returns it in ASCII format. The
resulting string can be embedded into an email message, and then decoded by the recipient to retrieve the
original image.

SELECT BASE64_ENCODE( image_data ) FROM IMAGES;

Related Information

String functions [page 214]


BASE64_DECODE function [String] [page 248]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 249
1.3.2.14 BINTOHEX function [Data type conversion]

Returns the hexadecimal equivalent of a binary string.

Syntax

BINTOHEX( binary-expression )

Parameters

binary-expression

The binary string to be converted to a hexadecimal string.

Returns

The BINTOHEX function returns a LONG VARCHAR string. The length of the result is twice the length of the input
string.

Remarks

The CAST, CONVERT, BINTOHEX, HEXTOBIN, HEXTOINT, and INTTOHEX functions can be used to convert to
and from hexadecimal values.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns a string containing 313233:

SELECT BINTOHEX(0x313233);

SQL Anywhere - SQL Reference


250 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Related Information

Converting to and from hexadecimal values [page 12]


HEXTOBIN function [Data type conversion] [page 384]

1.3.2.15 BIT_AND function [Aggregate]

Returns the bit-wise AND of the specified expression for each group of rows.

Syntax

BIT_AND( bit-expression )

Parameters

bit-expression

The object to be aggregated. The expression can be a VARBIT array, a BINARY value, or an INTEGER
(including all integer variants such as BIT and TINYINT).

Returns

The same data type as the argument. For each bit position compared, if every row has a 1 in the bit position, return
1; otherwise, return 0.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following example generates four rows containing a CHAR column, then converts the values to VARBIT:

SELECT BIT_AND( CAST( row_value AS VARBIT ) )


FROM dbo.sa_split_list( '0001,0111,0100,0011' );

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 251
The result 0000 is determined as follows:

1. A bitwise AND is performed between row 1 (0001) and row 2 (0111), resulting in 0001 (both values had a 1
in the fourth bit).
2. A bitwise AND is performed between the result from the previous comparison (0001) and row 3 (0100),
resulting in 0000 (neither value had a 1 in the same bit).
3. A bitwise AND is performed between the result from the previous comparison (0000) and row 4 (0011),
resulting in 0000 (neither value had a 1 in the same bit).

Related Information

BIT_OR function [Aggregate] [page 253]


BIT_XOR function [Aggregate] [page 256]
Bitwise operators [page 31]

1.3.2.16 BIT_LENGTH function [Bit array]

Returns the number of bits stored in the array.

Syntax

BIT_LENGTH( bit-expression )

Parameters

bit-expression

The bit expression for which the length is to be determined.

Returns

INT

Standards

ANSI/ISO SQL Standard

SQL Anywhere - SQL Reference


252 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Not in the standard.

Example
The following statement returns the value 8:

SELECT BIT_LENGTH( '01101011' );

Related Information

CHAR_LENGTH function [String] [page 271]

1.3.2.17 BIT_OR function [Aggregate]

Returns the bit-wise OR of the specified expression for each group of rows.

Syntax

BIT_OR( bit-expression )

Parameters

bit-expression

The object to be aggregated. The expression can be a VARBIT array, a BINARY value, or an INTEGER
(including all integer variants such as BIT and TINYINT).

Returns

The same data type as the argument. For each bit position compared, if any row has a 1 in the bit position, this
function returns 1; otherwise, it returns 0.

Standards

ANSI/ISO SQL Standard

Not in the standard.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 253
Example
The following example generates four rows containing a CHAR column, then converts the values to VARBIT:

SELECT BIT_OR( CAST( row_value AS VARBIT ) )


FROM dbo.sa_split_list( '0001,0111,0100,0011' );

The result 0111 is determined as follows:

1. A bitwise OR is performed between row 1 (0001) and row 2 (0111), resulting in 0111.
2. A bitwise OR is performed between the result from the previous comparison (0111) and row 3 (0100),
resulting in 0111.
3. A bitwise OR is performed between the result from the previous comparison (0111) and row 4 (0011),
resulting in 0111.

Related Information

BIT_AND function [Aggregate] [page 251]


BIT_XOR function [Aggregate] [page 256]
Bitwise operators [page 31]

1.3.2.18 BIT_SUBSTR function [Bit array]

Returns a sub-array of a bit array.

Syntax

BIT_SUBSTR( bit-expression [, start [, length ] ])

Parameters

bit-expression

The bit array from which the sub-array is to be extracted.


start

The start position of the sub-array to return. A negative starting position specifies the number of bits from the
end of the array instead of the beginning. The first bit in the array is at position 1.
length

The length of the sub-array to return. A positive length specifies that the sub-array ends length bits to the
right of the starting position, while a negative length returns, at most, length bits up to, and including, the
starting position, from the left of the starting position.

SQL Anywhere - SQL Reference


254 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Returns

LONG VARBIT

Remarks

Both start and length can be either positive or negative. Using appropriate combinations of negative and
positive numbers, you can get a sub-array from either the beginning or end of the string. Using a negative number
for length does not impact the order of the bits returned in the sub-array.

If length is specified, the sub-array is restricted to that length. If start is zero and length is non-negative, a
start value of 1 is used. If start is zero and length is negative, a start value of -1 is used.

If length is not specified, selection continues to the end of the array.

The BIT_SUBSTR function is equivalent to, but faster than, the following:

CAST( SUBSTR( CAST( bit-expression AS VARCHAR ),


start [, length ] )
AS VARBIT );

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns 1101:

SELECT BIT_SUBSTR( '001101', 3 );

The following statement returns 10110:

SELECT BIT_SUBSTR( '01011011101111011111', 2, 5 );

The following statement returns 11111:

SELECT BIT_SUBSTR( '01011011101111011111', -5, 5 );

Related Information

SUBSTRING function [String] [page 554]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 255
1.3.2.19 BIT_XOR function [Aggregate]

Returns the bit-wise XOR of the specified expression for each group of rows.

Syntax

BIT_XOR( bit-expression )

Parameters

bit-expression

The object to be aggregated. The expression can be a VARBIT array, a BINARY value, or an INTEGER
(including all integer variants such as BIT and TINYINT).

Returns

The same data type as the argument. For each bit position compared, if an odd number of rows have a 1 in the bit
position, return 1; otherwise, return 0.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following example generates four rows containing a CHAR column, then converts the values to VARBIT:

SELECT BIT_XOR( CAST( row_value AS VARBIT ) )


FROM dbo.sa_split_list( '0001,0111,0100,0011' );

The result 0001 is determined as follows:

1. A bitwise exclusive OR (XOR) is performed between row 1 (0001) and row 2 (0111), resulting in 0110.
2. A bitwise XOR is performed between the result from the previous comparison (0110) and row 3 (0100),
resulting in 0010.
3. A bitwise XOR is performed between the result from the previous comparison (0010) and row 4 (0011),
resulting in 0001.

SQL Anywhere - SQL Reference


256 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Related Information

BIT_AND function [Aggregate] [page 251]


BIT_OR function [Aggregate] [page 253]
Bitwise operators [page 31]

1.3.2.20 BYTE_INSERTSTR function [String]

Inserts a string into another string at a position specified in bytes.

Syntax

BYTE_INSERTSTR( insert-position, source-string, insert-string )

Parameters

insert-position

The byte position after which insert-string is to be inserted. The first byte in the string is position 0.
source-string

The string into which insert-string is to be inserted. source-string can be any length.
insert-string

The string to be inserted.

Returns

LONG BINARY

Remarks

The arguments source-string and insert-string are treated as binary strings.

Standards

ANSI/ISO SQL Standard

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 257
Not in the standard.

Example
The following statement inserts the string 123456 starting at the 5th byte position, and returns the value
0xfedcba9876123456543210:

SELECT BYTE_INSERTSTR(5,0xfedcba9876543210,0x123456);

1.3.2.21 BYTE_LENGTH function [String]

Returns the number of bytes in a string.

Syntax

BYTE_LENGTH( string-expression )

Parameters

string-expression

The string whose length is to be calculated.

Returns

INT

Remarks

Trailing white space characters in the string-expression are included in the length returned.

The return value of a NULL string is NULL.

If the string is in a multibyte character set, the BYTE_LENGTH value may differ from the number of characters
returned by CHAR_LENGTH.

This function supports NCHAR inputs and/or outputs.

UltraLite: UltraLite does not support NCHAR inputs and/or outputs.

SQL Anywhere - SQL Reference


258 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Standards

ANSI/ISO SQL Standard

Not in the standard. The equivalent function is the OCTET_LENGTH function.

Example
The following statement returns the value 12:

SELECT BYTE_LENGTH( 'Test Message' );

Related Information

String functions [page 214]


CHAR_LENGTH function [String] [page 271]
DATALENGTH function [System] [page 302]
LENGTH function [String] [page 420]

1.3.2.22 BYTE_LOCATE function

Returns the position of one BYTE string within another.

Syntax

BYTE_LOCATE( source-string, search-string [, start-position ] )

Parameters

source-string The string to be searched.


search-string

The string to be searched for.


start-position

The byte position in the string to begin the search. The first byte is position 1. If the starting offset is negative,
then the BYTE_LOCATE function returns the last matching string offset rather than the first, as counted from
the end of the string. A negative offset indicates how much of the end of the string is to be excluded from the
search. The number of bytes excluded is calculated as (-1 * offset) -1.

Although start-position acts as an offset for where the search is started, the return value still reflects the
actual starting position of the matching string, regardless of where the search was started.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 259
Returns

INTEGER

Remarks

If start-position is specified, then the search starts at that offset into the string.

source-string can be any length, but search-string is limited to 255 bytes. If search-string is longer than
255 bytes, then the function returns a NULL value. If search-string is not found, then 0 is returned. Searching
for a zero-length search-string returns 1. If any of the arguments are NULL, then the result is NULL.

source-string and search-string can be any data type that can be converted to a binary data type; binary
comparisons are used.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
When start-position is any positive number from 0 to 8 inclusive, the following statement returns 8,
indicating that the first matching byte in the string is at position 8. If start-position is greater than 8, then
the example returns 0 because the string 'party' is not found after position 8.

SELECT BYTE_LOCATE(
'office party this week - rsvp as soon as possible',
'party',
2 );

When start-position is any number from 0 to -38 inclusive, the following statement returns 8. Any number
lower than -38 returns 0. This indicates that the first matching byte in the string is at position 8, and indicates
that the position of the last matching byte (the 'y' in 'party') is in position 38 as counted backwards from the
end of the string.

SELECT BYTE_LOCATE(
'office party this week - rsvp as soon as possible',
'party',
-38 );

SQL Anywhere - SQL Reference


260 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.3.2.23 BYTE_REPLACE function

Replaces a string with another string, and returns the new results.

Syntax

BYTE_REPLACE( source-string, search-string, replace-string )

Parameters

source-string

The string to be searched.


search-string

The string to be searched for and replaced by replace-string. search-string is limited to 255 bytes. If
search-string is an empty string, then source-string is returned unchanged.
replace-string

The string that replaces all instances of search-string. If replacement-string is an empty string, then
all occurrences of search-string are deleted.

Returns

LONG BINARY

Remarks

All instances of search-string are replaced with replace-string.

source-string, search-string, and replace-string can be any data type that can be converted to a binary
data type; binary comparisons are used.

Standards

ANSI/ISO SQL Standard

Not in the standard.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 261
Example
The following statement returns the value xx.def.xx.ghi:

SELECT BYTE_REPLACE( 'abc.def.abc.ghi', 'abc', 'xx' );

1.3.2.24 BYTE_STUFF function [String]

Deletes multiple bytes from one string and replaces them with different bytes.

Syntax

BYTE_STUFF( source-string, start-position, length, insert-string )

Parameters

source-string

The byte string to be modified by the BYTE_STUFF function. source-string can be any length.
start-position

The byte position at which to begin deleting characters. The first byte in the string is position 1.
length

The number of bytes to delete.


insert-string

The string to be inserted. To delete a portion of a string using the BYTE_STUFF function, use a NULL
replacement string.

Returns

LONG BINARY

Remarks

The arguments source-string and insert-string can be any data type that can be converted to a binary
data type, and are treated as binary strings.

SQL Anywhere - SQL Reference


262 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement inserts the string 123456 starting at the 5th byte position, and returns the value
0xfedcba9876123456543210:

SELECT BYTE_STUFF(0xfedcba9876543210, 6, 0, 0x123456);

1.3.2.25 BYTE_SUBSTR function [String]

Returns a substring of a string. The substring is calculated using bytes, not characters.

Syntax

BYTE_SUBSTR( source-string, start-position [, length ] )

Parameters

source-string

The string from which the substring is taken. source-string can be any length.
start-position

An integer expression indicating the start of the substring. A positive integer starts from the beginning of the
string, with the first character being position 1. A negative integer specifies a substring starting from the end
of the string, the final character being at position -1.
length

An integer expression indicating the length of the substring. A positive length specifies the number of bytes
to be taken starting at the start position. A negative length returns at most length bytes up to, and
including, the starting position, from the left of the starting position.

Returns

BINARY or LONG BINARY, depending on the input.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 263
Remarks

If length is specified, then the substring is restricted to that number of bytes. Both start-position and
length can be either positive or negative. Use appropriate combinations of negative and positive numbers, to get
a substring from either the beginning or end of the string.

If start-position is zero and length is non-negative, then a start-position value of 1 is used. If start-
position is zero and length is negative, then a start value of -1 is used.

The argument source-string can be any data type that can be converted to a binary data type, and is treated
as a binary string. The substring is calculated using bytes, not characters.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the value Test:

SELECT BYTE_SUBSTR( 'Test Message', 1, 4 );

Related Information

String functions [page 214]


SUBSTRING function [String] [page 554]

1.3.2.26 CARDINALITY function [Composite]

Returns the highest number of any array element that has been assigned a value, including NULL.

Syntax

CARDINALITY( array-expression )

Parameters

array-expression

SQL Anywhere - SQL Reference


264 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
The array expression on which the cardinality is calculated.

If array-expression is NULL, then CARDINALITY returns NULL.

Returns

INTEGER

Remarks

The cardinality of the collection is the number of elements in the collection.

The result is an integer between zero and the maximum size of the array.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following example returns the value 4:

SELECT CARDINALITY( ARRAY( 3,4 ) || ARRAY( 5,6 ) );

Related Information

ARRAY_AGG function [Aggregate] [page 238]


ARRAY_MAX_CARDINALITY function [Composite] [page 240]
TRIM_ARRAY function [Composite] [page 576]

1.3.2.27 CAST function [Data type conversion]

Returns the value of an expression converted to a supplied data type.

Syntax

CAST( expression AS datatype )

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 265
Parameters

expression

The expression to be converted.


datatype

The data type to cast the expression into. Set the data type explicitly, or specify the %TYPE attribute to set
the data type to the data type of a column in a table or view, or to the data type of a variable.

Returns

Depends on the data type requested.

Remarks

If you use the CAST function to truncate strings, then the string_rtruncation database option must be set to OFF;
otherwise, there will be an error. Use the LEFT function to truncate strings.

If you do not indicate a length for character string types, then an appropriate length is chosen. If neither precision
nor scale is specified for a DECIMAL conversion, then the database server selects appropriate values.

UltraLite: It is recommended that you explicitly indicate the precision and scale in your CAST function. The ability
to convert depends on the value used in the conversion. The values in the original data type must be compatible
with the new data type to avoid generating a conversion error. Use the following chart to determine whether a
conversion is supported:

SQL Anywhere - SQL Reference


266 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Symbol Compatibility

Always converts

Never converts

Value-dependent

Note
In UltraLite:

● To convert between a VARBINARY and a UNIQUEIDENTIFIER, the VARBINARY value must have a 16 byte
length.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 267
● To convert between a NUMERIC and a VARBINARY, the NUMERIC source must have a value that can also
be cast as a BIGINT.
● To convert from a VARCHAR to an ST_GEOMETRY, the VARCHAR source must represent a valid geometry
in either WKT or EWKT format.
● To convert from a VARBINARY to an ST_GEOMETRY, the VARBINARY source must represent a valid
geometry in WKB format.
● When casting from a WKB or WKT formatted source to an ST_GEOMETRY, an SRID of 0 is assigned to the
ST_GEOMETRY value. When casting from an ST_GEOMETRY, VARCHAR values are formatted in EWKT
and VARBINARY values are formatted in WKB.

The HEXTOINT and INTTOHEX functions can be used to convert to and from hexadecimal values.

Standards

ANSI/ISO SQL Standard

Core Feature. However, in the software, CAST supports a number of data type conversions that are not
permitted by the ANSI/ISO SQL Standard. For example, you can CAST an integer value to a DATE type,
whereas in the ANSI/ISO SQL Standard this type of conversion is not permitted.

Example
The following function ensures a string is used as a date:

SELECT CAST( '2000-10-31' AS DATE );

The value of the expression 1 + 2 is calculated, and the result is then cast into a single-character string.

SELECT CAST( 1 + 2 AS CHAR );

Casting between VARCHAR and ST_GEOMETRY is usually implicit. For example, the following statement adds
values to ST_GEOMETRY columns using the ST_POINT function and a VARCHAR. Each value is implicitly cast
to an ST_GEOMETRY data type consistent with the table columns, but results still appear as VARCHAR.

INSERT INTO T1 VALUES (2, ST_POINT(1,2,0), 'SRID=2163;Point(1 2)');

The following statement casts a value to the data type defined for the BirthDate column (DATE data type) of
the Employees table:

SELECT CAST ( '1966-10-30' AS Employees.BirthDate%TYPE );

UltraLite: You can use the CAST function to shorten strings:

SELECT CAST ( 'Surname' AS CHAR(5) );

SQL Anywhere - SQL Reference


268 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Related Information

Data type conversions [page 194]


Converting to and from hexadecimal values [page 12]
CONVERT function [Data type conversion] [page 285]
LEFT function [String] [page 418]

1.3.2.28 CEILING function [Numeric]

Returns the first integer that is greater or equal to a given value. For positive numbers, this is known as rounding
up.

Syntax

{ CEILING | CEIL } ( numeric-expression )

Parameters

numeric-expression

The number whose ceiling is to be calculated.

Returns

DOUBLE

Remarks

This function converts its argument to DOUBLE, and performs the computation in double-precision floating-point
arithmetic.

Standards

ANSI/ISO SQL Standard

The CEILING function comprises part of optional ANSI/ISO SQL Language Feature T621, "Enhanced numeric
functions".

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 269
Example
The following statement returns the value 60:

SELECT CEILING( 59.84567 );

Related Information

FLOOR function [Numeric] [page 373]

1.3.2.29 CHAR function [String]

Returns the character with the ASCII value of a number.

Syntax

CHAR( integer-expression )

Parameters

integer-expression

The number to be converted to an ASCII character. The number must be in the range 0 to 255, inclusive.

Returns

VARCHAR

Remarks

The character returned corresponds to the supplied numeric expression in the current database character set,
according to a binary sort order.

CHAR returns NULL for integer expressions with values greater than 255 or less than zero.

SQL Anywhere - SQL Reference


270 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the value Y:

SELECT CHAR( 89 );

Related Information

String functions [page 214]

1.3.2.30 CHAR_LENGTH function [String]

Returns the number of characters in a string.

Syntax

CHAR_LENGTH ( string-expression )

Parameters

string-expression

The string whose length is to be calculated.

Returns

INT

Remarks

Trailing white space characters are included in the length returned.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 271
The return value of a NULL string is NULL.

If the string is in a multibyte character set, the value returned by the CHAR_LENGTH function may differ from the
number of bytes returned by the BYTE_LENGTH function.

You can use the CHAR_LENGTH function and the LENGTH function interchangeably for CHAR, VARCHAR, LONG
VARCHAR, and NCHAR data types. However, you must use the LENGTH function for BINARY and bit array data
types. This function supports NCHAR inputs and/or outputs.

UltraLite: You can use the CHAR_LENGTH function and the LENGTH function interchangeably for CHAR,
VARCHAR and LONG VARCHAR data types. However, you must use the LENGTH function for BINARY and bit
array data types.

Standards

ANSI/ISO SQL Standard

CHAR_LENGTH is a Core Feature. Using CHAR_LENGTH over an expression of type NCHAR comprises part of
optional ANSI/ISO SQL Language Feature F421.

Example
The following statement returns the value 8:

SELECT CHAR_LENGTH( 'Chemical' );

Related Information

String functions [page 214]


BYTE_LENGTH function [String] [page 258]

1.3.2.31 CHARINDEX function [String]

Returns the position of one string in another.

Syntax

CHARINDEX( string-expression-1, string-expression-2 )

SQL Anywhere - SQL Reference


272 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Parameters

string-expression-1

The string for which you are searching. The value must be less than 256 bytes.
string-expression-2

The string to be searched.

Returns

INT

Remarks

The first character of string-expression-1 is identified as 1. If the string being searched contains more than
one instance of the other string, then the CHARINDEX function returns the position of the first instance.

If the string being searched does not contain the other string, then the CHARINDEX function returns 0.

If any of the arguments are NULL, the result is NULL.

This function supports NCHAR inputs and/or outputs.

UltraLite does not support NCHAR inputs or outputs.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns last and first names from the Surname and GivenName columns of the
Employees table, but only when the last name begins with the letter K:

SELECT Surname, GivenName


FROM GROUPO.Employees
WHERE CHARINDEX( 'K', Surname ) = 1;

The following results are returned:

Surname GivenName

Klobucher James

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 273
Surname GivenName

Kuo Felicia

Kelly Moira

Related Information

String functions [page 214]


SUBSTRING function [String] [page 554]
REPLACE function [String] [page 505]
LOCATE function [String] [page 426]

1.3.2.32 COALESCE function [Miscellaneous]

Returns the first non-NULL expression from a list. This function is identical to the ISNULL function.

Syntax

COALESCE( expression, expression [ ,...] )

Parameters

expression

Any expression.

At least two expressions must be passed into the function, and all expressions must be comparable.

Returns

The return type for this function depends on the expressions specified. That is, when the database server
evaluates the function, it first searches for a data type in which all the expressions can be compared. When found,
the database server compares the expressions and then returns the first non-NULL expression from the list. If the
database server cannot find a common comparison type, then an error is returned.

SQL Anywhere - SQL Reference


274 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Remarks

The result is NULL only if all the arguments are NULL.

The parameters can be of any scalar type, but not necessarily same type.

Standards

ANSI/ISO SQL Standard

Core Feature.

Example
The following statement returns the value 34:

SELECT COALESCE( NULL, 34, 13, 0 );

Related Information

ISNULL function [Miscellaneous] [page 413]

1.3.2.33 COMPARE function [String]

Allows you to compare two character strings based on alternate collation rules.

Syntax

COMPARE(
string-expression-1,
string-expression-2
[, { collation-id | collation-name[(collation-tailoring-string) ] } ]
)

Parameters

string-expression-1

The first string expression.


string-expression-2

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 275
The second string expression.

The string expression can only contain characters that are encoded in the database's character set.
collation-id

A variable or integer constant that specifies the sort order to use. You can only use a collation-id for built-
in collations.

If you do not specify a collation name or ID, the default is Default Unicode multilingual.
collation-name

A string or a character variable that specifies the name of the collation to use. You can also specify
char_collation or db_collation (for example, COMPARE( 'abc', 'ABC', 'char_collation' );) to use
the database's CHAR collation. Similarly, you can specify nchar_collation to use the database's NCHAR
collation.
collation-tailoring-string

Optionally, you can specify collation tailoring options (collation-tailoring-string) for additional
control over the character comparison. These options take the form of keyword=value pairs in parentheses,
following the collation name. For example, 'UCA(locale=es;case=LowerFirst;accent=respect)'. The
syntax for specifying these options is identical to the syntax defined for the COLLATION clause of the CREATE
DATABASE statement.

Note
All the collation tailoring options are supported when specifying the UCA collation. For all other collations,
only case sensitivity tailoring option is supported.

Returns

An INTEGER, based on the collation rules that you choose:

Value Meaning

1 string-expression-1 is greater than string-


expression-2

0 string-expression-1 is equal to string-expression-2

-1 string-expression-1 is less than string-expression-2

Remarks

The COMPARE function does not equate empty strings and strings containing only spaces, even if the database
has blank-padding enabled. The COMPARE function uses the SORTKEY function to generate collation keys for
comparison. Therefore, an empty string, a string with one space, and a string with two spaces do not compare
equally.

If either string-expression-1 or string-expression-2 is NULL, the result is NULL.

SQL Anywhere - SQL Reference


276 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following example performs three comparisons using the COMPARE function:

SELECT COMPARE( 'abc','ABC','UCA(case=LowerFirst)' ),


COMPARE( 'abc','ABC','UCA(case=Ignore)' ),
COMPARE( 'abc','ABC','UCA(case=UpperFirst)' );

The values returned are -1, 0, 1, indicating the result of each comparison. The first comparison results in -1,
indicating that string-expression-2 ('ABC') is less than string-expression-1 ('abc'). This is because
case sensitivity is set to LowerFirst in the first COMPARE statement.

Related Information

String functions [page 214]


SORTKEY function [String] [page 534]

1.3.2.34 COMPRESS function [String]

Compresses the string and returns a value of type LONG BINARY.

Syntax

COMPRESS( string-expression [ , compression-algorithm-alias ] )

Parameters

string-expression

The string to be compressed. Binary values can be passed to this function. This parameter is case sensitive,
even in case-insensitive databases.
compression-algorithm-alias

Alias for the algorithm to use for compression. The supported values are zip and gzip (both are based on the
same algorithm, but use different headers and trailers). Zip is a widely supported compression algorithm.
Gzip is compatible with the gzip utility on Unix, whereas the zip algorithm is not.

Decompression must be performed with the same algorithm.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 277
Returns

LONG BINARY

Remarks

The value returned by the COMPRESS is not human-readable. If the value returned is longer than the original
string, its maximum size will not be larger than a 0.1% increase over the original string + 12 bytes. You can
decompress a compressed string-expression using the DECOMPRESS function.

If you are storing compressed values in a table, the column should be BINARY or LONG BINARY so that character
set conversion is not performed on the data.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following example returns the length of the binary string created by compressing the string 'Hello World'
using the gzip algorithm. This example can be useful when you want to determine whether a value has a shorter
length when compressed.

SELECT LENGTH( COMPRESS( 'Hello world', 'gzip' ) );

Related Information

String functions [page 214]


DECOMPRESS function [String] [page 327]

1.3.2.35 CONFLICT function [Miscellaneous]

Indicates if a column is a source of conflict for an UPDATE being performed against a consolidated database in a
SQL Remote environment.

Syntax

CONFLICT( column-name )

SQL Anywhere - SQL Reference


278 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Parameters

column-name

The name of the column being tested for conflicts.

Returns

Returns TRUE if the column appears in the VERIFY list of an UPDATE statement executed by the SQL Remote
Message Agent and if the value provided in the VALUES list of that statement does not match the original value of
the column in the row being updated. Otherwise, returns FALSE.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The CONFLICT function is intended for use in SQL Remote RESOLVE UPDATE triggers to avoid error
messages. To illustrate the use of the CONFLICT function, consider the following table:

CREATE TABLE Admin (


PKey bigint NOT NULL DEFAULT GLOBAL AUTOINCREMENT,
TextCol CHAR(20) NULL, PRIMARY KEY ( PKey ) );

Assume that consolidated and remote databases both have the following row in the Admin table:

1, 'Initial'

Now, at the consolidated database, update the row as follows:

UPDATE Admin SET TextCol = 'Consolidated Update' WHERE PKey = 1;

At the remote database, update the row to a different value as follows:

UPDATE Admin SET TextCol = 'Remote Update' WHERE PKey = 1;

Next, run dbremote on the remote database. It generates a message file with the following statements in it, to
be executed at the consolidated database:

UPDATE Admin SET TextCol='Remote Update'


VERIFY ( TextCol )
VALUES ( 'Initial' )
WHERE PKey=1;

When the SQL Remote Message Agent runs at the consolidated database and applies this UPDATE statement,
SQL Anywhere uses the VERIFY and VALUES clause to determine whether a RESOLVE UPDATE trigger will fire.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 279
A RESOLVE UPDATE trigger fires only when the update is executed from the SQL Remote Message Agent
against a consolidated database. Here is a RESOLVE UPDATE trigger:

CREATE TRIGGER ResolveUpdateAdmin


RESOLVE UPDATE ON Admin
REFERENCING OLD AS OldConsolidated
NEW AS NewRemote
REMOTE as OldRemote
FOR EACH ROW BEGIN
MESSAGE 'OLD';
MESSAGE OldConsolidated.PKey || ',' || OldConsolidated.TextCol;
MESSAGE 'NEW';
MESSAGE NewRemote.PKey || ',' || NewRemote.TextCol;
MESSAGE 'REMOTE';
MESSAGE OldRemote.PKey || ',' || OldRemote.TextCol;
END;

The RESOLVE UPDATE trigger fires because the current value of the TextCol column at the consolidated
database ('Consolidated Update') does not match the value in the VALUES clause for the associated
column ('Initial').

This trigger results in a failure because the PKey column was not modified in the UPDATE statement executed
on the remote, so there is no OldRemote.PKey value accessible from this trigger.

The CONFLICT function helps to avoid this error by returning the following values:

● If there is no OldRemote.PKey value, return FALSE.


● If there is an OldRemote.PKey value, but it matches OldConsolidated.PKey, return FALSE.
● If there is an OldRemote.PKey value, and it is different than OldConsolidated.PKey, return TRUE.

You can use the CONFLICT function to rewrite the trigger as follows and avoid the error:

CREATE TRIGGER ResolveUpdateAdmin


RESOLVE UPDATE ON Admin
REFERENCING OLD AS OldConsolidated
NEW AS NewRemote
REMOTE as OldRemote
FOR EACH ROW BEGIN
message 'OLD';
message OldConsolidated.PKey || ',' || OldConsolidated.TextCol;
message 'NEW';
message NewRemote.PKey || ',' || NewRemote.TextCol;
message 'REMOTE';
if CONFLICT( PKey ) then
message OldRemote.PKey;
end if;
if CONFLICT( TextCol ) then
message OldRemote.TextCol;
end if;
END;

Related Information

CREATE TRIGGER statement [page 985]

SQL Anywhere - SQL Reference


280 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.3.2.36 CONNECTION_EXTENDED_PROPERTY function
[String]
Returns the value of the given property. Allows an optional property-specific string parameter to be specified.

Syntax

CONNECTION_EXTENDED_PROPERTY(
{ property-id | property-name }
[, property-specific-argument [, connection-id ] ]
)

Parameters

property-id

The connection property ID.


property-name

The connection property name. The supported property names are:

CharSet

Returns the CHAR character set label for the connection as it is known by the specified standard. The
possible values include: ASE, IANA, MIME, JAVA, WINDOWS, UTR22, IBM, and ICU. The default is IANA
unless the database connection was made through TDS in which case ASE is the default.
NcharCharSet

Returns the NCHAR character set label for the connection as it is known by the specified standard. The
possible values are the same as listed above for CharSet.
HasSecuredFeature Returns Yes if at least one of the features in the property-specific-argument
argument is secured for the connection, otherwise returns No. Returns NULL if property-specific-
argument is NULL.
Progress

Returns information about how long a statement has been executing. Specify a property-specific-
argument, followed by connection-id, to return information specific to the statement's progress.
property-specific-argument

An optional property-specific string parameter associated with the following connection property:

HasSecuredFeature feature-list

Specify a list of features to determine whether at least one of these features is secured.
Progress

PercentComplete

Specify PercentComplete to obtain the percentage of the statement that has been processed.
Completed

Specify Completed to obtain the completed number of units.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 281
Total

Specify Total to obtain the total number of units left to be processed.


Units

Specify Units to obtain the type of units left to be processed (pages, rows, or bytes).
Elapsed

Specify Elapsed to obtain the current elapsed time in milliseconds.


Remaining

Specify Remaining to obtain the estimated remaining time in milliseconds.


Raw

Specify Raw to obtain a string combining all of the above values in the order listed, separated by
semicolons. For example, 43;9728;22230;pages;5025;6138.
Formatted

Specify Formatted to obtain the human readable format. For example:

43% ( 9728 of 22230 pages ) complete after 00:00:05; estimated 00:00:06


remaining

The Remaining value may be empty if the remaining time has not yet been estimated, or if the
number of units completed is greater than the original estimate.

For all property-specific arguments except Formatted, large byte values are never converted to kilobytes
or megabytes.
connection-id

The connection ID number of a database connection. The ID number for the current connection is used if a
value is not specified.

Returns

Returns extended connection properties. The returned value is a VARCHAR.

Remarks

Either the property ID or the property name must be specified.

The CONNECTION_EXTENDED_PROPERTY function is similar to the CONNECTION_PROPERTY function except


that it allows an optional property-specific string parameter to be specified. The interpretation of the property-
specific argument depends on the property ID or name specified in the first argument.

You can use the CONNECTION_EXTENDED_PROPERTY function to return the value for any connection property.
However, extended information is only available for the extended properties.

SQL Anywhere - SQL Reference


282 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Privileges

No privileges are required to execute this function for the current connection ID. To execute this function for other
connections, you must have either the SERVER OPERATOR, MONITOR, or DROP CONNECTION system privilege.

NULL is returned if you specify an invalid parameter value or don't have one of the required system privileges.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following example returns the CHAR character set of the current connection as it is known by the Java
standard:

SELECT CONNECTION_EXTENDED_PROPERTY( 'charset', 'Java' );

Related Information

CONNECTION_PROPERTY function [System] [page 283]


DB_EXTENDED_PROPERTY function [System] [page 318]
DB_PROPERTY function [System] [page 325]

1.3.2.37 CONNECTION_PROPERTY function [System]

Returns the value of a given connection property as a string.

Syntax

CONNECTION_PROPERTY(
{ property-id | property-name }
[ , connection-id ] )

Parameters

property-id

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 283
The connection property ID.
property-name

The connection property name.


connection-id

The connection ID number of a database connection. The ID number for the current connection is used if a
value is not specified.

Returns

VARCHAR, LONG VARCHAR

Remarks

Either the property ID or the property name must be specified.

Privileges

No privileges are required to execute this function for the current connection ID. To execute this function for other
connections, you must have either the SERVER OPERATOR, MONITOR, or DROP CONNECTION system privilege.

NULL is returned if you specify an invalid parameter value or don't have one of the required system privileges.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the number of prepared statements being maintained:

SELECT CONNECTION_PROPERTY( 'PrepStmt' );

Related Information

PROPERTY_NUMBER function [System] [page 477]

SQL Anywhere - SQL Reference


284 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.3.2.38 CONVERT function [Data type conversion]

Returns an expression converted to a supplied data type.

Syntax

CONVERT( datatype, expression [ , format-style ] )

Parameters

datatype

The data type to convert the expression into. Set the data type explicitly, or specify the %TYPE attribute to set
the data type to the data type of a column in a table or view, or to the data type of a variable.
expression

The expression to be converted.


format-style

The style code to apply to the output value. Use this parameter when converting strings to date or time data
types, and vice versa. The table below shows the supported style codes, followed by a representation of the
output format produced by that style code. The style codes are separated into two columns, depending on
whether the century is included in the output format (for example, 06 versus 2006).

Style code 0 is used if an argument is not provided.

Without century (yy) style codes With century (yyyy) style codes Output format

- 0 or 100 Mmm dd yyyy hh:nnAA

1 101 mm/dd/yy[yy]

2 102 [yy]yy.mm.dd

3 103 dd/mm/yy[yy]

4 104 dd.mm.yy[yy]

5 105 dd-mm-yy[yy]

6 106 dd Mmm yy[yy]

7 107 Mmm dd, yy[yy]

8 108 hh:nn:ss

- 9 or 109 Mmm dd yyyy hh:nn:ss:sssAA

10 110 mm-dd-yy[yy]

11 111 [yy]yy/mm/dd

12 112 [yy]yymmdd

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 285
Without century (yy) style codes With century (yyyy) style codes Output format

- 13 or 113 dd Mmm yyyy hh:nn:ss:sss (24 hour


clock, Europe default + milliseconds, 4-
digit year )

- 14 or 114 hh:nn:ss:sss (24 hour clock)

- 20 or 120 yyyy-mm-dd hh:nn:ss (24-hour clock,


ODBC canonical, 4-digit year)

- 21 or 121 yyyy-mm-dd hh:nn:ss.sss (24 hour


clock, ODBC canonical with millisec­
onds, 4-digit year )

Returns

Depends on the data type specified.

Remarks

The CONVERT function can be used to convert a string to a DATE, TIME, or TIMESTAMP data type, provided that
there is no ambiguity when parsing the string. If format-style is specified, then the database server may use it
as a hint on how to parse the string. The database server returns an error if it cannot parse the string
unambiguously.

UltraLite: This function is similar to the CAST function but allows you to specify a format style to assist with date
and time data type conversions.

Standards

ANSI/ISO SQL Standard

The CONVERT function is defined in the ANSI/ISO SQL Standard. However, in the Standard the purpose of
CONVERT is to perform a transcoding of the input string expression to a different character set, which is
implemented in the software as the CSCONVERT function.

Example
The following statements illustrate the use of format style:

SELECT CONVERT( CHAR( 20 ), OrderDate, 104 ) FROM GROUPO.SalesOrders;

OrderDate

16.03.2000

SQL Anywhere - SQL Reference


286 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
OrderDate

20.03.2000

23.03.2000

25.03.2000

...

SELECT CONVERT( CHAR( 20 ), OrderDate, 7 ) FROM GROUPO.SalesOrders;

OrderDate

Mar 16, 00

Mar 20, 00

Mar 23, 00

Mar 25, 00

...

The following statement illustrates conversion to an integer and returns the value 5:

SELECT CONVERT( integer, 5.2 );

The following statement converts a value to the data type defined for the BirthDate column (DATE data type) of
the Employees table:

SELECT CONVERT ( Employees.BirthDate%TYPE, '1966-10-30' );

Related Information

CAST function [Data type conversion] [page 265]


CSCONVERT function [String] [page 298]

1.3.2.39 CORR function [Aggregate]

Returns the correlation coefficient of a set of number pairs.

Syntax

CORR( dependent-expression, independent-expression)

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 287
Parameters

dependent-expression

The variable that is affected by the independent variable.


independent-expression

The variable that influences the outcome.

Returns

DOUBLE

Remarks

This function converts its arguments to DOUBLE, and performs the computation in double-precision floating-
point arithmetic. If the function is applied to an empty set, then it returns NULL.

Both dependent-expression and independent-expression are numeric. The function is applied to the set
of (dependent-expression, independent-expression) after eliminating the pairs for which either
dependent-expression or independent-expression is NULL. The following computation is made:

COVAR_POP ( y, x ) / STDDEV_POP ( y ) * STDDEV_POP ( x )

where y represents the dependent-expression and x represents the independent-expression.

Standards

ANSI/ISO SQL Standard

The CORR function comprises part of optional ANSI/ISO SQL Language Feature T621, "Enhanced numeric
functions".

Example
The following example performs a correlation to discover whether age is associated with income level and
returns the value 0.44022675645996:

SELECT CORR( Salary, ( YEAR( NOW( ) ) - YEAR( BirthDate ) ) ) FROM


GROUPO.Employees;

SQL Anywhere - SQL Reference


288 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Related Information

Aggregate functions [page 202]


COVAR_POP function [Aggregate] [page 295]
STDDEV_POP function [Aggregate] [page 545]

1.3.2.40 COS function [Numeric]

Returns the cosine of the angle in radians given by its argument.

Syntax

COS( numeric-expression )

Parameters

numeric-expression

The angle, in radians.

Returns

This function converts its argument to DOUBLE, performs the computation in double-precision floating-point
arithmetic, and returns a DOUBLE as the result. If the parameter is NULL, the result is NULL.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the value of the cosine of an angle 0.52 radians:

SELECT COS( 0.52 );

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 289
Related Information

ACOS function [Numeric] [page 233]


COT function [Numeric] [page 290]
SIN function [Numeric] [page 530]
TAN function [Numeric] [page 563]

1.3.2.41 COT function [Numeric]

Returns the cotangent of the angle in radians given by its argument.

Syntax

COT( numeric-expression )

Parameters

numeric-expression

The angle, in radians.

Returns

This function converts its argument to DOUBLE, performs the computation in double-precision floating-point
arithmetic, and returns a DOUBLE as the result. If the parameter is NULL, the result is NULL.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the cotangent value of 0.52:

SELECT COT( 0.52 );

SQL Anywhere - SQL Reference


290 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Related Information

COS function [Numeric] [page 289]


SIN function [Numeric] [page 530]
TAN function [Numeric] [page 563]

1.3.2.42 COUNT function [Aggregate]

Counts the number of rows in a group depending on the specified parameters.

Syntax
Expressions

COUNT( [ * | [ ALL | DISTINCT ] expression ] )

Window function

COUNT( [ * | [ ALL ]expression ]) OVER ( window-spec )

window-spec : see the Remarks section below

UltraLite expressions

COUNT( [ * | [ DISTINCT ] expression ] )

Parameters

Return the number of rows in each group. COUNT(*) and COUNT() are semantically equivalent.
[ ALL ] expression

Return the number of rows in each group where the value of expression is not NULL.
UltraLite expression

Return the number of rows in each group where the value of expression is not null.

p
DISTINCT expression

Return the number of distinct values of expression for all of the rows in each group where expression is
not NULL.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 291
Returns

The COUNT function returns a value of type INT.

COUNT never returns the value NULL. If a group contains no rows, or if there are no non-NULL values of
expression in a group, then COUNT returns 0.

Remarks

In SQL Anywhere, the COUNT function returns a maximum value of 2147483647. Use the COUNT_BIG function
when counting large result sets, the result might have more rows, or there is a possibility of overflow. Specifying
this function with window-spec represents usage as a window function in a SELECT statement. As such,
elements of window-spec can be specified either in the function syntax (inline), or with a WINDOW clause in the
SELECT statement.

Standards

ANSI/ISO SQL Standard

Core Feature. When used as a window function, COUNT comprises part of optional ANSI/ISO SQL Language
Feature T611, "Basic OLAP operations".

The ability to specify DISTINCT over an expression that is not a column reference comprises part of optional
ANSI/ISO SQL Language Feature F561, "Full value expressions". The software also supports ANSI/ISO SQL
Language Feature F441, "Extended set function support", which permits operands of aggregate functions to
be arbitrary expressions possibly including outer references to expressions in other query blocks that are not
column references.

The software does not support optional ANSI/ISO SQL Feature F442, "Mixed column references in set
functions". The software does not permit the arguments of an aggregate function to include both a column
reference from the query block containing the COUNT function, combined with an outer reference.

Example
The following statement returns each unique city, and the number of employees working in that city:

SELECT City, COUNT( * ) FROM GROUPO.Employees GROUP BY City;

Related Information

WINDOW clause [page 1413]


AVG function [Aggregate] [page 246]
SUM function [Aggregate] [page 557]

SQL Anywhere - SQL Reference


292 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
COUNT_BIG function [Aggregate] [page 293]

1.3.2.43 COUNT_BIG function [Aggregate]

Counts the number of rows in a group depending on the specified parameters.

Syntax

COUNT_BIG(
[ * | [ ALL | DISTINCT ] expression ]
| [ * | [ ALL ] expression ]) OVER ( window-spec
)

window-spec : see the Remarks section below

Parameters

Return the number of rows in each group. COUNT_BIG(*) and COUNT_BIG() are semantically equivalent.
[ ALL ] expression

Return the number of rows in each group where the value of expression is not NULL.
DISTINCT expression

Return the number of distinct values of expression for all of the rows in each group where expression is
not NULL.

Returns

COUNT_BIG returns a value of type BIGINT.

COUNT_BIG never returns the value NULL. If a group contains no rows, or if there are no non-NULL values of
expression in a group, then COUNT_BIG returns 0.

Remarks

It is recommended that you use the COUNT_BIG function when counting large result sets, the result might have
more rows, or there is a possibility of overflow. Otherwise, use the COUNT function, which has a maximum value
of 2147483647.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 293
Specifying this function with window-spec represents usage as a window function in a SELECT statement. As
such, elements of window-spec can be specified either in the function syntax (inline), or with a WINDOW clause
in the SELECT statement.

Standards

ANSI/ISO SQL Standard

Not in the standard.

The software does not support optional Feature F442, "Mixed column references in set functions". The
software also does not permit the arguments of an aggregate function to include both a column reference
from the query block containing the COUNT_BIG function, combined with an outer reference.

Example
The following statement returns each unique city, and the number of employees working in that city:

SELECT City, COUNT_BIG( * ) FROM GROUPO.Employees GROUP BY City;

Related Information

AVG function [Aggregate] [page 246]


SUM function [Aggregate] [page 557]
COUNT function [Aggregate] [page 291]

1.3.2.44 COUNT_SET_BITS function [Bit array]

Returns a count of the number of bits set to 1 (TRUE) in the array.

Syntax

COUNT_SET_BITS( bit-expression )

Parameters

bit-expression

The bit array for which to determine the set bits.

SQL Anywhere - SQL Reference


294 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Returns

UNSIGNED INT

Remarks

Returns NULL if bit-expression is NULL.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the value 4:

SELECT COUNT_SET_BITS( '00110011' );

The following statement returns the value 12:

SELECT COUNT_SET_BITS( '0011001111111111' );

1.3.2.45 COVAR_POP function [Aggregate]

Returns the population covariance of a set of number pairs.

Syntax
Expression

COVAR_POP( dependent-expression, independent-expression)

Window function

COVAR_POP( dependent-expression, independent-expression)


OVER ( window-spec )

window-spec : see the Remarks section below

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 295
Parameters

dependent-expression

The variable that is affected by the independent variable.


independent-expression

The variable that influences the outcome.

Returns

DOUBLE

Remarks

This function converts its arguments to DOUBLE, and performs the computation in double-precision floating-
point arithmetic. If the function is applied to an empty set, then it returns NULL.

Both dependent-expression and independent-expression are numeric. The function is applied to the set
of (dependent-expression, independent-expression) pairs after eliminating all pairs for which either
dependent-expression or independent-expression is NULL. The following computation is then made:

( SUM( y * x ) - SUM( x ) * SUM( y ) / n ) / n

where y represents the dependent-expression and x represents the independent-expression.

Specifying this function with window-spec represents usage as a window function in a SELECT statement. As
such, elements of window-spec can be specified either in the function syntax (inline), or with a WINDOW clause
in the SELECT statement.

Standards

ANSI/ISO SQL Standard

The COVAR_POP function comprises part of optional ANSI/ISO SQL Language Feature T621, "Enhanced
numeric functions".

Example
The following example measures the strength of association between employees' age and salary. This function
returns the value 73785.84005866687.

SELECT COVAR_POP( Salary, ( YEAR( NOW( ) ) - YEAR( BirthDate ) ) )


FROM GROUPO.Employees;

SQL Anywhere - SQL Reference


296 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Related Information

WINDOW clause [page 1413]


COVAR_SAMP function [Aggregate] [page 297]
SUM function [Aggregate] [page 557]

1.3.2.46 COVAR_SAMP function [Aggregate]

Returns the sample covariance of a set of number pairs.

Syntax
Expression

COVAR_SAMP( dependent-expression, independent-expression)

Window function

COVAR_SAMP( dependent-expression, independent-expression)


OVER ( window-spec )

window-spec : see the Remarks section below

Parameters

dependent-expression

The variable that is affected by the independent variable.


independent-expression

The variable that influences the outcome.

Returns

DOUBLE

Remarks

This function converts its arguments to DOUBLE, and performs the computation in double-precision floating-
point arithmetic. If the function is applied to an empty set, then it returns NULL.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 297
Both dependent-expression and independent-expression are numeric. The function is applied to the set
of (dependent-expression, independent-expression) pairs after eliminating all pairs for which either
dependent-expression or independent-expression is NULL.

Specifying this function with window-spec represents usage as a window function in a SELECT statement. As
such, elements of window-spec can be specified either in the function syntax (inline), or with a WINDOW clause
in the SELECT statement.

Standards

ANSI/ISO SQL Standard

The COVAR_SAMP function comprises part of optional ANSI/ISO SQL Language Feature T621, "Enhanced
numeric functions".

Example
The following example returns the value 74782.9460054052:

SELECT COVAR_SAMP( Salary, ( 2008 - YEAR( BirthDate ) ) )


FROM GROUPO.Employees;

Related Information

WINDOW clause [page 1413]


COVAR_POP function [Aggregate] [page 295]
SUM function [Aggregate] [page 557]

1.3.2.47 CSCONVERT function [String]

Converts strings between character sets.

Syntax

CSCONVERT(
string-expression,
target-charset-string [, source-charset-string [, options ] ] )

Parameters

string-expression

SQL Anywhere - SQL Reference


298 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
The string to be converted.
target-charset-string

The destination character set. target-charset-string can be any of the supported character set labels. It
can also be:

os_charset

Specify this to use the character set used by the operating system that is hosting the database server.
char_charset

Specify this to use the CHAR character set used by the database.
nchar_charset

Specify this to use the NCHAR character set used by the database.
options

You can specify one of the following options:

Read or write a byte order mark (BOM)

Specify read_bom=on or read_bom=off to turn on or off reading byte order marks. Specify
write_bom=on or write_bom=off to turn on or off writing byte order marks. By default, the
behavior is read_bom=on and write_bom=off.
source-charset-string

The character set used for string-expression. The default is db_charset (the database character set).
source-charset-string can be any of the supported character set labels. It can also be:

os_charset

Specify this to use the character set used by the operating system that is hosting the database server.
char_charset

Specify this to use the CHAR character set used by the database.
nchar_charset

Specify this to use the NCHAR character set used by the database.

Returns

LONG BINARY

Remarks

You can view the list of supported character sets by running the following command:

dbinit -le

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 299
Standards

ANSI/ISO SQL Standard

Not in the standard. In the ANSI/ISO SQL Standard, conversion of string data from one charset to another is
accomplished with the CONVERT function (not to be confused with the CONVERT function provided in the
software) which has different arguments than CSCONVERT.

Example
This fragment converts the mytext column from the Traditional Chinese character set to the Simplified Chinese
character set:

SELECT CSCONVERT( mytext, 'cp936', 'cp950' )


FROM mytable;

This fragment converts the mytext column from the database character set to the Simplified Chinese character
set:

SELECT CSCONVERT( mytext, 'cp936' )


FROM mytable;

If a file name is stored in the database, it is stored in the database character set. If the server will read from or
write to a file whose name is stored in a database (for example, in an external stored procedure), the file name
must be explicitly converted to the operating system character set before the file can be accessed. File names
stored in the database and retrieved by the client are converted automatically to the client character set, so
explicit conversion is not necessary.

This fragment converts the value in the filename column from the database character set to the operating
system character set:

SELECT CSCONVERT( filename, 'os_charset' )


FROM mytable;

A table contains a list of file names. An external stored procedure takes a file name from this table as a
parameter and reads information directly out of that file. The following statement works when character set
conversion is not required:

SELECT MYFUNC( filename )


FROM mytable;

The mytable clause indicates a table with a filename column. However, if you need to convert the file name to
the character set of the operating system, you would use the following statement:

SELECT MYFUNC( csconvert( filename, 'os_charset' ) )


FROM mytable;

Related Information

String functions [page 214]

SQL Anywhere - SQL Reference


300 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.3.2.48 CUME_DIST function [Ranking]

Computes the relative position of one value among a group of rows.

Syntax

CUME_DIST( ) OVER ( window-spec )

window-spec : see the Remarks section below

Returns

A DOUBLE value between 0 and 1

Remarks

Composite sort keys are not currently allowed in the CUME_DIST function. You can use composite sort keys with
any of the other rank functions.

Elements of window-spec can be specified either in the function syntax (inline), or with a WINDOW clause in the
SELECT statement. When used as a window function, you must specify an ORDER BY clause, you may specify a
PARTITION BY clause, however, you cannot specify a ROWS or RANGE clause.

Standards

ANSI/ISO SQL Standard

The CUME_DIST function comprises part of optional SQL Language Feature T612, "Advanced OLAP
operations".

Example
The following example returns a result set that provides a cumulative distribution of the salaries of employees
who live in California:

SELECT DepartmentID, Surname, Salary,


CUME_DIST() OVER (PARTITION BY DepartmentID
ORDER BY Salary DESC) "Rank"
FROM GROUPO.Employees
WHERE State IN ('CA');

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 301
Here is the result set:

DepartmentID Surname Salary Rank

200 Savarino 72300.000 0.333333333333333

200 Clark 45000.000 0.666666666666667

200 Overbey 39300.000 1

Related Information

WINDOW clause [page 1413]


DENSE_RANK function [Ranking] [page 334]
PERCENT_RANK function [Ranking] [page 468]
RANK function [Ranking] [page 482]

1.3.2.49 DATALENGTH function [System]

Returns the length, in bytes, of the underlying storage for the result of an expression.

Syntax

DATALENGTH( expression )

Parameters

expression

Usually a column name. If expression is a string constant, you must enclose it in quotes.

Returns

UNSIGNED INT

SQL Anywhere - SQL Reference


302 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Remarks

The return values of the DATALENGTH function are as follows:

Data type DATALENGTH

BIT 1

TINYINT 1

SMALLINT 2

INTEGER 4

BIGINT 8

REAL 4

DOUBLE 8

TIME 8

DATE 4

TIMESTAMP 8

DATETIME 8

TIMESTAMP WITH TIME ZONE 29

UNIQUEIDENTIFIER 16

CHAR Length of the data

VARCHAR Length of the data

BINARY Length of the data

VARBINARY Length of the data

NCHAR Length of the data

NVARCHAR Length of the data

TEXT Length of the data

NTEXT Length of the data

IMAGE Length of the data

XML Length of the data

In SQL Anywhere, this function supports NCHAR inputs and outputs.

Standards

ANSI/ISO SQL Standard

Not in the standard.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 303
Example
The following statement returns the length of the longest string in the CompanyName column:

SELECT MAX( DATALENGTH( CompanyName ) )


FROM GROUPO.Customers;

The following statement returns the length of the string '8sdofinsv8s7a7s7gehe4h':

SELECT DATALENGTH( '8sdofinsv8s7a7s7gehe4h' );

Related Information

SQL data types [page 126]

1.3.2.50 DATE function [Date and time]

Converts the expression into a date, and removes any hours, minutes, or seconds.

Syntax

DATE( expression )

Parameters

expression

The value to be converted to date format, typically a string.

Returns

DATE

Standards

ANSI/ISO SQL Standard

Not in the standard.

SQL Anywhere - SQL Reference


304 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Example
The following statement returns the value 1999-01-02 as a date:

SELECT DATE( '1999-01-02 21:20:53' );

The following statement returns the create dates of all the objects listed in the SYSOBJECT system view:

SELECT DATE( creation_time ) FROM SYSOBJECT;

Related Information

Expressions in SQL statements [page 32]

1.3.2.51 DATEADD function [Date and time]

Returns a TIMESTAMP or TIMESTAMP WITH TIME ZONE value produced by adding a date part to its argument.

Syntax

DATEADD( date-part, integer-expression, timestamp-expression )

date-part :
year
| quarter
| month
| week
| day
| dayofyear
| hour
| minute
| second
| millisecond
| microsecond

Parameters

date-part

The date part that integer-expression represents.


integer-expression

The number of date-part values to be added to timestamp-expression. integer-expression can be


any numeric type, but its value is truncated to an INTEGER.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 305
timestamp-expression

The TIMESTAMP or TIMESTAMP WITH TIME ZONE value to be modified.

Returns

TIMESTAMP WITH TIME ZONE if timestamp-expression is a TIMESTAMP WITH TIME ZONE; otherwise
TIMESTAMP.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the TIMESTAMP value 2016-05-02 00:00:00.000:

SELECT DATEADD( month, 12, '2015/05/02' );

The following statement returns the TIMESTAMP value 2015-05-02 04:00:00.000:

SELECT DATEADD( hour, 4, '2015/05/02' );

The following statement returns the TIMESTAMP WITH TIME ZONE value 2015-05-06 11:33:00.000+04:00:

SELECT DATEADD( day, 4, CAST( '2015/05/02 11:33:00.000000+04:00' as TIMESTAMP


WITH TIME ZONE ));

Related Information

Specifying date parts [page 208]

1.3.2.52 DATEDIFF function [Date and time]

Returns the interval between two dates.

Syntax

DATEDIFF( date-part, date-expression-1, date-expression-2 )

SQL Anywhere - SQL Reference


306 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
date-part :
year
| quarter
| month
| week
| day
| dayofyear
| hour
| minute
| second
| millisecond
| microsecond

Parameters

date-part

Specifies the date part in which the interval is to be measured.


date-expression-1

The starting date for the interval. This value is subtracted from date-expression-2 to return the number of
date-parts between the two arguments.
date-expression-2

The ending date for the interval. Date-expression-1 is subtracted from this value to return the number of
date-parts between the two arguments.

Returns

INT with year, quarter, month, week, day, and dayofyear. BIGINT with hour, minute, second, millisecond, and
microsecond.

Remarks

This function calculates the number of date parts between two specified dates. The result is a signed integer value
equal to (date-expression-2 - date-expression-1), in date parts.

The DATEDIFF function results are truncated, not rounded, when the result is not an even multiple of the date
part.

When you use day as the date part, the DATEDIFF function returns the number of midnights between the two
times specified, including the second date but not the first.

When you use month as the date part, the DATEDIFF function returns the number of first-of-the-months between
two dates, including the second date but not the first.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 307
When you use week as the date part, the DATEDIFF function returns the number of Sundays between the two
dates, including the second date but not the first.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns 1:

SELECT DATEDIFF( hour, '4:00AM', '5:50AM' );

The following statement returns 102:

SELECT DATEDIFF( month, '1987/05/02', '1995/11/15' );

The following statement returns 0:

SELECT DATEDIFF( day, '00:00', '23:59' );

The following statement returns 4:

SELECT DATEDIFF( day,


'1999/07/19 00:00',
'1999/07/23 23:59' );

The following statement returns 0:

SELECT DATEDIFF( month, '1999/07/19', '1999/07/23' );

The following statement returns 1:

SELECT DATEDIFF( month, '1999/07/19', '1999/08/23' );

The following example shows how to use the DATEDIFF function to return the number of milliseconds to do a 3-
way join with the GROUPO.Customers table. The output is sent to the database server window:

BEGIN
DECLARE startTime, endTime TIMESTAMP;
DECLARE rowCount INT;

SET startTime = CURRENT TIMESTAMP;


SELECT count(*) INTO rowCount FROM GROUPO.Customers AS T1, GROUPO.Customers
AS T2, GROUPO.Customers AS T3;
SET endTime = CURRENT TIMESTAMP;

MESSAGE 'Time to count rows: ' || DATEDIFF( MILLISECOND, startTime, endTime )


|| ' ms';
END

SQL Anywhere - SQL Reference


308 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Related Information

Specifying date parts [page 208]


DATEADD function [Date and time] [page 305]

1.3.2.53 DATEFORMAT function [Date and time]

Returns a string representing a date expression in the specified format.

Syntax

DATEFORMAT( datetime-expression, string-expression )

Parameters

datetime-expression

The datetime to be converted.


string-expression

The format of the converted date.

This function supports NCHAR inputs and/or outputs.

UltraLite does not support NCHAR inputs and/or outputs.

Returns

VARCHAR

Remarks

Any allowable date format can be used for the string-expression.

Standards

ANSI/ISO SQL Standard

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 309
Not in the standard.

Example
The following statement returns the value Jan 01, 1989:

SELECT DATEFORMAT( '1989-01-01', 'Mmm dd, yyyy' );

1.3.2.54 DATENAME function [Date and time]

Returns the name of the specified part (such as the month June) of a TIMESTAMP or TIMESTAMP WITH TIME
ZONE value, as a character string.

Syntax

DATENAME( date-part, timestamp-expression )

Parameters

date-part

The date part to be named.


timestamp-expression

The TIMESTAMP or TIMESTAMP WITH TIME ZONE value for which the date part name is to be returned. For
meaningful results, timestamp-expression should contain the requested date-part.

Returns

VARCHAR

Remarks

The DATENAME function returns a string, even if the result is numeric, such as 23 for the day.

In SQL Anywhere, English names are returned for an English locale, other names are returned when the locale is
not English. For example, use the Language (LANG) connection parameter to specify a different language.

When the date part TZOffset (TZ) is specified, DATENAME returns the offset as a string of the form: { + | - }hh:nn.

SQL Anywhere - SQL Reference


310 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
In an English locale, the following statement returns the value May:

SELECT DATENAME( month, '1987/05/02' );

On SQL Anywhere in a German locale, the value returned is Mai. In a Spanish locale, the value returned is Mayo.
Several locales are supported.

The following statement returns the value -05:00:

SELECT DATENAME( TZ, CAST('2016/02/03 12:02:00-5:00' AS TIMESTAMP WITH TIME


ZONE) ) AS TZOffset;

Related Information

Specifying date parts [page 208]


DATEPART function [Date and time] [page 311]
MONTHNAME function [Date and time] [page 445]

1.3.2.55 DATEPART function [Date and time]

Returns a portion of a TIMESTAMP or TIMESTAMP WITH TIME ZONE value.

Syntax

DATEPART( date-part, timestamp-expression )

Parameters

date-part

The date part to be returned.


timestamp-expression

The TIMESTAMP or TIMESTAMP WITH TIME ZONE value for which the part is to be returned.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 311
Returns

INT

Remarks

For meaningful results timestamp-expression should contain the required date-part portion.

The numbers that correspond to week days depend on the setting of the first_day_of_week database option. By
default Sunday=7.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the value 5:

SELECT DATEPART( month , '1987/05/02' );

The following example creates a table, TableStatistics, and inserts into it the total number of sales orders per
year as stored in the SalesOrders table:

CREATE TABLE TableStatistics (


ID INTEGER NOT NULL DEFAULT AUTOINCREMENT,
Year INT,
NumberOrders INT );
INSERT INTO TableStatistics ( Year, NumberOrders )
SELECT DATEPART( Year, OrderDate ), COUNT(*)
FROM GROUPO.SalesOrders
GROUP BY DATEPART( Year, OrderDate );

Related Information

Specifying date parts [page 208]


SET statement [T-SQL] [page 1330]
EXTRACT function [Date and time] [page 369]
MICROSECOND function [Date and time] [page 436]
MILLISECOND function [Date and time] [page 437]

SQL Anywhere - SQL Reference


312 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.3.2.56 DATETIME function [Date and time]

Converts an expression into a TIMESTAMP value.

Syntax

DATETIME( expression )

Parameters

expression

The expression to be converted. It is generally a string.

Returns

TIMESTAMP

Remarks

Attempts to convert numerical values return an error.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns a timestamp with value 1998-09-09 12:12:12.000:

SELECT DATETIME( '1998-09-09 12:12:12.000' );

Related Information

Expressions in SQL statements [page 32]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 313
CAST function [Data type conversion] [page 265]
CURRENT TIME special value [page 91]
CURRENT TIMESTAMP special value [page 93]
CURRENT UTC TIMESTAMP special value [page 96]
DATE data type [page 163]
DATE function [Date and time] [page 304]
DATETIME data type [page 164]
DATETIMEOFFSET data type [page 165]
GETDATE function [Date and time] [page 377]
ISDATE function [Data type conversion] [page 409]
NOW function [Date and time] [page 460]
SMALLDATETIME data type [page 167]
TIME data type [page 169]
TIMESTAMP special value [page 108]
TIMESTAMP data type [page 170]
UTC TIMESTAMP special value [page 110]

1.3.2.57 DAY function [Date and time]

Returns the day of the month of its argument as an integer between 1 and 31.

Syntax

DAY( date-expression )

Parameters

date-expression

The date as a DATE data type.

Returns

SMALLINT

Remarks

The DAY function returns an integer between 1 and 31, corresponding to the day of the month in the argument.

SQL Anywhere - SQL Reference


314 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the value 12:

SELECT DAY( '2001-09-12' );

1.3.2.58 DAYNAME function [Date and time]

Returns the name of the day of the week from a date.

Syntax

DAYNAME( date-expression )

Parameters

date-expression

The date.

Returns

VARCHAR

Remarks

The names are returned as: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday.

SQL Anywhere returns English names for an English locale, and returns other names when the locale is not
English. For example, the Language (LANG) connection parameter can be used to specify a different language.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 315
Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
In an English locale, the following statement returns the value Saturday:

SELECT DAYNAME( '1987/05/02' );

In a German locale, the value returned is Samstag. In an Italian locale, the value returned is sabato. Several
locales are supported.

1.3.2.59 DAYS function [Date and time]

Manipulates a TIMESTAMP or returns the number of days between two TIMESTAMP values.

Syntax
Return number of days between 0000-02-29 and a TIMESTAMP value

DAYS( timestamp-expression )

Return number of days between two TIMESTAMP values

DAYS( timestamp-expression, timestamp-expression )

Add time to a TIMESTAMP

DAYS( timestamp-expression, integer-expression )

Parameters

timestamp-expression

A TIMESTAMP value.
integer-expression

The number of days to be added to the timestamp-expression. If the integer-expression is negative,


the appropriate number of days is subtracted from timestamp-expression. If you supply an integer
expression, the timestamp-expression must be explicitly cast as a TIME, DATE or TIMESTAMP. If
timestamp-expression is a TIME value, the current date is assumed.

SQL Anywhere - SQL Reference


316 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Returns

TIMESTAMP when adding time to a timestamp; otherwise, INTEGER.

Remarks

The result of the DAYS function depends on its arguments. The DAYS function ignores hours, minutes, and
seconds in its arguments.

Return number of days since 0000-02-29

If you pass a single timestamp-expression to the DAYS function, it will return the number of days between
0000-02-29 and timestamp-expression as an INTEGER.

Note
0000-02-29 is not meant to imply an actual date; it is the default date used by the DAYS function.

Return number of days between two TIMESTAMP values

If you pass two TIMESTAMP values to the DAYS function, the function returns the integer number of days
between them.

You can also use the DATEDIFF function to get the interval between two dates.
Add time to a TIMESTAMP

If you pass a TIMESTAMP value and an integer to the DAYS function, the function returns the TIMESTAMP
result of adding the integer number of days to the timestamp-expression argument.

You can also use the DATEADD function to add a date part to a TIMESTAMP.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the integer 729889:

SELECT DAYS( '1998-07-13 06:07:12' );

The following statements return the integer value -366, indicating that the second DATE value is 366 days
before the first. It is recommended that you use the second example (DATEDIFF):

SELECT DAYS( '1998-07-13 06:07:12',


'1997-07-12 10:07:12' );

SELECT DATEDIFF( day,

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 317
'1998-07-13 06:07:12',
'1997-07-12 10:07:12' );

The following statements return the TIMESTAMP value 1999-07-14 00:00:00.000. It is recommended that you
use the second example (DATEADD):

SELECT DAYS( CAST('1998-07-13' AS DATE ), 366 );

SELECT DATEADD( day, 366, '1998-07-13' );

Related Information

DATEDIFF function [Date and time] [page 306]


DATEADD function [Date and time] [page 305]
CAST function [Data type conversion] [page 265]

1.3.2.60 DB_EXTENDED_PROPERTY function [System]

Returns the value of the given property. Allows an optional property-specific string parameter to be specified.

Syntax

DB_EXTENDED_PROPERTY(
{ property-id | property-name }
[, property-specific-argument
[, database-id | database-name ] ]
)

Parameters

property-id

The database property ID to query.


property-name

The database property name to query.


property-specific-argument

The following database properties allow you to specify additional arguments, as noted below, to return
specific information about the property.

CatalogCollation, Collation, NcharCollation

SQL Anywhere - SQL Reference


318 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
When querying these properties, the following values can be specified as a property-specific-
argument to return information specific to the collation:

AccentSensitivity

Returns the accent sensitivity setting for the collation. For example, the following statement returns
the accent sensitivity setting for the NCHAR collation:

SELECT DB_EXTENDED_PROPERTY( 'NcharCollation', 'AccentSensitivity');

Possible return values are: NULL, Ignore, Respect, and French.


CaseSensitivity

Returns the case sensitivity setting for the collation. Possible return values are: NULL, Ignore,
Respect, UpperFirst, and LowerFirst.
PunctuationSensitivity

Returns the punctuation sensitivity setting for the collation. Possible return values are: NULL, Ignore,
Primary, and Quaternary.
Properties

Returns a string containing all the tailoring options specified for the collation.
Specification

Returns a string containing the full collation specification used for the collation.
CharSet

Specify the name of a standard to obtain the default CHAR character set label for the standard. Possible
values you can specify are: ASE, IANA, MIME, JAVA, WINDOWS, UTR22, IBM, and ICU. If no standard is
specified, IANA is used as the default, unless the database connection was made through TDS, in which
case ASE is the default.
DBFileFragments

Specify the name of a dbspace, or the file ID for the dbspace, to obtain the number of file fragments. If you
do not specify the dbspace name or file ID, then the system dbspace is used. If the specified dbspace
name or ID does not exist for the database to which you are connected, then the function returns NULL.
DriveBus

(Microsoft Windows only) Specify the name of a dbspace, or the file ID for the dbspace, to obtain the
configuration of the drive on which it resides. DriveBus returns BusType from an
IOCTL_STORAGE_QUERY_PROPERTY call. If you do not specify the dbspace name or file ID, then the
system dbspace is used. If the specified dbspace name or ID does not exist for the database to which you
are connected, then the function returns NULL.
DriveModel

(Microsoft Windows only) Specify the name of a dbspace, or the file ID for the dbspace, to obtain the
model of the drive on which it resides. DriveModel returns the concatenation of the VendorId, ProductId,
and ProductRevision strings from an IOCTL_STORAGE_QUERY_PROPERTY call. If you do not specify the
dbspace name or file ID, then the system dbspace is used. If the specified dbspace name or ID does not
exist for the database to which you are connected, then the function returns NULL.
DriveType

Specify the name of a dbspace, or the file ID for the dbspace, to obtain its drive type. The value returned is
one of the following: CD, FIXED, RAMDISK, REMOTE, REMOVABLE, or UNKNOWN. If you do not specify

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 319
the dbspace name or file ID, then the system dbspace is used. If the specified dbspace name or ID does
not exist for the database to which you are connected, then the function returns NULL.
File

Specify the name of a dbspace, or the file ID for the dbspace, to obtain the file name of the database root
file, including the path. Specify 'translog' to obtain the path and file name of the transaction log file, and
'translogmirror' to obtain the path and file name of the transaction log mirror file. If you do not specify the
dbspace name or file ID, then the system dbspace is used. If the specified dbspace name or ID does not
exist for the database to which you are connected, then the function returns NULL.
FileSize

Specify the name of a dbspace, or the file ID for the dbspace, to obtain the size of the specified file in
pages. You can also specify 'temporary' to return the size of the temporary dbspace, 'translog' to return
the size of the transaction log file, and 'translogmirror' to return the size of the transaction log file mirror.
If you do not specify the dbspace name or file ID, then the system dbspace is used. If the specified
dbspace name or ID does not exist for the database to which you are connected, then the function returns
NULL.
FreePages

Specify the name of a dbspace, or the file ID for the dbspace, to obtain the number of free pages. You can
also specify temporary to return the number of free pages in the temporary dbspace, or translog to return
the number of free pages in the transaction log file. If you do not specify the dbspace name or file ID, then
the system dbspace is used. If the specified dbspace name or ID does not exist for the database to which
you are connected, then the function returns NULL.
IOParallelism

Specify the name of a dbspace, or the file ID for the dbspace, to obtain the estimated number of
simultaneous I/O operations supported by the dbspace. If you do not specify the dbspace name or file ID,
then the system dbspace is used. If the specified dbspace name or ID does not exist for the database to
which you are connected, then the function returns NULL.
MirrorServerState

Specify a server name to determine the connection status of the mirror server. Returns connected,
disconnected, incoming only, outgoing only, or NULL. The value is NULL when the database is not
mirrored; Connected when there is a connection from this server to a specified server and a connection
from the specified server to this server; Disconnected when there are no connections between this server
and the specified server; Incoming only when there is a connection from the specified server to this
server; and Outgoing only when there is a connection from this server to the specified server.
MirrorState

Specify a server name to determine the synchronization status of the mirror server. Returns
synchronizing, synchronized, or NULL. The value is Synchronizing when the mirror server is not
connected, or has not yet read all the primary server's log pages, or if the synchronization mode is
asynchronous. The value is Synchronized when the mirror server is connected and has all of the changes
that have been committed on the primary server. If the database is not being mirrored the value is NULL.
NcharCharSet

Specify the name of a standard to obtain the default NCHAR character set encoding label for that
standard. Possible values you can specify are: ASE, IANA, MIME, JAVA, WINDOWS, UTR22, IBM, and ICU.
If no standard is specified, IANA is used as the default, unless the database connection was made through
TDS, in which case ASE is the default.
NextScheduleTime

SQL Anywhere - SQL Reference


320 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Specify an event name to obtain its next scheduled execution time.
database-id

The database ID number, as returned by the DB_ID function. Typically, the database name is used.
database-name

The name of the database, as returned by the DB_NAME function.

Returns

VARCHAR

Remarks

The DB_EXTENDED_PROPERTY function is similar to the DB_PROPERTY function except that it allows an optional
property-specific-argument string parameter to be specified. The interpretation of property-specific-
argument depends on the property ID or name specified in the first argument.

The current database is used if the third argument is omitted.

When comparing catalog strings such as table names and procedure names, the database server uses the CHAR
collation. For the UCA collation, the catalog collation is the same as the CHAR collation but with the tailoring
changed to be case-insensitive, accent-insensitive and with punctuation sorted in the primary level. For legacy
collations, the catalog collation is the same as the CHAR collation but with the tailoring changed to be case-
insensitive. While you cannot explicitly specify the tailoring used for the catalog collation, you can query the
Specification property to obtain the full collation specification used by the database server for comparing catalog
strings. Querying the Specification property can be useful if you need to exploit the difference between the CHAR
and catalog collations. For example, suppose you have a punctuation-insensitive CHAR collation and you want to
execute an upgrade script that defines a procedure called my_procedure, and that also attempts to delete an old
version named myprocedure. The following statements cannot achieve the desired results because
my_procedure is equivalent to myprocedure, using the CHAR collation:

CREATE PROCEDURE my_procedure( ) ...;


IF EXISTS ( SELECT * FROM SYS.SYSPROCEDURE WHERE proc_name = 'myprocedure' )
THEN DROP PROCEDURE myprocedure
END IF;

Instead, you could execute the following statements to achieve the desired results:

CREATE PROCEDURE my_procedure( ) ...;


IF EXISTS ( SELECT * FROM SYS.SYSPROCEDURE
WHERE COMPARE( proc_name, 'myprocedure',
DB_EXTENDED_PROPERTY( 'CatalogCollation', 'Specification' ) ) = 0 )
THEN DROP PROCEDURE myprocedure
END IF;

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 321
Privileges

No privileges are required to execute this function for the current database. To execute this function for other
databases, you must have either the SERVER OPERATOR or MONITOR system privilege.

NULL is returned if you specify an invalid parameter value or don't have one of the required system privileges.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the location of the current database:

SELECT DB_EXTENDED_PROPERTY( 'File' );

The following statement returns the file size of the system dbspace, in pages:

SELECT DB_EXTENDED_PROPERTY( 'FileSize' );

The following statement returns the file size of the transaction log, in pages:

SELECT DB_EXTENDED_PROPERTY( 'FileSize', 'translog' );

The following statement returns the case sensitivity setting for the NCHAR collation:

SELECT DB_EXTENDED_PROPERTY( 'NcharCollation',' CaseSensitivity' );

The following statement returns the tailoring options specified for the database CHAR collation:

SELECT DB_EXTENDED_PROPERTY ( 'Collation', 'Properties' );

The following statement returns the full collation specification for the database NCHAR collation:

SELECT DB_EXTENDED_PROPERTY( 'NcharCollation', 'Specification' );

The following statement returns the connection status of the mirror server Test:

SELECT DB_EXTENDED_PROPERTY( 'MirrorServerState', 'Test' );

The following statement returns the synchronization status of the mirror server Test:

SELECT DB_EXTENDED_PROPERTY( 'MirrorState', 'Test' );

SQL Anywhere - SQL Reference


322 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Related Information

DB_ID function [System] [page 323]


DB_NAME function [System] [page 324]
CONNECTION_PROPERTY function [System] [page 283]
CONNECTION_EXTENDED_PROPERTY function [String] [page 281]

1.3.2.61 DB_ID function [System]

Returns the database ID number.

Syntax

DB_ID( [ database-name ] )

Parameters

database-name

A string containing the database name. If no database-name is supplied, the ID number of the current
database is returned.

Returns

INT

Remarks

None

Privileges

None

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 323
Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the value 0, when executed against the sample database as the sole database
on the server:

SELECT DB_ID( 'demo' );

The following statement returns the value 0 if executed against the only running database:

SELECT DB_ID( );

1.3.2.62 DB_NAME function [System]

Returns the name of a database with a given ID number.

Syntax

DB_NAME( [ database-id ] )

Parameters

database-id

The ID of the database. The database-id must be a numeric expression.

Returns

VARCHAR

Remarks

If no database ID is supplied, the name of the current database is returned.

SQL Anywhere - SQL Reference


324 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Privileges

No privileges are required to execute this function for the current database. To execute this function for other
databases, you must have either the SERVER OPERATOR or MONITOR system privilege.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the database name demo when executed against the sample database as the
sole database on the server:

SELECT DB_NAME( 0 );

Related Information

sa_db_list system procedure [page 1486]


NEXT_DATABASE function [System] [page 453]

1.3.2.63 DB_PROPERTY function [System]

Returns the value of the specified database property.

Syntax

DB_PROPERTY(
{ property-id | property-name }
[, database-id | database-name ]
)

UltraLite:

DB_PROPERTY( property-name )

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 325
Parameters

property-id

The database property ID.


property-name

The database property name.


database-id

The database ID number, as returned by the DB_ID function. Typically, the database name is used.
database-name

The name of the database, as returned by the DB_NAME function.

Returns

VARCHAR, LONG VARCHAR

Remarks

Returns a string.

The current database is used if the second argument is omitted.

UltraLite: To set an option in UltraLite, use the SET OPTION statement or your component's API-specific Set
Database Option method.

Privileges

No privileges are required to execute this function for the current database. To execute this function for other
databases, you must have either the SERVER OPERATOR or MONITOR system privilege.

NULL is returned if you specify an invalid parameter value or don't have one of the required system privileges.

UltraLite: These privileges do not apply to UltraLite.

Standards

ANSI/ISO SQL Standard

Not in the standard.

SQL Anywhere - SQL Reference


326 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Example
The following statement returns the page size of the current database, in bytes:

SELECT DB_PROPERTY( 'PageSize' );

UltraLite: The following statement returns the page size of the current database, in bytes:

SELECT DB_PROPERTY( 'page_size');

Related Information

DB_ID function [System] [page 323]


DB_NAME function [System] [page 324]
PROPERTY function [System] [page 472]

1.3.2.64 DECOMPRESS function [String]

Decompresses the string and returns a LONG BINARY value.

Syntax

DECOMPRESS( string-expression [, compression-algorithm-alias] )

Parameters

string-expression

The string to decompress. Binary values can also be passed to this function. This parameter is case sensitive,
even in case-insensitive databases.
compression-algorithm-alias

Alias (string) for the algorithm to use for decompression. The supported values are 'zip' and 'gzip' (both are
based on the same algorithm, but use different headers and trailers).

Zip is a widely supported compression algorithm. Gzip is compatible with the gzip utility on Unix, whereas the
zip algorithm is not.

If no algorithm is specified, the function attempts to detect which algorithm was used to compress the string.
If the incorrect algorithm is specified, or the correct algorithm cannot be detected, the string is not
decompressed.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 327
Returns

LONG BINARY

Remarks

This function can be used to decompress a value that was compressed using the COMPRESS function.

You do not need to use the DECOMPRESS function on values that are stored in a compressed column.
Compression and decompression of values in a compressed column are handled automatically by the database
server.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following example uses the DECOMPRESS function to decompress values from the Attachment column of
a fictitious table, TableA:

SELECT DECOMPRESS ( Attachment, 'gzip' )


FROM TableA;

Since DECOMPRESS returns binary values, if the original values were of a character type, such as LONG
VARCHAR, a CAST can be applied to return human-readable values:

SELECT CAST ( DECOMPRESS ( Attachment, 'gzip' )


AS LONG VARCHAR ) FROM TableA;

Related Information

String functions [page 214]


COMPRESS function [String] [page 277]

SQL Anywhere - SQL Reference


328 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.3.2.65 DECRYPT function [String]

Decrypts the string using the supplied key and returns a LONG BINARY value.

Syntax

DECRYPT( string-expression, key [, algorithm-format [, initialization-vector ] ] )

algorithm-format :
algorithm [ ( format ) ]

algorithm :
AES
| AES256
| AES_FIPS
| AES256_FIPS
| RSA
| RSA_FIPS

format :
FORMAT={ RAW[; padding ] | INTERNAL }

padding :
PADDING={ PKCS5
| ZEROES
| OAEP
| PKCS1
| ALL
| NONE }

Parameters

string-expression

The string to be decrypted. Binary values are supported. This parameter is case sensitive, even in case-
insensitive databases.
key

The encryption key (string) that is required to decrypt the string-expression. For AES, this value must be
the same encryption key that was used to encrypt the string-expression to obtain the original value that
was encrypted. This parameter is case sensitive, even in case-insensitive databases.

Specify keys in PEM format for RSA.

Caution
For strongly encrypted databases, store a copy of the key in a safe location. If you lose the encryption key,
there is no way to access the data, even with the assistance of Technical Support. The database must be
discarded and you must create a new database.

algorithm-format

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 329
This optional string parameter specifies the type of algorithm, format, and padding that was used to encrypt
the string-expression.

algorithm

This optional string parameter specifies the type of algorithm originally used to encrypt the string-
expression. Specify one of the following formats:

AES

The data is encrypted using the AES algorithm.

If algorithm-format is not specified, then AES is used by default.

For the AES algorithm, padding can be PKCS5, ZEROES, or NONE. The default padding is PKCS5.
AES256 The data is encrypted using the AES 256-bit algorithm. For AES256, padding can be
PKCS5, ZEROES, and NONE (if FORMAT=RAW).
AES_FIPS

The data is encrypted using the FIPS-certified version of the AES algorithm.

If the database server was started using the -fips server option, AES_FIPS is used as the default. For
AES_FIPS, padding can be PKCS5, ZEROES, and NONE (if FORMAT=RAW).
AES256_FIPS The data is encrypted using the FIPS-certified version of the AES 256-bit algorithm.
For AES256_FIPS, padding can be PKCS5, ZEROES, and NONE (if FORMAT=RAW).
RSA

For the RSA algorithm, when encrypting with a public key, padding can be PKCS1, OAEP, or NONE.
When encrypting with a private key, padding must be PKCS1. The default padding is PKCS1.

If the RSA algorithm is specified, then the initialization-vector parameter is ignored and
FORMAT=RAW is ignored.

If a public key encrypts the message, then a private key must decrypt it. Using the same key for
encryption and decryption fails unless PADDING=NONE. However, if PADDING=NONE is set and the
incorrect key is supplied, then the function succeeds but returns meaningless data.

Note
The maximum message length for RSA encryption is equal to the key size minus 11 bytes for
PKCS1 padding and the key size minus 42 bytes for OAEP padding. If you specify
PADDING=NONE, then the message must be equal to the key size. Unlike AES, the length of the
output is not the same as the length of the input when using RSA encryption.

RSA_FIPS The same as RSA except that the data is encrypted using the FIPS-certified version of the
RSA algorithm.
FORMAT clause

Use the optional FORMAT clause to specify the storage format for the data. If the data was stored in the
proprietary storage format, then specify INTERNAL . If the encrypted data was stored as-is (that is, it can
be decrypted by any software that can decrypt the specified algorithm), then specify RAW. For data
stored as RAW, specify the initialization-vector parameter.
PADDING clause

Use the optional PADDING clause to specify the padding type for AES and RSA encryption. For AES
encryption, you must also specify FORMAT=RAW.

SQL Anywhere - SQL Reference


330 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
The padding type for decryption must match that used for encryption unless PADDING=ALL is used.

PKCS5

The data is padded by using the PKCS#5 algorithm. The encrypted data is 1-16 bytes longer than the
decrypted data. This option is only available for AES encryption.This is the default padding for AES
encryption.
ZEROES

The data is padded with zeros (0) before encryption. The encrypted data is 0-15 bytes longer than the
decrypted data. When the encrypted data is decrypted, the result is also padded with zeros.
OAEP The data is padded using Optimal Asymmetric Encryption Padding. This option is only available
for RSA encryption (RSA or RSA_FIPS).
PKCS1 The data is padded using the PKCS#1 algorithm. This option is only available for RSA
encryption (RSA or RSA_FIPS). This option is the default for RSA encryption (RSA or RSA_FIPS).
NONE

The data is not padded. The input data must be a multiple of the cipher block length (16-bytes) for
AES, or exactly equal to the key size for RSA.
ALL

Each valid padding type is attempted to be used until one of them works.
initialization-vector

Specify initialization-vector when format is set to RAW. The string cannot be longer than 16 bytes.
Any value less than 16 bytes is padded with 0 bytes. This string cannot be set to NULL. initialization-
vector is ignored when format is set to INTERNAL

Returns

LONG BINARY

Remarks

The DECRYPT function decrypts a string-expression that was encrypted with the ENCRYPT function. This
function returns a LONG BINARY value with the same number of bytes as the input string, unless the data is in raw
format. When FORMAT=RAW, the length of the returned value depends on the padding format.

For AES, to successfully decrypt a string-expression, use the same encryption key that was used to encrypt
the data. When FORMAT=RAW, use the same initialization vector and padding format that was used to encrypt
the data. Data in raw format can be decrypted outside of the database server.

For RSA, if you specify an incorrect encryption key, then an error is generated unless FORMAT=RAW is specified.
When you specify FORMAT=RAW and an incorrect encryption key or an incorrect initialization vector, the
decryption fails silently.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 331
Caution
For strongly encrypted data, store a copy of the key in a safe location. If you lose the encryption key, then there
is no way to access the data, even with the assistance of Technical Support.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following example decrypts a user's password from the user_info table. The CAST function is used to
convert the password back to a CHAR data type because the DECRYPT function converts values to the LONG
BINARY data type, which is unreadable.

SELECT CAST( DECRYPT( user_pwd, '8U3dkA' ) AS CHAR(100) ) FROM user_info;

The following example updates the secret column with an encrypted version of the password column. The
data is encrypted using encryption key 'TheEncryptionKey', raw-format AES encryption, and the initialization
vector 'ThisIsTheIV'. Default PKCS#5 padding is used.

CREATE OR REPLACE TABLE SensitiveData


(
username char(30), password char(30), secret binary(48)
);
INSERT INTO SensitiveData (username, password)
VALUES
('Martin', 'topXsecret1'),
('Jasmine', 'my_big_secret'),
('Aidan', 'Shortcutsmakelongdelays');
UPDATE SensitiveData
SET secret = ENCRYPT( password, 'TheEncryptionKey', 'AES(FORMAT=RAW)',
'ThisIsTheIV' );

The encrypted text in the secret column is decrypted using the DECRYPT function.

SELECT
username,
password,
CAST(DECRYPT( secret, 'TheEncryptionKey','AES(FORMAT=RAW;PADDING=PKCS5)',
'ThisIsTheIV' ) AS LONG VARCHAR)
AS revealed
FROM SensitiveData;

Related Information

String functions [page 214]


ENCRYPT function [String] [page 338]

SQL Anywhere - SQL Reference


332 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
ISENCRYPTED function [System] [page 411]

1.3.2.66 DEGREES function [Numeric]

Converts a number from radians to degrees.

Syntax

DEGREES( numeric-expression )

Parameters

numeric-expression

An angle in radians.

Returns

DOUBLE

Remarks

This function converts its argument to DOUBLE, performs the computation in double-precision floating-point
arithmetic, and returns the degrees of the angle given by numeric-expression. If the parameter is NULL, the
result is NULL.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the value 29.79380534680281:

SELECT DEGREES( 0.52 );

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 333
1.3.2.67 DENSE_RANK function [Ranking]

Calculates the rank of a value in a partition. For tied values, the DENSE_RANK function does not leave gaps in the
ranking sequence.

Syntax

DENSE_RANK( ) OVER ( window-spec )

window-spec : see the Remarks section below

Returns

INTEGER

Remarks

Elements of window-spec can be specified either in the function syntax (inline), or with a WINDOW clause in the
SELECT statement. When used as a window function, you must specify an ORDER BY clause, you may specify a
PARTITION BY clause, however, you cannot specify a ROWS or RANGE clause. More information is available in the
window-spec definition of the WINDOW clause.

Standards

ANSI/ISO SQL Standard

The DENSE_RANK function comprises part of optional ANSI/ISO SQL Language Feature T612, "Advanced
OLAP operations".

SQL Language Feature F441, "Extended set function support", which permits operands of window functions to
be arbitrary expressions that are not column references, is supported.

Optional ANSI/ISO SQL Feature F442, "Mixed column references in set functions" is not supported. The
software does not support the arguments of an aggregate function to include both a column reference from
the query block containing the DENSE_RANK function, combined with an outer reference.

Example
The following example returns a result set that provides a ranking of the employees' salaries in Utah and New
York. Although 19 records are returned in the result set, only 18 rankings are listed because of a 7th-place tie

SQL Anywhere - SQL Reference


334 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
between the 7th and 8th employee in the list, who have identical salaries. Instead of ranking the 9th employee
as '9', the employee is listed as '8' because the DENSE_RANK function does not leave gaps in the ranks.

SELECT DepartmentID, Surname, Salary, State,


DENSE_RANK() OVER (ORDER BY Salary DESC) AS SalaryRank
FROM GROUPO.Employees
WHERE State IN ('NY','UT');

Here is the result set:

DepartmentID Surname Salary State SalaryRank

100 Shishov 72995.000 UT 1

100 Wang 68400.000 UT 2

100 Cobb 62000.000 UT 3

400 Morris 61300.000 UT 4

300 Davidson 57090.000 NY 5

200 Martel 55700.000 NY 6

400 Blaikie 54900.000 NY 7

100 Diaz 54900.000 UT 7

100 Driscoll 48023.000 UT 8

400 Hildebrand 45829.000 UT 9

100 Whitney 45700.000 NY 10

100 Guevara 42998.000 NY 11

100 Soo 39075.000 NY 12

200 Goggin 37900.000 UT 13

400 Wetherby 35745.000 NY 14

400 Ahmed 34992.000 NY 15

500 Rebeiro 34576.000 UT 16

300 Bigelow 31200.000 UT 17

500 Lynch 24903.000 UT 18

Related Information

WINDOW clause [page 1413]


CUME_DIST function [Ranking] [page 301]
PERCENT_RANK function [Ranking] [page 468]
RANK function [Ranking] [page 482]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 335
1.3.2.68 DIFFERENCE function [String]

Returns the difference in the SOUNDEX values between the two string expressions.

Syntax

DIFFERENCE ( string-expression-1, string-expression-2 )

Parameters

string-expression-1

The first SOUNDEX argument.


string-expression-2

The second SOUNDEX argument.

Returns

SMALLINT

Remarks

The DIFFERENCE function compares the SOUNDEX values of two strings and evaluates the similarity between
them, returning a value from 0 through 4, where 4 is the best match.

This function always returns some value. The result is NULL only if one of the arguments are NULL.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns similarity between the words test and chest:

SELECT DIFFERENCE( 'test', 'chest' );

SQL Anywhere - SQL Reference


336 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Related Information

String functions [page 214]


SOUNDEX function [String] [page 536]

1.3.2.69 DOW function [Date and time]

Returns a number from 1 to 7 representing the day of the week of a date, where Sunday=1, Monday=2, and so on.

Syntax

DOW( date-expression )

Parameters

date-expression

The value (of type DATE) to be evaluated.

Returns

SMALLINT

Remarks

The DOW function is not affected by the value specified for the first_day_of_week database option. For example,
even if first_day_of_week is set to Monday, the DOW function returns a 2 for Monday.

Standards

ANSI/ISO SQL Standard

Not in the standard.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 337
Example
The following statement returns the value 5:

SELECT DOW( '1998-07-09' );

The following statement returns the value 1:

SELECT DOW( CAST( '2010/05/30 11:33:00.000000+04:00' as TIMESTAMP WITH TIME


ZONE ));

The following statement queries the Employees table and returns the employee StartDate, expressed as the
number of the day of the week:

SELECT DOW( StartDate ) FROM GROUPO.Employees;

1.3.2.70 ENCRYPT function [String]

Encrypts the specified value using the supplied encryption key and returns a LONG BINARY value.

Syntax

ENCRYPT( string-expression, key[, algorithm-format [, initialization-vector ] ] )

algorithm-format :
algorithm [ ( format-clause ) ]

algorithm :
AES
| AES256
| AES_FIPS
| AES256_FIPS
| RSA
| RSA_FIPS

format-clause :
FORMAT={ RAW[; padding-clause ] | INTERNAL }

padding-clause :
PADDING={ PKCS5
| ZEROES
| OAEP
| PKCS1
| ALL
| NONE }

SQL Anywhere - SQL Reference


338 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Parameters

string-expression

The string to be decrypted. Binary values are supported. This parameter is case sensitive, even in case-
insensitive databases.
key

The encryption key (string) that is required to decrypt the string-expression. For AES, this value must be
the same encryption key that was used to encrypt the string-expression to obtain the original value that
was encrypted. This parameter is case sensitive, even in case-insensitive databases.

Specify keys in PEM format for RSA.

Caution
For strongly encrypted databases, store a copy of the key in a safe location. If you lose the encryption key,
there is no way to access the data, even with the assistance of Technical Support. The database must be
discarded and you must create a new database.

algorithm-format

This optional string parameter specifies the type of algorithm, format, and padding to use when encrypting
the string-expression.

algorithm

This optional string parameter specifies the type of algorithm used to encrypt the string-expression.
Specify one of the following formats:

AES

The data is encrypted using the AES algorithm.

If algorithm-format is not specified, then AES is used by default.

For the AES algorithm, padding can be PKCS5, ZEROES, or NONE. The default padding is PKCS5.
AES256 The data is encrypted using the AES 256-bit algorithm. For AES256, padding can be
PKCS5, ZEROES, and NONE (if FORMAT=RAW).
AES_FIPS

The data is encrypted using the FIPS-certified version of the AES algorithm.

If the database server was started using the -fips server option, AES_FIPS is used as the default. For
AES_FIPS, padding can be PKCS5, ZEROES, and NONE (if FORMAT=RAW).
AES256_FIPS The data is encrypted using the FIPS-certified version of the AES 256-bit algorithm.
For AES256_FIPS, padding can be PKCS5, ZEROES, and NONE (if FORMAT=RAW).
RSA

For the RSA algorithm, when encrypting with a public key, padding can be PKCS1, OAEP, or NONE.
When encrypting with a private key, padding must be PKCS1. The default padding is PKCS1.

If the RSA algorithm is specified, then the initialization-vector parameter is ignored and
FORMAT=RAW is ignored.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 339
If a public key encrypts the message, then a private key must decrypt it. Using the same key for
encryption and decryption fails unless PADDING=NONE. However, if PADDING=NONE is set and the
incorrect key is supplied, then the function succeeds but returns meaningless data.

Note
The maximum message length for RSA encryption is equal to the key size minus 11 bytes for
PKCS1 padding and the key size minus 42 bytes for OAEP padding. If you specify
PADDING=NONE, then the message must be equal to the key size. Unlike AES, the length of the
output is not the same as the length of the input when using RSA encryption.

RSA_FIPS The same as RSA except that the data is encrypted using the FIPS-certified version of the
RSA algorithm.
FORMAT clause

Use the optional FORMAT clause to specify the storage format for the data. If the data was stored in the
proprietary storage format, then specify INTERNAL . If the encrypted data was stored as-is (that is, it can
be decrypted by any software that can decrypt the specified algorithm), then specify RAW. For data
stored as RAW, specify the initialization-vector parameter.
PADDING clause

Use the optional PADDING clause to specify the padding type for AES and RSA encryption. For AES
encryption, you must also specify FORMAT=RAW.

The padding type for decryption must match that used for encryption unless PADDING=ALL is used.

PKCS5

The data is padded by using the PKCS#5 algorithm. The encrypted data is 1-16 bytes longer than the
decrypted data. This option is only available for AES encryption.This is the default padding for AES
encryption.
ZEROES

The data is padded with zeros (0) before encryption. The encrypted data is 0-15 bytes longer than the
decrypted data. When the encrypted data is decrypted, the result is also padded with zeros.
OAEP The data is padded using Optimal Asymmetric Encryption Padding. This option is only available
for RSA encryption (RSA or RSA_FIPS).
PKCS1 The data is padded using the PKCS#1 algorithm. This option is only available for RSA
encryption (RSA or RSA_FIPS). This option is the default for RSA encryption (RSA or RSA_FIPS).
NONE

The data is not padded. The input data must be a multiple of the cipher block length (16-bytes) for
AES, or exactly equal to the key size for RSA.
initialization-vector

Specify initialization-vector when format is set to RAW. The string cannot be longer than 16 bytes.
Any value less than 16 bytes is padded with 0 bytes. This string cannot be set to NULL. initialization-
vector is ignored when format is set to INTERNAL

Returns

LONG BINARY

SQL Anywhere - SQL Reference


340 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Remarks

The LONG BINARY value returned by this function is up to 31 bytes longer than the input string-expression.
The value returned by this function is not human-readable. Use the DECRYPT function to decrypt a string-
expression that was encrypted with the ENCRYPT function. For AES, to successfully decrypt a string-
expression, use the same encryption key and algorithm that were used to encrypt the data. If you specify an
incorrect encryption key, then an error is generated. A lost key results in inaccessible data, from which there is no
recovery.

If you are storing encrypted values in a table, then the column should be BINARY or LONG BINARY so that
character set conversion is not performed on the data.

When FORMAT=RAW is specified, the data is encrypted using raw encryption. Specify the encryption key,
initialization vector, and, optionally, the padding format. These same values must be specified when decrypting
the data. The decryption can be performed outside of the database server or by using the DECRYPT function.

Do not use raw encryption when the data is to be encrypted and decrypted only within the database server
because you must specify the initialization vector and the padding, and the encryption key cannot be verified
during decryption.

Note
For the ISENCRYPTED function to return meaningful results, data must be encrypted using the ENCRYPT
function with AES/AES256 and must not use FORMAT=RAW.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following trigger encrypts the user_pwd column of the user_info table. This column contains users'
passwords, and the trigger fires whenever a password value is changed.

CREATE TRIGGER encrypt_updated_pwd


BEFORE UPDATE OF user_pwd
ON user_info
REFERENCING NEW AS new_pwd
FOR EACH ROW
BEGIN
SET new_pwd.user_pwd=ENCRYPT( new_pwd.user_pwd, '8U3dkA' );
END;

The following example updates the secret column with an encrypted version of the password column. The
data is encrypted using encryption key 'TheEncryptionKey', raw-format AES encryption, PKCS#5 padding (the
default), and the initialization vector 'ThisIsTheIV'.

CREATE OR REPLACE TABLE SensitiveData


(
username char(30), password char(30), secret binary(48)

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 341
);
INSERT INTO SensitiveData (username, password)
VALUES
('Martin', 'topXsecret1'),
('Jasmine', 'my_big_secret'),
('Aidan', 'Shortcutsmakelongdelays');
UPDATE SensitiveData
SET secret = ENCRYPT( password, 'TheEncryptionKey',
'AES(FORMAT=RAW;PADDING=PKCS5)', 'ThisIsTheIV' );
SELECT *, LENGTH(secret) FROM SensitiveData;

Related Information

DECRYPT function [String] [page 329]


ISENCRYPTED function [System] [page 411]

1.3.2.71 ERROR_LINE function [Miscellaneous]

Returns the line number of the procedure or batch where the error occurred that invoked the CATCH block of a
TRY...CATCH statement.

Syntax

ERROR_LINE( )

Returns

UNSIGNED INTEGER representing the line number within the stored procedure or the compound statement
where an error occurred.

Remarks

Call this function anywhere within a CATCH block. This function reports information about the current error when
it is invoked within an error handler, a nested compound statement, a function, or a procedure.

This function returns line numbers as found in the proc_defn column of the SYSPROCEDURE system table for the
procedure. These line numbers might differ from those of the source definition used to create the procedure.

SQL Anywhere - SQL Reference


342 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
When executed within a handler that was invoked by a division by zero error on line 15 of the procedure
u1.proc1, the following statement SELECT ERROR_LINE( ), ERROR_MESSAGE( ), ERROR_PROCEDURE( )
returns a result similar to the following one:

15, 'Division by zero', '"u1"."proc1"'

Related Information

TRY statement [page 1374]


BEGIN statement [page 749]
ERROR_MESSAGE function [Miscellaneous] [page 343]
ERROR_PROCEDURE function [Miscellaneous] [page 344]
ERROR_SQLCODE function [Miscellaneous] [page 346]
ERROR_SQLSTATE function [Miscellaneous] [page 347]
ERROR_STACK_TRACE function [Miscellaneous] [page 349]
STACK_TRACE function [Miscellaneous] [page 542]
sa_error_stack_trace system procedure [page 1509]
sa_stack_trace system procedure [page 1639]
SYSPROCEDURE system view [page 1832]
SYSPROCEDURE system view [page 1832]

1.3.2.72 ERROR_MESSAGE function [Miscellaneous]

Returns the message text of the error that invoked the CATCH block of a TRY...CATCH statement.

Syntax

ERROR_MESSAGE( )

Returns

VARCHAR containing the error message of the error that invoked the CATCH block.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 343
Remarks

Call this function anywhere within a CATCH block. This function returns the active error message anywhere in the
error handler, while the ERRORMSG function, when called with no parameters, only returns the error message
when invoked in the first statement of the error handler.

The parameters in the error message are replaced with actual values.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
When executed within a handler that was invoked by a division by zero error on line 15 of the procedure
u1.proc1, the following statement SELECT ERROR_LINE(), ERROR_MESSAGE(), ERROR_PROCEDURE()
returns the following result:

15, 'Division by zero', '"u1"."proc1"'

Related Information

TRY statement [page 1374]


BEGIN statement [page 749]
ERROR_LINE function [Miscellaneous] [page 342]
ERROR_PROCEDURE function [Miscellaneous] [page 344]
ERROR_SQLCODE function [Miscellaneous] [page 346]
ERROR_SQLSTATE function [Miscellaneous] [page 347]
ERROR_STACK_TRACE function [Miscellaneous] [page 349]
STACK_TRACE function [Miscellaneous] [page 542]
sa_error_stack_trace system procedure [page 1509]
sa_stack_trace system procedure [page 1639]

1.3.2.73 ERROR_PROCEDURE function [Miscellaneous]


Returns the name of the procedure within which the error that caused the exception handler to run occurred.

Syntax

ERROR_PROCEDURE( )

SQL Anywhere - SQL Reference


344 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Returns

VARCHAR containing the qualified name of the procedure where the exception has occurred. If the compound
statement is not part of a procedure, function, trigger, or event, the type of batch (<watcom_batch> or
<tsql_batch>) is returned instead of the procedure owner and name.

Remarks

ERROR_PROCEDURE can be called anywhere within an exception handler.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following batch illustrates division by zero exception handling.

BEGIN
DECLARE divTest INT;
SET divTest = 1 / 0;
SELECT 'No error';
EXCEPTION WHEN OTHERS THEN
SELECT 'Exception: SQLCODE = ' || ERROR_SQLCODE() ||
', SQLSTATE = ' || ERROR_SQLSTATE() ||
', PROCEDURE = ' || ERROR_PROCEDURE();
END;

The result of executing this batch is:

Exception: SQLCODE = -628, SQLSTATE = 22012, PROCEDURE = <watcom_batch>

The following procedure also illustrates division by zero exception handling.

CREATE OR REPLACE PROCEDURE ExceptionDemo()


BEGIN
DECLARE divTest INT;
SET divTest = 1 / 0;
SELECT 'No error';
EXCEPTION WHEN OTHERS THEN
SELECT 'Exception: SQLCODE = ' || ERROR_SQLCODE() ||
', SQLSTATE = ' || ERROR_SQLSTATE() ||
', PROCEDURE = ' || ERROR_PROCEDURE();
END;
CALL ExceptionDemo()

The result of executing this procedure is:

Exception: SQLCODE = -628, SQLSTATE = 22012, PROCEDURE = "DBA"."ExceptionDemo"

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 345
Related Information

TRY statement [page 1374]


BEGIN statement [page 749]
ERROR_LINE function [Miscellaneous] [page 342]
ERROR_MESSAGE function [Miscellaneous] [page 343]
ERROR_SQLCODE function [Miscellaneous] [page 346]
ERROR_SQLSTATE function [Miscellaneous] [page 347]
ERROR_STACK_TRACE function [Miscellaneous] [page 349]
STACK_TRACE function [Miscellaneous] [page 542]
sa_error_stack_trace system procedure [page 1509]

1.3.2.74 ERROR_SQLCODE function [Miscellaneous]

Returns the SQLCODE of the error that invoked the error handler.

Syntax

ERROR_SQLCODE( )

Returns

SIGNED INTEGER with the value of the SQLCODE of the error that invoked the error handler.

Remarks

This function can be called anywhere within an error handler.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following batch illustrates division by zero exception handling.

BEGIN

SQL Anywhere - SQL Reference


346 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
DECLARE divTest INT;
SET divTest = 1 / 0;
SELECT 'No error';
EXCEPTION WHEN OTHERS THEN
SELECT 'Exception: SQLCODE = ' || ERROR_SQLCODE() ||
', SQLSTATE = ' || ERROR_SQLSTATE() ||
', PROCEDURE = ' || ERROR_PROCEDURE();
END;

The result of executing this batch is:

Exception: SQLCODE = -628, SQLSTATE = 22012, PROCEDURE = <watcom_batch>

Related Information

TRY statement [page 1374]


BEGIN statement [page 749]
ERROR_LINE function [Miscellaneous] [page 342]
ERROR_MESSAGE function [Miscellaneous] [page 343]
ERROR_PROCEDURE function [Miscellaneous] [page 344]
ERROR_SQLSTATE function [Miscellaneous] [page 347]
ERROR_STACK_TRACE function [Miscellaneous] [page 349]
STACK_TRACE function [Miscellaneous] [page 542]
sa_error_stack_trace system procedure [page 1509]
sa_stack_trace system procedure [page 1639]

1.3.2.75 ERROR_SQLSTATE function [Miscellaneous]

Returns the SQLSTATE of the error that invoked the error handler.

Syntax

ERROR_SQLSTATE( )

Returns

CHAR(5) representing the SQLSTATE of the error that invoked the error handler.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 347
Remarks

This function can be called anywhere within an error handler.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following batch illustrates division by zero exception handling.

BEGIN
DECLARE divTest INT;
SET divTest = 1 / 0;
SELECT 'No error';
EXCEPTION WHEN OTHERS THEN
SELECT 'Exception: SQLCODE = ' || ERROR_SQLCODE() ||
', SQLSTATE = ' || ERROR_SQLSTATE() ||
', PROCEDURE = ' || ERROR_PROCEDURE();
END;

The result of executing this batch is:

Exception: SQLCODE = -628, SQLSTATE = 22012, PROCEDURE = <watcom_batch>

Related Information

TRY statement [page 1374]


BEGIN statement [page 749]
ERROR_LINE function [Miscellaneous] [page 342]
ERROR_MESSAGE function [Miscellaneous] [page 343]
ERROR_PROCEDURE function [Miscellaneous] [page 344]
ERROR_SQLCODE function [Miscellaneous] [page 346]
ERROR_STACK_TRACE function [Miscellaneous] [page 349]
STACK_TRACE function [Miscellaneous] [page 542]
sa_error_stack_trace system procedure [page 1509]
sa_stack_trace system procedure [page 1639]

SQL Anywhere - SQL Reference


348 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.3.2.76 ERROR_STACK_TRACE function [Miscellaneous]

Returns a calling sequence stack trace for the error that invoked the error handler.

Syntax

ERROR_STACK_TRACE( )

Returns

LONG VARCHAR representing the stack trace of the error that invoked the error handler. If the compound
statement is not part of a procedure, function, trigger, or event, the type of batch (<watcom_batch> or
<tsql_batch>) is returned instead of the procedure name.

Remarks

The result contains lines of text delimited by line feed (\n) characters. Each line of the returned value contains the
qualified procedure name or batch type (if any) of the statement on the stack, followed by the line number of the
statement. The last line of the returned value is not terminated by a line feed character.

This function returns line numbers as found in the proc_defn column of the SYSPROCEDURE system table for the
procedure. These line numbers might differ from those of the source definition used to create the procedure.

This function returns the same information as the sa_error_stack_trace system procedure.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following set of procedures (with line numbers added for illustration) can be used to obtain the error stack:

1 CREATE OR REPLACE PROCEDURE proc1()


2 BEGIN TRY
3 CALL proc2();
4 END TRY
5 BEGIN CATCH
6 SELECT * FROM sa_split_list(ERROR_STACK_TRACE(), '\n' );
7 END CATCH;
1 CREATE OR REPLACE PROCEDURE proc2()
2 BEGIN
3 CALL proc3();
4 END;

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 349
1 CREATE OR REPLACE PROCEDURE proc3()
2 BEGIN
3 DECLARE v INTEGER = 0;
4 SET v = 1 / v;
5 END;
CALL proc1();

This call returns the following result set:

line_num row_value
1 "DBA"."proc1" : 3
2 "DBA"."proc2" : 3
3 "DBA"."proc3" : 4

If RESIGNAL is used in the error handler, and the resignaled error is handled, the error stack reported in the
second handler contains the stack trace of the original error, the record of the RESIGNAL, and the stack of the
resignaled exception. For example:

CREATE OR REPLACE PROCEDURE proc1()


BEGIN TRY
BEGIN TRY
DECLARE v INTEGER = 0;
SET v = 1 / v;
END TRY
BEGIN CATCH
CALL proc2();
END CATCH
END TRY
BEGIN CATCH
SELECT * FROM sa_split_list(ERROR_STACK_TRACE(), '\n' );
END CATCH;
CREATE OR REPLACE PROCEDURE proc2()
BEGIN
CALL proc3();
END;
CREATE OR REPLACE PROCEDURE proc3()
BEGIN
RESIGNAL;
END;
CALL proc1();

This call returns the following result string:

line_num row_value
1 "DBA"."proc1" : 8
2 "DBA"."proc2" : 3
3 RESIGNAL: "DBA"."proc3" : 3
4 "DBA"."proc1" : 5

Related Information

TRY statement [page 1374]


BEGIN statement [page 749]
ERROR_LINE function [Miscellaneous] [page 342]
ERROR_MESSAGE function [Miscellaneous] [page 343]
ERROR_PROCEDURE function [Miscellaneous] [page 344]

SQL Anywhere - SQL Reference


350 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
ERROR_SQLCODE function [Miscellaneous] [page 346]
ERROR_SQLSTATE function [Miscellaneous] [page 347]
STACK_TRACE function [Miscellaneous] [page 542]
sa_error_stack_trace system procedure [page 1509]
sa_stack_trace system procedure [page 1639]
SYSPROCEDURE system view [page 1832]

1.3.2.77 ERRORMSG function [Miscellaneous]

Provides the error message for the current error, or for a specified SQLSTATE or SQLCODE value.

Syntax

ERRORMSG( [ sqlstate | sqlcode ] )

sqlstate: string

sqlcode: integer

Parameters

sqlstate

The SQLSTATE value for which the error message is to be returned.


sqlcode

The SQLCODE value for which the error message is to be returned.

Returns

VARCHAR containing the error message.

Remarks

If no argument is supplied, the error message for the current state is supplied. Any substitutions (such as table
names and column names) are made.

If an argument is supplied, the error message for the supplied SQLSTATE or SQLCODE is returned, with no
substitutions. Table names and column names are supplied as placeholders (%1).

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 351
Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the error message for SQLCODE -813:

SELECT ERRORMSG( -813 );

1.3.2.78 ESTIMATE function [Miscellaneous]

Returns selectivity estimates as a percentage calculated by the query optimizer, based on specified parameters.

Syntax

ESTIMATE( column-name [, value [, relation-string ] ] )

Parameters

column-name

The column used in the estimate.


value

The value to which the column is compared. The default is NULL.


relation-string

The comparison operator used for the comparison, enclosed in single quotes. Possible values for this
parameter are: '=' , '>' , '<' , '>=' , '<=' , '<>' , '!=' , '!<' , and '!>'. The default is '='.

Returns

REAL

SQL Anywhere - SQL Reference


352 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Remarks

This function returns selectivity estimates for the predicate column-name relation-string value. If value
is NULL and the relation string is '=', the selectivity is for the predicate column-name IS NULL. If value is NULL
and the relation string is '!=' or '<>', the selectivity is for the predicate column-name IS NOT NULL.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns the percentage of EmployeeID values estimated to be greater than 200. The
precise value depends on the actions you have carried out on the database.

SELECT FIRST ESTIMATE( EmployeeID, 200, '>' )


FROM GROUPO.Employees
ORDER BY 1;

Related Information

INDEX_ESTIMATE function [Miscellaneous] [page 406]


ESTIMATE_SOURCE function [Miscellaneous] [page 353]
EXPERIENCE_ESTIMATE function [Miscellaneous] [page 362]

1.3.2.79 ESTIMATE_SOURCE function [Miscellaneous]

Provides the source for selectivity estimates used by the query optimizer.

Syntax

ESTIMATE_SOURCE(
column-name
[, value
[, relation-string ] ]
)

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 353
Parameters

column-name

The name of the column that is being investigated.


value

The value to which the column is compared. The default is NULL.


relation-string

The comparison operator used for the comparison, enclosed in single quotes. Possible values for this
parameter are: '=' , '>' , '<' , '>=' , '<=' , '<>' , '!=' , '!<' , and '!>'. The default is '='.

Returns

The following list shows the selectivity estimate sources that ESTIMATE_SOURCE returns.

Value Selectivity estimate source

Statistics Stored column statistics

Column Average of all values stored in the column statistics

Index Index probes

Guess Built-in guesses that are defined for each type of predicate.
This is returned only when there is no relevant index to use, no
statistics have been collected for the referenced columns, or
the predicate is a complex predicate.

Computed Other sources than the ones described above

Always Returned when the specified predicate is always true

Combined One or more of the above sources

Bounded Returned when there are upper and/or lower bounds placed
on the selectivity estimate

Remarks

This function returns the source of the selectivity estimate for the predicate column-name relation-string
value. If value is NULL and the relation string is '=', the selectivity source is for the predicate column-name IS
NULL. If value is NULL and the relation string is '!=' or '<>', the selectivity source is for the predicate column-
name IS NOT NULL.

Standards

ANSI/ISO SQL Standard

SQL Anywhere - SQL Reference


354 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Not in the standard.

Example
The following statement returns the selectivity source Index for evaluating whether the first value in the
EmployeeID column is greater than 200. Returning Index means that the query optimizer used an index to
estimate the selectivity.

SELECT FIRST ESTIMATE_SOURCE( EmployeeID, 200, '>' )


FROM GROUPO.Employees
ORDER BY 1;

Related Information

ESTIMATE function [Miscellaneous] [page 352]


INDEX_ESTIMATE function [Miscellaneous] [page 406]

1.3.2.80 EVENT_CONDITION function [System]

Specifies when an event handler is triggered.

Syntax

EVENT_CONDITION( condition-name )

Parameters

condition-name

The condition triggering the event. The possible values are preset in the database, and are case insensitive.
Each condition is valid only for certain event types. The conditions and the events for which they are valid are
as follows:

Condition name Units Valid for... Comments

DBFreePercent n/a DBDiskSpace The percentage of free disk


space remaining for the da­
tabase

DBFreeSpace MB DBDiskSpace The free disk space available


for the database in mega­
bytes

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 355
Condition name Units Valid for... Comments

DBSize MB GrowDB The size of the database in


megabytes

ErrorNumber n/a RAISERROR The error code number

IdleTime seconds ServerIdle The time that the server is


idle in seconds

Interval seconds All Time since handler last exe­


cuted

LogFreePercent n/a LogDiskSpace The percentage of free disk


space remaining for the log.

LogFreeSpace MB LogDiskSpace The free disk space remain­


ing for the log in megabytes.

LogSize MB GrowLog The size of the log in mega­


bytes

RemainingValues integer GlobalAutoincrement The number of remaining


values

TempFreePercent n/a TempDiskSpace The percentage of free disk


space in the temporary file
space

TempFreeSpace MB TempDiskSpace The free disk space available


for the temporary file space
in megabytes

TempSize MB GrowTemp The size of the temporary


file space in megabytes

Returns

INT

Remarks

The EVENT_CONDITION function returns NULL when not called from an event.

Standards

ANSI/ISO SQL Standard

Not in the standard.

SQL Anywhere - SQL Reference


356 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Example
The following event definition uses the EVENT_CONDITION function:

CREATE EVENT LogNotifier


TYPE LogDiskSpace
WHERE event_condition( 'LogFreePercent' ) < 50
HANDLER
BEGIN
MESSAGE 'LogNotifier message'
END;

Related Information

CREATE EVENT statement [page 808]

1.3.2.81 EVENT_CONDITION_NAME function [System]

Lists the possible parameters for EVENT_CONDITION.

Syntax

EVENT_CONDITION_NAME( integer )

Parameters

integer

Must be greater than or equal to zero.

Returns

VARCHAR

Remarks

You can use the EVENT_CONDITION_NAME function to obtain a list of all arguments for the EVENT_CONDITION
function by looping over integers until the function returns NULL.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 357
The EVENT_CONDITION_NAME function returns NULL when not called from an event.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Related Information

CREATE EVENT statement [page 808]

1.3.2.82 EVENT_PARAMETER function [System]

Provides context information for event handlers.

Syntax

EVENT_PARAMETER( context-name )

context-name :
AppInfo
| ConnectionID
| DisconnectReason
| EventName
| Executions
| MirrorServerName
| NumActive
| ScheduleName
| SQLCODE
| TableName
| User
| condition-name

Parameters

context-name

One of the preset strings. The strings must be quoted, are case insensitive, and carry the following
information:

AppInfo

SQL Anywhere - SQL Reference


358 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
The value of the AppInfo connection property for the connection that caused the event to be triggered.
Use the following statement to see the value of the property outside the context of the event:

SELECT CONNECTION_PROPERTY( 'AppInfo' );

The AppInfo string contains the computer name and application name of the client connection for
Embedded SQL, ODBC, OLE DB, ADO.NET, and SQL Anywhere JDBC driver connections.
ConnectionID

The connection ID of the connection that caused the event to be triggered.


DisconnectReason

A string indicating the reason the connect was terminated. This parameter is valid only for Disconnect
events. Possible results include:

abnormal

A disconnect occurred as a result of the client application terminating abnormally before


disconnecting from the database, or as a result of a communication failure between the client and
server computers.
connect failed

A connection attempt failed.


drop connection

A DROP CONNECTION statement was executed.


from client

The client application disconnected.


inactive

No requests were received for the period specified by the -ti server option.
liveness

No liveness packets were received for the period specified by the -tl server option.
EventName

The name of the event that has been triggered.


Executions

The number of times the event handler has been executed.


MirrorServerName

The name of the mirror or arbiter server that lost its connection to the primary server in a database
mirroring system.
NumActive

The number of active instances of an event handler. This is useful for limiting an event handler so that
only one instance executes at any given time.
ScheduleName

The name of the schedule which caused an event to be fired. If the event was fired manually using
TRIGGER EVENT or as a system event, the result will be an empty string. If the schedule was not assigned
a name explicitly when it was created, its name is the name of the event.
SQLCODE

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 359
The SQLCODE of the error that occurred during a failed connection. This parameter is valid only for
ConnectFailed events.
TableName

The name of the table, for use with RemainingValues.


User

The user ID for the user that caused the event to be triggered.

In addition, you can access any of the valid condition-name arguments to the EVENT_CONDITION function
from the EVENT_PARAMETER function.

The following table indicates which context-name values are valid for which system event types.

System event types Context-name value

BackupEnd AppInfo, ConnectionID, EventName, Executions, NumAc­


tive, User

Connect AppInfo, ConnectionID, EventName, Executions, NumAc­


tive, User

ConnectFailed AppInfo, EventName, Executions, NumActive, SQLCODE,


User

"Disconnect" AppInfo, ConnectionID, EventName, Executions, NumAc­


tive, User

GlobalAutoincrement ConnectionID, EventName, Executions, NumActive, Table­


Name, User

"RAISERROR" AppInfo, ConnectionID, EventName, Executions, NumAc­


tive, User

User events AppInfo, ConnectionID, EventName, Executions, NumAc­


tive, User

Returns

VARCHAR

Remarks

The maximum size of values passed to an event is limited by the maximum page size for the server (-gp server
option). Values that are longer are truncated to be less than the maximum page size.

Standards

ANSI/ISO SQL Standard

SQL Anywhere - SQL Reference


360 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Not in the standard.

Example
The following example shows how to pass a string parameter to an event. The event displays the time it was
triggered in the database server messages window.

CREATE EVENT ev_PassedParameter


HANDLER
BEGIN
MESSAGE 'ev_PassedParameter - was triggered at ' || event_parameter( 'time' );
END;
TRIGGER EVENT ev_PassedParameter( "Time"=string(current timestamp ) );

The following example uses the => parameter syntax instead:

CREATE EVENT ev_PassedParameter


HANDLER
BEGIN
MESSAGE 'ev_PassedParameter - was triggered at ' ||
event_parameter( 'what_time' );
END;
TRIGGER EVENT ev_PassedParameter( what_time => string( current timestamp ) );

Related Information

EVENT_CONDITION function [System] [page 355]


CREATE EVENT statement [page 808]
TRIGGER EVENT statement [page 1369]

1.3.2.83 EXP function [Numeric]

Returns the result of the base of natural logarithms e raised to the power of the given argument.

Syntax

EXP( numeric-expression )

Parameters

numeric-expression

The exponent.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 361
Returns

DOUBLE

Remarks

The EXP function returns the result of raising the base of natural logarithms e by the value specified by numeric-
expression.

This function converts its argument to DOUBLE, performs the computation in double-precision floating-point
arithmetic, and returns a DOUBLE as the result. If the parameter is NULL, the result is NULL.

Standards

ANSI/ISO SQL Standard

The EXP function comprises part of optional ANSI/ISO SQL Language Feature T621, "Enhanced numeric
functions".

Example
The statement returns the value 3269017.3724721107:

SELECT EXP( 15 );

1.3.2.84 EXPERIENCE_ESTIMATE function [Miscellaneous]

Returns selectivity estimates as a percentage calculated by the query optimizer, based on specified parameters.

Syntax

EXPERIENCE_ESTIMATE(
column-name
[, value
[, relation-string ] ]
)

Parameters

column-name

SQL Anywhere - SQL Reference


362 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
The name of the column that is being investigated.
value

The value to which the column is compared.


relation-string

The comparison operator used for the comparison. Possible values for this parameter are: '=' , '>' , '<' , '>=' ,
'<=' , '<>' , '!=' , '!<' , and '!>'. The default is '='.

Returns

REAL

Remarks

If value is NULL then the relation strings = and != are interpreted as the IS NULL and IS NOT NULL conditions,
respectively.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns 90.3262405396:

SELECT DISTINCT EXPERIENCE_ESTIMATE( EmployeeID, 200, '>' )


FROM GROUPO.Employees;

Related Information

ESTIMATE function [Miscellaneous] [page 352]


INDEX_ESTIMATE function [Miscellaneous] [page 406]
ESTIMATE_SOURCE function [Miscellaneous] [page 353]

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 363
1.3.2.85 EXPLANATION function [Miscellaneous]

Returns the optimization strategy of a SQL statement as a plain text string.

Syntax

EXPLANATION(
string-expression
[ , cursor-type ]
[, update-status ]
)

UltraLite:

EXPLANATION( string-expression )

Parameters

string-expression

The SQL statement, which is commonly a SELECT statement, but can also be an UPDATE, MERGE, or
DELETE statement.
cursor-type

A cursor type, expressed as a string. Possible values are asensitive, insensitive, sensitive, or keyset-driven. If
cursor-type is not specified, asensitive is used by default.
update-status

A string parameter accepting one of the following values indicating how the optimizer should treat the given
cursor:

Value Description

READ-ONLY The cursor is read-only.

READ-WRITE (default) The cursor can be read or written to.

FOR UPDATE The cursor can be read or written to. This is the same as
READ-WRITE.

Returns

LONG VARCHAR

SQL Anywhere - SQL Reference


364 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
Remarks

The execution plan for the query, returned as a string.

The GRAPHICAL_PLAN function offers significantly greater information about access plans, including system
properties that may have affected how the statement was optimized.

This information can help you decide which indexes to add or how to structure your database for better
performance.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement passes a SELECT statement as a string parameter and returns the plan for executing
the query:

SELECT EXPLANATION( 'SELECT * FROM Departments WHERE DepartmentID > 100' );

The following statement returns a string containing the short form of the text plan for an INSENSITIVE cursor
over the query SELECT * FROM Departments WHERE ...':

SELECT EXPLANATION( 'SELECT * FROM GROUPO.Departments WHERE DepartmentID > 100',


'insensitive', 'read-only' );

Related Information

PLAN function [Miscellaneous] [page 470]


GRAPHICAL_PLAN function [Miscellaneous] [page 378]

1.3.2.86 EXPRTYPE function [Miscellaneous]

Returns a string that identifies the data type of an expression.

Syntax

EXPRTYPE( string-expression, integer-expression )

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 365
Parameters

string-expression

A SELECT statement. The expression whose data type is to be queried must appear in the SELECT list. If the
string is not a valid SELECT statement, NULL is returned.
integer-expression

The position in the SELECT list of the desired expression. The first item in the SELECT list is numbered 1. If the
integer-expression value does not correspond to a SELECT list item, NULL is returned.

Returns

LONG VARCHAR

Remarks

For user-defined domains, EXPRTYPE returns the description of the underlying data type, not the domain name.
For example, suppose you create a domain, mydomain, and define a table column using mydomain, as follows:

CREATE DOMAIN mydomain CHAR(20);


CREATE TABLE mytable( colA mydomain, colB DATETIME );

When you execute SELECT EXPRTYPE( 'SELECT * FROM mytable', 1 ), the data type returned is char(20),
not mydomain.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
The following statement returns smallint when executed against the SQL Anywhere sample database:

SELECT EXPRTYPE( 'SELECT LineID FROM SalesOrderItems', 1 );

Related Information

SQL data types [page 126]

SQL Anywhere - SQL Reference


366 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
sa_describe_query system procedure [page 1496]

1.3.2.87 EXTENDED_PROPERTY function [System]

Returns the value of the given database server property. Allows an optional property-specific string parameter to
be specified.

Syntax

EXTENDED_PROPERTY(
{ property-id | property-name }
[, property-specific-argument]
)

Parameters

property-id

An integer that is the property number of the database server property. This number can be determined from
the PROPERTY_NUMBER function. The property-id is commonly used when looping through a set of
properties.
property-name

The database server property name to query.

HasSecureFeatureKey

Specify a list of features to determine whether the database server has a secured feature key that unlocks
all of the features in the list. Returns NULL if property-specific-argument is NULL; otherwise
returns Yes or No.
HasSecuredFeature

Specify a list of features to determine whether any of the specified features is secured at the global server
level. Returns NULL if property-specific-argument is NULL; otherwise returns Yes or No.
property-specific-argument

The following database server properties allow you to specify additional arguments, as noted below, to return
specific information about the property.

HasSecureFeatureKey feature-list

Specify a list of features to determine whether there is a secure feature key that unlocks all of the features
in feature-list.
HasSecuredFeature feature-list

Specify a list of features to determine whether at least one of these features is secured.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 367
Returns

VARCHAR, LONG VARCHAR

Remarks

The EXTENDED_PROPERTY function is similar to the PROPERTY function except that it allows an optional
property-specific-argument string parameter to be specified. The interpretation of property-specific-
argument depends on the property ID or name specified in the first argument.

Privileges

No privileges are required to execute this function.

NULL is returned if you specify an invalid parameter value.

Standards

ANSI/ISO SQL Standard

Not in the standard.

Example
Execute the following statement to determine whether the xp_cmdshell system procedure can be used on the
current connection without requiring a key:

SELECT EXTENDED_PROPERTY( 'HasSecuredFeature', 'cmdshell' );

If the CMDSHELL feature is not secured, the statement returns No. If the CMDSHELL feature is secured and a
secured feature key is required to access the feature, the statement returns Yes.

Execute the following statement to determine whether there is a secured feature key that allows access to the
CMDSHELL feature:

SELECT EXTENDED_PROPERTY( 'HasSecureFeatureKey', 'cmdshell' );

If there is no secured feature key available, the statement returns No. If there is a secured feature key that
would permit access to this feature, the statement returns Yes.

Execute the following statement to determine whether the current connection can perform BACKUP and
RESTORE statements without requiring a key..

SELECT EXTENDED_PROPERTY( 'HasSecuredFeature', 'backup,restore' );

SQL Anywhere - SQL Reference


368 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
If none of the features are secured, the statement returns No. If any feature is secured, the statement returns
Yes. To determine if both features are secured, execute the following statement and check both results.

SELECT EXTENDED_PROPERTY( 'HasSecuredFeature', 'backup' ) AS [backup],


EXTENDED_PROPERTY( 'HasSecuredFeature', 'restore' ) AS [restore];

Execute the following statement to determine whether there is a secure feature key that allows the current
connection to perform BACKUP and RESTORE statements.

SELECT EXTENDED_PROPERTY( 'HasSecureFeatureKey', 'backup,restore' );

If there is a key that enables both features, the statement returns Yes. If any feature cannot be enabled by at
least one key, the statement returns No.

Related Information

PROPERTY function [System] [page 472]

1.3.2.88 EXTRACT function [Date and time]

Returns a date part from a TIMESTAMP expression.

Syntax

EXTRACT( date-part FROM timestamp-expression )

Parameters

date-part

The date part to be returned. The valid values are YEAR, MONTH, DAY, HOUR, MINUTE, SECOND,
TIMEZONE_HOUR, and TIMEZONE_MINUTE.
timestamp-expression

The TIMESTAMP or TIMESTAMP WITH TIME ZONE value.

Returns

If date-part is SECOND, then the function returns a NUMERIC value that includes the fractional second (up to
microsecond precision). For all other date-part values, the function returns an INTEGER.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 369
Remarks

The EXTRACT function is similar to the DATEPART function but not completely. The EXTRACT function accepts
only a subset of date parts. Also, the two functions return different values when date-part is SECOND.

Standards

ANSI/ISO SQL Standard

Core feature.

Example
The following statement returns 56.789000:

SELECT EXTRACT( SECOND FROM '2015-07-01 12:34:56.789000' );

The following statement returns 30:

SELECT EXTRACT( TIMEZONE_MINUTE FROM '2015-07-01 12:34:56.789000 +05:30' );

The following statement returns 5:

SELECT EXTRACT( TIMEZONE_HOUR FROM '2015-07-01 12:34:56.789000 +05:30' );

Related Information

Specifying date parts [page 208]


SET statement [T-SQL] [page 1330]
MICROSECOND function [Date and time] [page 436]
DATEPART function [Date and time] [page 311]
MILLISECOND function [Date and time] [page 437]

1.3.2.89 FIRST_VALUE function [Aggregate]

Returns values from the first row of a window.

Syntax

FIRST_VALUE( [ ALL ] expression [ { RESPECT | IGNORE } NULLS ] )


OVER ( window-spec )

SQL Anywhere - SQL Reference


370 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
window-spec : see the Remarks section below

Parameters

expression

The expression to evaluate. For example, a column name.

Returns

Data type of the values from the first row of a window.

Remarks

The FIRST_VALUE function allows you to select the first value (according to some ordering) in a table, without
having to use a self-join. This is valuable when you want to use the first value as the baseline in calculations.

The FIRST_VALUE function takes the first record from the window. Then, the expression is computed against
the first record and results are returned.

If IGNORE NULLS is specified, the first non-NULL value of expression is returned. If RESPECT NULLS is
specified (the default), the first value is returned whether or not it is NULL.

The FIRST_VALUE function is different from most other aggregate functions in that it can only be used with a
window specification.

Elements of window-spec can be specified either in the function syntax (inline), or with a WINDOW clause in the
SELECT statement. More information is provided in the window-spec definition of the WINDOW clause.

Standards

ANSI/ISO SQL Standard

Not in the standard. The software supports ANSI/ISO SQL Language Feature F441, "Extended set function
support", which permits operands of window functions to be arbitrary expressions that are not column
references.

The software does not support optional ANSI/ISO SQL Feature F442, "Mixed column references in set
functions". Also, the software does not permit the arguments of an aggregate function to include both a
column reference from the query block containing the FIRST_VALUE function, combined with an outer
reference.

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 371
Example
The following example returns the relationship, as a percentage, between each employee's salary and that of
the most recently hired employee in the same department:

SELECT DepartmentID, EmployeeID,


100 * Salary / ( FIRST_VALUE( Salary ) OVER (
PARTITION BY DepartmentID ORDER BY StartDate DESC ) )
AS percentage
FROM GROUPO.Employees;

DepartmentID EmployeeID percentage

500 1658 100

500 1615 110.4284624

500 1570 138.8427097

500 1013 109.5851905

500 921 167.4497049

500 868 113.2393688

500 750 137.7344095

500 703 222.8679276

500 191 119.6642975

400 1751 100

400 1740 99.705647

400 1684 130.969936

400 1643 83.9734797

400 1607 175.1828989

400 1576 197.0164609

... ... ...

Employee 1658 is the first row for department 500, indicating that they are the most recent hire in that
department and their percentage is 100%. Percentages for the remaining department 500 employees are
calculated relative to that of employee 1658. For example, employee 1570 earns approximately 139% of what
employee 1658 earns.

If another employee in the same department makes the same salary as the most recent hire, they will have a
percentage of 100 as well.

Related Information

WINDOW clause [page 1413]


LAST_VALUE function [Aggregate] [page 415]

SQL Anywhere - SQL Reference


372 © 2016 SAP SE or an SAP affiliate company. All rights reserved. SQL Anywhere Server - SQL Reference
1.3.2.90 FLOOR function [Numeric]

Returns the largest integer not greater than the given number.

Syntax

FLOOR( numeric-expression )

Parameters

numeric-expression

The value to be truncated, typically a fixed numeric type with non-zero scale or an approximate numeric type
(DOUBLE, REAL, or FLOAT).

Returns

DOUBLE

Remarks

This function converts its arguments to DOUBLE, and performs the computation in double-precision floating-
point arithmetic.

Standards

ANSI/ISO SQL Standard

The FLOOR function comprises part of optional ANSI/ISO SQL Language Feature T621, "Enhanced numeric
functions".

Example
The following statement returns a Floor value of 123:

SELECT FLOOR (123);

The following statement returns a Floor value of 123:

SELECT FLOOR (123.45);

SQL Anywhere - SQL Reference


SQL Anywhere Server - SQL Reference © 2016 SAP SE or an SAP affiliate company. All rights reserved. 373
The following statement returns a Floor value of -124:

SELECT FLOOR (-123.45);

Related Inf