SQL Reference en
SQL Reference en
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:
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.
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;
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.
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:
● 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
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.
● 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:
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 (`...`):
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:
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:
Related Information
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.
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.
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]'):
The following example shows how to use indirect identifiers to query a table:
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.
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
1.1.3 Strings
● 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.
Byte 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
1.1.4 Constants
In this section:
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:
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:
The following argument returns an error because the 10-digit value cannot be represented as a signed 32-bit
integer:
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 argument returns an error because the argument represents a positive integer value that cannot be
represented as a signed 32-bit integer:
Related Information
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:
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.
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
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:
Related Information
Operator Description
= Equal to
!= Not equal to
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.
Trailing blanks
The behavior of the database server when comparing strings is set at database creation.
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
When using AND, the combined condition is TRUE if both conditions are TRUE, FALSE if either condition is
FALSE, and UNKNOWN otherwise.
OR operator
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:
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:
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.
Related Information
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.
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:
The result is the number of days between expression1 and expression2, which could also be expressed as
( DATEDIFF ( day, expression1,expression2 ) ).
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
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:
Standards
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(
xml-data
, xpath
[, flags
[, namespaces ] ]
)
WITH ( column-name column-type
[ xpath ] [ , ... ]
)
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 .
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
Value Description
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 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 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.
● 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 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.
ProductName ProductID
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, &, Sweater, and Set. You can use a period (.) to
concatenate the children together in the result set.
ProductName ProductID
The following query uses an equality predicate to generate a result set from the supplied XML document.
The following query uses the XPath @attribute expression to generate a result set:
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.
Related Information
expression || expression
Array concatenation (two vertical bars). If either array is NULL, it is treated as a zero-length array for
concatenation.
Standards
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.
Creates a derived table from the given array expressions that results in one row per array element.
Syntax
Parameters
array-expression
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
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:
300
301
302
400
401
500
501
600
601
700
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:
X Y Z
300 28 1
301 54 2
302 75 3
400 112 4
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:
The following statement returns the data in the array and row together:
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
10 601 9
10 700 10
The following statement returns the first values in the array and row:
a1 x2.b1[[1]]
10 300
The following statements create an array of ROW and populate it with data
expression
300
301
302
400
401
500
501
600
601
700
Related Information
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 OR
^ bitwise exclusive OR
~ bitwise NOT
The bitwise operators &, | and ~ are not interchangeable with the logical operators AND, OR, and NOT.
Standards
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;
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.
The operators at the top of the following list are evaluated before those at the bottom of the list.
When you use more than one operator in an expression, make the order of operation explicit using parentheses.
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
constant :
integer | number | string | host-variable
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 formed from several different kinds of elements. These are discussed in the sections on functions
and variables.
Side effects
None.
In this section:
Related Information
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.
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]
A subquery is a SELECT statement that is nested inside another SELECT, INSERT, UPDATE, or DELETE
statement, or another subquery.
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
IF condition
THEN expression1
[ ELSE expression2 ]
{ ENDIF | END IF }
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
Related Information
The CASE expression provides conditional SQL expressions. Case expressions can be used anywhere an
expression can be used.
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;
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.
The NULLIF function provides a way to write some CASE clauses in short form. The syntax for NULLIF is as
follows:
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
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
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:
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 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.
In this section:
Metacharacters are symbols or characters that have a special meaning within a regular expression.
● 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.
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.
{} 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}
Related Information
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.
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.
SELECT City
FROM GROUPO.Contacts
WHERE City REGEXP
'.*[[:space:]].*';
[[:graph:]] is equivalent to
[[:alnum:][:punct:]].
[[:print:]] is equivalent to
[[:graph:][:whitespace:]].
[[:word:]] is equivalent to
[[:alnum:]_].
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.
SELECT Name
FROM GROUPO.Products
WHERE Name REGEXP '.*\\s.*'
SELECT Surname
FROM GROUPO.Contacts
WHERE Surname REGEXP '\\w{7}';
Equivalent to [[:alnum:]_]..
Equivalent to \x{hh}.
\x{ hhh } Matches the character whose value is 0xhhh, where hhh is, at
most, eight hex digits.
Equivalent to $.
Equivalent to $.
Related Information
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:
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:
● 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})
Syntax Meaning
Related Information
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, '.+@.+\\..+')
Credit Card Numbers (REGEXP only): Matches (Visa): 4123 6453 2222 1746
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}
HTML Hexadecimal Color Codes (REGEXP and SIMILAR Matches: AB1234, CCCCCC, 12AF3B
TO):
Non-Matches: 123G45, 12-44-CC
[A-F0-9]{6}
Java Comments (REGEXP only): Matches Java comments that are between /* and */, or one
line comments prefaced by //.
/\*.*\*/|//[^\n]*
Non-Matches: a=1
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
Phone Numbers (REGEXP and SIMILAR TO): Matches: 519-883-6898, 519 888 6898
Related Information
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:
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.
The following statement changes the setting of the quoted_identifier option to On:
The following statement changes the setting of the quoted_identifier option to Off:
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.
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
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 ] [ ... ]
comparison-operator :
=
| >
| <
| >=
| <=
| <>
| !=
| !<
| !>
trigger-operation :
INSERTING
| DELETING
| UPDATING [ ( column-name-string ) ]
| UPDATE( column-name )
Parameters
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.
The LIKE, SIMILAR TO, and REGEXP search conditions are very similar.
Prerequisites
Side effects
None.
In this section:
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.
Related Information
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
Core Feature.
Related Information
Use the ALL search condition to compare a value to all values in a set.
Syntax
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...
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
Core Feature.
Use the ANY or SOME search condition to compare a value to any value in a set.
Syntax
comparison-operator:
=
| >
| <
| >=
| <=
| <>
| !=
| !<
| !>
Remarks
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...
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.
Core Feature.
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
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:
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:
Standards
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".
Use the BETWEEN search condition to evaluate whether a value is between values in another set.
Syntax
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.
Standards
Core Feature.
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.
● 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).
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.
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:
Related Information
Syntax
The syntax for the LIKE search condition is as follows:
expression
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.
[^] Any single character not in the specified range or set. For ex
ample, M[^c] matches Mb and Md, but not Mc.
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.
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.
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.
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.
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.
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.
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 [.
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.
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).
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
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
Syntax
Parameters
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:]]'.
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.
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
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
Syntax
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'.
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.
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.
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
Related Information
Syntax
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 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
Core Feature.
Use the CONTAINS search condition to evaluate whether a value is contained in a set.
Syntax
contains-query-string :
simple-expression
| or-expression
simple-expression :
primary-expression
| and-expression
or-expression :
simple-expression { OR | | } contains-query-string
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
Parameters
and-expression
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 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:
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:
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.
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.
During query evaluation, expressions are evaluated using the following order of precedence:
1. FUZZY, NEAR
2. AND NOT
3. AND
4. OR
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".
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.
'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.
Note
Interpretation of query strings containing asterisks can vary depending on the text configuration object
settings.
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 -best' 'the AND NOT best', 'the AND Find the term the, and not the term 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.
'wild - west' 'wild west', and 'wild AND Find the term wild, and the term west.
west'
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.
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.
square brackets [ ] Square brackets are used with the keyword NEAR to contain
distance. Other uses of square brackets return an error.
Related Information
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
Core Feature.
Use the IS NULL search condition to evaluate whether a value in a set is NULL.
Syntax
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
Core Feature.
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
The following tables display how the AND, OR, NOT, and IS logical operators of SQL work in three-valued logic.
AND operator
OR operator
NOT operator
IS operator
Core Feature. Truth value tests, such as IS UNKNOWN, comprise SQL Language Feature F571.
Related Information
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.
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
Related Information
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:
Data type
string
Remarks
During an UPDATE operation, columns with a default value of CURRENT DATABASE are not changed.
Standards
Related Information
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
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 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.
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
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
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
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.
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.
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.
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
Not in the ANSI/ISO SQL Standard. In the standard, the special register that defines the present timestamp is
called CURRENT_TIMESTAMP.
CURRENT TIME returns the present hour, minute, second, and fraction of a second.
Data type
TIME
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
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 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
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.
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.
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 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
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.
Standards
Not in the ANSI/ISO SQL Standard. In the standard, the special register that defines the current user is called
CURRENT_USER.
Related Information
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
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
Not in the standard. However, the TIMESTAMP WITH TIME ZONE data type is optional ANSI/ISO SQL
Language Feature F41.
Related Information
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.
Standards
Related Information
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.
Standards
Related Information
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 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
Related Information
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.
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.
Many common errors in formulating SQL queries are caused by the behavior of NULL. You have to be careful to
avoid these problem areas.
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:
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
Side effects
None.
Standards
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 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.
Related Information
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.
Standards
Related Information
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.
Standards
Related Information
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
Related Information
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:
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
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
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
Create a table with a DEFAULT column set to the CURRENT TIMESTAMP special value. Then insert some
values under two different time zones.
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
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
Related Information
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
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
Related Information
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.
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.
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.
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:
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:
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.
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:
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:
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:
In this section:
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 an enabled view (including materialized views). Materialized views must be initialized as well.
variable-name
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
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
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 casts a value to the data type defined for the BirthDate column (DATE data type) of
the Employees table:
Related Information
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
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
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
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
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.
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 #
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
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:
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:
Related Information
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.
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 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
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:
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.
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:
Standards
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:
Related Information
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.
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
1.1.11 Comments
Comments are used to attach explanatory text to SQL statements or statement blocks. The database server does
not execute comments.
-- (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)
Example
The following example illustrates the use of double-hyphen comments:
Standards
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.
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
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' );
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
Related Information
In this section:
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:
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
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:
Related Information
Syntax
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.
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
UltraLite remarks
Standards
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.
The LONG NVARCHAR data type stores Unicode character data of arbitrary length.
Syntax
LONG NVARCHAR
Remarks
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.
Standards
The use of LONG NVARCHAR to declare a national character string is not in the standard.
Related Information
The LONG VARCHAR data type stores character data of arbitrary length.
Syntax
LONG VARCHAR
Remarks
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
Related Information
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.
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.
Related Information
The NTEXT data type stores Unicode character data of arbitrary length.
Syntax
NTEXT
Remarks
Standards
Related Information
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.
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.
Related Information
Syntax
TEXT
Remarks
Standards
Related Information
Syntax
UNIQUEIDENTIFIERSTR
Remarks
Used for remote data access, when mapping Microsoft SQL Server uniqueidentifier columns.
Standards
Related Information
Syntax
UltraLite:
VARCHAR [ ( max-length) ]
Parameters
max-length
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
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
The XML data type stores character data of arbitrary length, and stores XML documents.
Syntax
XML
Remarks
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
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:
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.
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
Related Information
Syntax
BIT
Remarks
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.
Standards
Related Information
The DECIMAL data type is a decimal number with precision total digits and with scale digits after the decimal
point.
Syntax
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 DECIMAL data type is an exact numeric data type; its accuracy is preserved to the least significant digit after
arithmetic operations.
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.
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
Core Feature.
Related Information
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.
Standards
Core Feature
Related Information
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
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
Core Feature.
Related Information
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.
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
Related Information
Syntax
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.
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.
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.
Compatible with ANSI/ISO SQL Standard if the scale option is set to zero.
Related Information
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.
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
Related Information
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.
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
Compatible with the standard. However, the UNSIGNED keyword is not in the standard.
MySQL
Related Information
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.
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.
The UNSIGNED keyword may precede or follow TINYINT, but the UNSIGNED modifier has no effect as the
type is always unsigned.
Related Information
In this section:
Syntax
MONEY
Standards
Related Information
The SMALLMONEY data type stores monetary data that is less than one million currency units.
Syntax
SMALLMONEY
Remarks
Standards
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:
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
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
Related Information
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:
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.
The date and time of day with a time zone offset can be sent to the database as a string only.
In this section:
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.
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.
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).
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).
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.
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
In the following example, the date value is constructed from the current date.
Related Information
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'.
The non-ISO AM and PM designators are also supported. For example, '11:59:59 PM' is equivalent to '23:59:59'.
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
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
ISO 8601 also permits the addition of a time zone offset to a date and time of day string.
(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.
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
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.
timestamp + integer
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.
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.
The DATE data type stores calendar dates, such as a year, month, and day.
Syntax
DATE
Remarks
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
Related Information
Syntax
DATETIME
Remarks
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.
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.
Standards
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
Syntax
DATETIMEOFFSET
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.
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 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.
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:
Note
The TimeZoneAdjustment connection property is not supported in UltraLite databases.
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
SMALLDATETIME is a domain, implemented as TIMESTAMP, used to store date and time of day information.
SMALLDATETIME is a Transact-SQL type.
Syntax
SMALLDATETIME
None
Standards
Related Information
The TIME data type stores the time of day, containing the hour, minute, second, and fraction of a second.
Syntax
TIME
Remarks
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
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
Syntax
TIMESTAMP
Remarks
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.
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
Adaptive Server Enterprise uses the DATETIME type for TIMESTAMP values.
Related Information
The TIMESTAMP WITH TIME ZONE data type stores a point in time with a time zone offset.
Syntax
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.
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 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.
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:
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
TIMESTAMP WITH TIME ZONE is part of optional ANSI/ISO SQL Language Feature F411.
Related Information
Binary data types store binary data, including images and other types of information that are not interpreted by
the database.
In this section:
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.
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.
Standards
Related Information
Syntax
IMAGE
Remarks
Standards
Related Information
The LONG BINARY data type stores binary data of arbitrary length.
Syntax
LONG BINARY
Remarks
You can cast strings to/from LONG BINARY data. LONG BINARY data cannot be concatenated.
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
The LONG BINARY data type comprises SQL Language Features T021, "BINARY and VARBINARY data types",
and T041, "Basic LOB data type support".
Related Information
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 );
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.
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
Related Information
The VARBINARY data type stores binary data of a specified maximum length (in bytes).
Syntax
VARBINARY [ ( max-length ) ]
max-length
The maximum length of the value, in bytes. If the length is not specified, then it is 1.
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 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
Related Information
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.
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.
Creating a ROW or ARRAY domain allows you to reference the row or array type, instead of defining it repeatedly
inside statements.
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:
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.
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 an alternative way of declaring an array of 5 integers that is compatible with the
Oracle syntax:
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:
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:
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:
Related Information
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
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.
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.
● 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.
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
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:
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:
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:
Table 3: Results
surname givenname birthdate
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:
The following example shows how you can use table reference variables in a procedure:
Related Information
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
The following statement creates a data type named street_address, which is a 35-character string.
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:
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.
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:
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
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
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.
In this section:
Related Information
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
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
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.
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:
Related Information
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.
The table below summarizes the conversions that are implicit when comparing certain data types with date, time,
or date-time data types.
CHAR TIMESTAMP WITH TIME ZONE CHAR cast to TIMESTAMP WITH TIME
ZONE
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
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.
Related Information
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:
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.
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. 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
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
● 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:
Related Information
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:
Therefore, it is important to consider this option when converting from NCHAR to CHAR.
Related Information
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:
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.
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.
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.
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).
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).
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'.
When converting a DOUBLE type to a NUMERIC type, precision is maintained for the first 15 significant digits.
Related Information
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:
Data type conversion between Java types and SQL types is required for both Java stored procedures and JDBC
applications.
String CHAR
String VARCHAR
String TEXT
java.math.BigDecimal NUMERIC
java.math.BigDecimal MONEY
java.math.BigDecimal SMALLMONEY
boolean BIT
byte TINYINT
short SMALLINT
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
Data type conversion between SQL types and Java types follow a specific mapping.
CHAR String
VARCHAR String
TEXT String
NUMERIC java.math.BigDecimal
DECIMAL java.math.BigDecimal
MONEY java.math.BigDecimal
SMALLMONEY java.math.BigDecimal
BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT double
DOUBLE double
BINARY byte[ ]
VARBINARY byte[ ]
IMAGE byte[ ]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
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.
In this section:
Related Information
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 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 functions
Related Information
List of functions
Related Information
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
Related Information
Data type conversion functions are used to convert arguments from one data type to another, or to test whether
they can be converted.
Related Information
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:
The following date and time functions are available for UltraLite:
In this section:
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:
Year YY 1-9999
Quarter QQ 1-4
Month MM 1-12
Day DD 1-31
Dayofyear DY 1-366
Hour HH 0-23
Minute MI 0-59
Second SS 0-59
Millisecond MS 0-999
Related Information
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.
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.
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.
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:
Related Information
Miscellaneous functions perform operations on arithmetic, string, or date/time expressions, including the return
values of other functions.
Numeric functions perform mathematical operations on numerical data types or return numeric information.
HTTP functions assist the handling of HTTP requests within web services. Likewise, SOAP functions assist the
handling of SOAP requests within web services.
Related Information
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.
List of functions
● 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
Returns the INTEGER defined length of the specified column. @object_name can contain the owner, for
example, 'GROUPO.Customers'.
Syntax: COL_TERM
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
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:
Related Information
Syntax
ABS( numeric-expression )
Parameters
numeric-expression
INT INT
FLOAT FLOAT
DOUBLE DOUBLE
NUMERIC NUMERIC
Standards
Example
The following statement returns the value 66:
Syntax
ACOS( numeric-expression )
Parameters
numeric-expression
DOUBLE
Remarks
This function converts its argument to DOUBLE, and performs the computation in double-precision floating-point
arithmetic.
Standards
Example
The following statement returns the arc-cosine value for 0.52:
Related Information
Syntax
integer-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
Example
The following statement returns the value 6:
Syntax
ARRAY(
expression [, expression ... ]
Parameters
expression
Returns
Array value
Remarks
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
Example
The following example illustrates how to construct an array:
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.
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:
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]];
Related Information
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.
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
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.
Syntax
ARRAY_MAX_CARDINALITY( array-expression )
Parameters
array-expression
Returns
INTEGER
Remarks
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
Feature S403.
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
Related Information
Syntax
ASIN( numeric-expression )
Parameters
numeric-expression
Returns
DOUBLE
Remarks
This function converts its argument to DOUBLE, and performs the computation in double-precision floating-point
arithmetic.
Example
The following statement returns the arc-sine value for 0.52:
Related Information
Syntax
ATAN( numeric-expression )
Parameters
numeric-expression
Returns
DOUBLE
This function converts its argument to DOUBLE, and performs the computation in double-precision floating-point
arithmetic.
Standards
Example
The following statement returns the arc-tangent value for 0.52:
Related Information
Syntax
Parameters
numeric-expression-1
Returns
DOUBLE
Remarks
This function converts its arguments to DOUBLE, and performs the computation in double-precision floating-
point arithmetic.
Standards
Example
The following statement returns the arc-tangent value for the ratio 0.52 to 0.60:
Related Information
Computes the average, for a set of rows, of a numeric expression or of a set of unique values.
Syntax
Numeric expressions
Window function
Parameters
[ ALL ] numeric-expression
The expression whose average is calculated over the rows in each group.
DISTINCT clause
Returns
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.
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:
The following statement returns the average product price from the Products table when connected to the SQL
Anywhere 17 Demo database:
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:
Related Information
Decodes data using the MIME base64 format and returns the string as a LONG VARCHAR.
Syntax
BASE64_DECODE( string-expression )
Parameters
string-expression
Returns
LONG VARCHAR
Standards
Example
The following inserts an image into an image table from an Embedded SQL program. The input data (host
variable) must be base64 encoded:
Related Information
Encodes data using the MIME base64 format and returns it as a 7-bit ASCII string.
Syntax
BASE64_ENCODE( string-expression )
Parameters
string-expression
Returns
LONG VARCHAR
Standards
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.
Related Information
Syntax
BINTOHEX( binary-expression )
Parameters
binary-expression
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
Example
The following statement returns a string containing 313233:
SELECT BINTOHEX(0x313233);
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
Example
The following example generates four rows containing a CHAR column, then converts the values to VARBIT:
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
Syntax
BIT_LENGTH( bit-expression )
Parameters
bit-expression
Returns
INT
Standards
Example
The following statement returns the value 8:
Related Information
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
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
Syntax
Parameters
bit-expression
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.
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.
The BIT_SUBSTR function is equivalent to, but faster than, the following:
Standards
Example
The following statement returns 1101:
Related Information
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
Example
The following example generates four rows containing a CHAR column, then converts the values to VARBIT:
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.
Syntax
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
Returns
LONG BINARY
Remarks
Standards
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);
Syntax
BYTE_LENGTH( string-expression )
Parameters
string-expression
Returns
INT
Remarks
Trailing white space characters in the string-expression are included in the length returned.
If the string is in a multibyte character set, the BYTE_LENGTH value may differ from the number of characters
returned by CHAR_LENGTH.
Example
The following statement returns the value 12:
Related Information
Syntax
Parameters
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.
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
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 );
Replaces a string with another string, and returns the new results.
Syntax
Parameters
source-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
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
Deletes multiple bytes from one string and replaces them with different bytes.
Syntax
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 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.
Example
The following statement inserts the string 123456 starting at the 5th byte position, and returns the value
0xfedcba9876123456543210:
Returns a substring of a string. The substring is calculated using bytes, not characters.
Syntax
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
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
Example
The following statement returns the value Test:
Related Information
Returns the highest number of any array element that has been assigned a value, including NULL.
Syntax
CARDINALITY( array-expression )
Parameters
array-expression
Returns
INTEGER
Remarks
The result is an integer between zero and the maximum size of the array.
Standards
Example
The following example returns the value 4:
Related Information
Syntax
expression
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
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:
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.
The HEXTOINT and INTTOHEX functions can be used to convert to and from hexadecimal values.
Standards
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:
The value of the expression 1 + 2 is calculated, and the result is then cast into a single-character string.
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.
The following statement casts a value to the data type defined for the BirthDate column (DATE data type) of
the Employees table:
Returns the first integer that is greater or equal to a given value. For positive numbers, this is known as rounding
up.
Syntax
Parameters
numeric-expression
Returns
DOUBLE
Remarks
This function converts its argument to DOUBLE, and performs the computation in double-precision floating-point
arithmetic.
Standards
The CEILING function comprises part of optional ANSI/ISO SQL Language Feature T621, "Enhanced numeric
functions".
Related Information
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.
Example
The following statement returns the value Y:
SELECT CHAR( 89 );
Related Information
Syntax
CHAR_LENGTH ( string-expression )
Parameters
string-expression
Returns
INT
Remarks
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
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:
Related Information
Syntax
string-expression-1
The string for which you are searching. The value must be less than 256 bytes.
string-expression-2
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.
Standards
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:
Surname GivenName
Klobucher James
Kuo Felicia
Kelly Moira
Related Information
Returns the first non-NULL expression from a list. This function is identical to the ISNULL function.
Syntax
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.
The parameters can be of any scalar type, but not necessarily same type.
Standards
Core Feature.
Example
The following statement returns the value 34:
Related Information
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 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
Value Meaning
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.
Example
The following example performs three comparisons using the COMPARE function:
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
Syntax
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.
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
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.
Related Information
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 )
column-name
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
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:
Assume that consolidated and remote databases both have the following row in the Admin table:
1, 'Initial'
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:
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.
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:
You can use the CONFLICT function to rewrite the trigger as follows and avoid the error:
Related Information
Syntax
CONNECTION_EXTENDED_PROPERTY(
{ property-id | property-name }
[, property-specific-argument [, connection-id ] ]
)
Parameters
property-id
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 Units to obtain the type of units left to be processed (pages, rows, or bytes).
Elapsed
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
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
Remarks
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.
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
Example
The following example returns the CHAR character set of the current connection as it is known by the Java
standard:
Related Information
Syntax
CONNECTION_PROPERTY(
{ property-id | property-name }
[ , connection-id ] )
Parameters
property-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
Remarks
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
Example
The following statement returns the number of prepared statements being maintained:
Related Information
Syntax
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 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).
Without century (yy) style codes With century (yyyy) style codes Output format
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]
8 108 hh:nn:ss
10 110 mm-dd-yy[yy]
11 111 [yy]yy/mm/dd
12 112 [yy]yymmdd
Returns
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
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:
OrderDate
16.03.2000
20.03.2000
23.03.2000
25.03.2000
...
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:
The following statement converts a value to the data type defined for the BirthDate column (DATE data type) of
the Employees table:
Related Information
Syntax
dependent-expression
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:
Standards
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:
Syntax
COS( numeric-expression )
Parameters
numeric-expression
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
Example
The following statement returns the value of the cosine of an angle 0.52 radians:
Syntax
COT( numeric-expression )
Parameters
numeric-expression
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
Example
The following statement returns the cotangent value of 0.52:
Syntax
Expressions
Window function
UltraLite expressions
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.
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
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:
Related Information
Syntax
COUNT_BIG(
[ * | [ ALL | DISTINCT ] expression ]
| [ * | [ ALL ] expression ]) OVER ( window-spec
)
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 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.
Standards
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:
Related Information
Syntax
COUNT_SET_BITS( bit-expression )
Parameters
bit-expression
UNSIGNED INT
Remarks
Standards
Example
The following statement returns the value 4:
Syntax
Expression
Window function
dependent-expression
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:
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
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.
Syntax
Expression
Window function
Parameters
dependent-expression
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.
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
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:
Related Information
Syntax
CSCONVERT(
string-expression,
target-charset-string [, source-charset-string [, options ] ] )
Parameters
string-expression
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
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
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:
This fragment converts the mytext column from the database character set to the Simplified Chinese character
set:
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:
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:
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:
Related Information
Syntax
Returns
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
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:
Related Information
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
BIT 1
TINYINT 1
SMALLINT 2
INTEGER 4
BIGINT 8
REAL 4
DOUBLE 8
TIME 8
DATE 4
TIMESTAMP 8
DATETIME 8
UNIQUEIDENTIFIER 16
Standards
Related Information
Converts the expression into a date, and removes any hours, minutes, or seconds.
Syntax
DATE( expression )
Parameters
expression
Returns
DATE
Standards
The following statement returns the create dates of all the objects listed in the SYSOBJECT system view:
Related Information
Returns a TIMESTAMP or TIMESTAMP WITH TIME ZONE value produced by adding a date part to its argument.
Syntax
date-part :
year
| quarter
| month
| week
| day
| dayofyear
| hour
| minute
| second
| millisecond
| microsecond
Parameters
date-part
Returns
TIMESTAMP WITH TIME ZONE if timestamp-expression is a TIMESTAMP WITH TIME ZONE; otherwise
TIMESTAMP.
Standards
Example
The following statement returns the TIMESTAMP value 2016-05-02 00:00:00.000:
The following statement returns the TIMESTAMP WITH TIME ZONE value 2015-05-06 11:33:00.000+04:00:
Related Information
Syntax
Parameters
date-part
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.
Standards
Example
The following statement returns 1:
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;
Syntax
Parameters
datetime-expression
Returns
VARCHAR
Remarks
Standards
Example
The following statement returns the value Jan 01, 1989:
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
Parameters
date-part
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.
Example
In an English locale, the following statement returns the value May:
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.
Related Information
Syntax
Parameters
date-part
The TIMESTAMP or TIMESTAMP WITH TIME ZONE value for which the part is to be returned.
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
Example
The following statement returns the value 5:
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:
Related Information
Syntax
DATETIME( expression )
Parameters
expression
Returns
TIMESTAMP
Remarks
Standards
Example
The following statement returns a timestamp with value 1998-09-09 12:12:12.000:
Related Information
Returns the day of the month of its argument as an integer between 1 and 31.
Syntax
DAY( date-expression )
Parameters
date-expression
Returns
SMALLINT
Remarks
The DAY function returns an integer between 1 and 31, corresponding to the day of the month in the argument.
Example
The following statement returns the value 12:
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.
Example
In an English locale, the following statement returns the value Saturday:
In a German locale, the value returned is Samstag. In an Italian locale, the value returned is sabato. Several
locales are supported.
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 )
Parameters
timestamp-expression
A TIMESTAMP value.
integer-expression
Remarks
The result of the DAYS function depends on its arguments. The DAYS function ignores hours, minutes, and
seconds in its arguments.
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.
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
Example
The following statement returns the integer 729889:
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):
The following statements return the TIMESTAMP value 1999-07-14 00:00:00.000. It is recommended that you
use the second example (DATEADD):
Related Information
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 following database properties allow you to specify additional arguments, as noted below, to return
specific information about the property.
AccentSensitivity
Returns the accent sensitivity setting for the collation. For example, the following statement returns
the accent sensitivity setting for the NCHAR collation:
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
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
The database ID number, as returned by the DB_ID function. Typically, the database name is used.
database-name
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.
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:
Instead, you could execute the following statements to achieve the desired results:
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
Example
The following statement returns the location of the current database:
The following statement returns the file size of the system dbspace, in pages:
The following statement returns the file size of the transaction log, in pages:
The following statement returns the case sensitivity setting for the NCHAR collation:
The following statement returns the tailoring options specified for the database CHAR collation:
The following statement returns the full collation specification for the database NCHAR collation:
The following statement returns the connection status of the mirror server Test:
The following statement returns the synchronization status of the mirror server Test:
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
Example
The following statement returns the value 0, when executed against the sample database as the sole database
on the server:
The following statement returns the value 0 if executed against the only running database:
SELECT DB_ID( );
Syntax
DB_NAME( [ database-id ] )
Parameters
database-id
Returns
VARCHAR
Remarks
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
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
Syntax
DB_PROPERTY(
{ property-id | property-name }
[, database-id | database-name ]
)
UltraLite:
DB_PROPERTY( property-name )
property-id
The database ID number, as returned by the DB_ID function. Typically, the database name is used.
database-name
Returns
Remarks
Returns a string.
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.
Standards
UltraLite: The following statement returns the page size of the current database, in bytes:
Related Information
Syntax
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.
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
Example
The following example uses the DECOMPRESS function to decompress values from the Attachment column of
a fictitious table, 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:
Related Information
Decrypts the string using the supplied key and returns a LONG BINARY value.
Syntax
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.
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
algorithm
This optional string parameter specifies the type of algorithm originally used to encrypt the string-
expression. Specify one of the following formats:
AES
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.
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.
Standards
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.
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.
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
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
Example
The following statement returns the value 29.79380534680281:
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
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
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
Related Information
Returns the difference in the SOUNDEX values between the two string expressions.
Syntax
Parameters
string-expression-1
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
Example
The following statement returns similarity between the words test and chest:
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
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
The following statement queries the Employees table and returns the employee StartDate, expressed as the
number of the day of the week:
Encrypts the specified value using the supplied encryption key and returns a LONG BINARY value.
Syntax
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 }
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.
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
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.
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
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
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.
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'.
Related Information
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.
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:
Related Information
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.
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
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:
Related Information
Syntax
ERROR_PROCEDURE( )
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
Standards
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;
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
Standards
Example
The following batch illustrates division by zero exception handling.
BEGIN
Related Information
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.
Standards
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;
Related Information
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
Example
The following set of procedures (with line numbers added for illustration) can be used to obtain the error stack:
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:
line_num row_value
1 "DBA"."proc1" : 8
2 "DBA"."proc2" : 3
3 RESIGNAL: "DBA"."proc3" : 3
4 "DBA"."proc1" : 5
Related Information
Provides the error message for the current error, or for a specified SQLSTATE or SQLCODE value.
Syntax
sqlstate: string
sqlcode: integer
Parameters
sqlstate
Returns
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).
Example
The following statement returns the error message for SQLCODE -813:
Returns selectivity estimates as a percentage calculated by the query optimizer, based on specified parameters.
Syntax
Parameters
column-name
The comparison operator used for the comparison, enclosed in single quotes. Possible values for this
parameter are: '=' , '>' , '<' , '>=' , '<=' , '<>' , '!=' , '!<' , and '!>'. The default is '='.
Returns
REAL
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
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.
Related Information
Provides the source for selectivity estimates used by the query optimizer.
Syntax
ESTIMATE_SOURCE(
column-name
[, value
[, relation-string ] ]
)
column-name
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.
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.
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
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.
Related Information
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:
Returns
INT
Remarks
The EVENT_CONDITION function returns NULL when not called from an event.
Standards
Related Information
Syntax
EVENT_CONDITION_NAME( integer )
Parameters
integer
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.
Standards
Related Information
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
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
A string indicating the reason the connect was terminated. This parameter is valid only for Disconnect
events. Possible results include:
abnormal
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 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
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.
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
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.
Related Information
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.
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
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 );
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
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
Example
The following statement returns 90.3262405396:
Related Information
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
FOR UPDATE The cursor can be read or written to. This is the same as
READ-WRITE.
Returns
LONG VARCHAR
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
Example
The following statement passes a SELECT statement as a string parameter and returns the plan for executing
the query:
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 ...':
Related Information
Syntax
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:
When you execute SELECT EXPRTYPE( 'SELECT * FROM mytable', 1 ), the data type returned is char(20),
not mydomain.
Standards
Example
The following statement returns smallint when executed against the SQL Anywhere sample database:
Related Information
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
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.
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
Standards
Example
Execute the following statement to determine whether the xp_cmdshell system procedure can be used on the
current connection without requiring a key:
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:
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..
Execute the following statement to determine whether there is a secure feature key that allows the current
connection to perform BACKUP and RESTORE statements.
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
Syntax
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
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.
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
Core feature.
Example
The following statement returns 56.789000:
Related Information
Syntax
Parameters
expression
Returns
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
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.
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
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
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:
Related Inf