SQL++ Query Strings
How to use SQL++ query strings to build effective queries with Kotbase
Note
The examples used in this topic are based on the Travel Sample app and data introduced in the Couchbase Mobile Workshop tutorial.
Introduction
Developers using Kotbase can provide SQL++ query strings using the SQL++ Query API. This API uses query statements of the form shown in Example 2.
The structure and semantics of the query format are based on that of Couchbase Server’s SQL++ query language — see SQL++ Reference Guide and SQL++ Data Model.
Running
The database can create a query object with the SQL++ string. See Query Result Sets for how to work with result sets.
Example 1. Running a SQL++ Query
We are accessing the current database using the shorthand notation _
— see the FROM
clause for more on data
source selection and Query Parameters for more on parameterized queries.
Query Format
The API uses query statements of the form shown in Example 2.
Example 2. Query Format
Query Components
Component | Description |
---|---|
SELECT statement | The document properties that will be returned in the result set |
FROM | The data source to be queried |
WHERE statement | The query criteria The SELECT ed properties of documents matching this criteria will be returned in the result set |
JOIN statement | The criteria for joining multiple documents |
GROUP BY statement | The criteria used to group returned items in the result set |
ORDER BY statement | The criteria used to order the items in the result set |
LIMIT statement | The maximum number of results to be returned |
OFFSET statement | The number of results to be skipped before starting to return results |
Tip
We recommend working through the SQL++ Tutorials to build your SQL++ skills.
SELECT statement
Purpose
Projects the result returned by the query, identifying the columns it will contain.
Syntax
Example 3. SQL++ Select Syntax
Arguments
- The select clause begins with the
SELECT
keyword.- The optional
ALL
argument is used to specify that the query should return ALL results (the default). - The optional
DISTINCT
argument specifies that the query should remove duplicated results.
- The optional
selectResults
is a list of columns projected in the query result. Each column is an expression which could be a property expression or any expressions or functions. You can use the wildcard*
to select all columns — see Select Wildcard.- Use the optional
AS
argument to provide an alias name for a property. Each property can be aliased by putting theAS <alias name>
after the column name.
Select Wildcard
When using the SELECT *
option the column name (key) of the SQL++ string is one of:
- The alias name if one was specified
- The data source name (or its alias if provided) as specified in the
FROM
clause.
This behavior is inline with that of Couchbase Server SQL++ — see example in Table 1.
Table 1. Example Column Names for SELECT *
Query | Column Name |
---|---|
SELECT * AS data FROM _ |
data |
SELECT * FROM _ |
_ |
SELECT * FROM _default |
_default |
SELECT * FROM db |
db |
SELECT * FROM db AS store |
store |
Example
Example 4. SELECT properties
- Use the
*
wildcard to select all properties. - Select all properties from the
db
data source. Give the object an alias name ofdata
. - Select a pair of properties.
- Select a specific property from the db data source.
- Select the property item
city
from its parent propertyaddress
.
See Query Result Sets for more on processing query results.
FROM
Purpose
Specifies the data source, or sources, and optionally applies an alias (AS
). It is mandatory.
Syntax
Datasource
A datasource can be:
- < database-name > : default collection
- _ (underscore) : default collection
- < scope-name >.< collection-name > : a collection in a scope
- < collection-name > : a collection in the default scope
Arguments
- Here
dataSource
is the database name against which the query is to run or the. . Use AS
to give the database an alias you can use within the query.
To use the current database, without specifying a name, use_
as the datasource. JOIN joinclause
— use this optional argument to link data sources — seeJOIN
statement.
Example
Example 5. FROM clause
JOIN statement
Purpose
The JOIN
clause enables you to select data from multiple data sources linked by criteria specified in the JOIN
statement.
Currently only self-joins are supported. For example to combine airline details with route details, linked by the airline id — see Example 6.
Syntax
joinClause = ( join )*
join = joinOperator _ dataSource _ (constraint)?
joinOperator = ( LEFT (OUTER)? | INNER | CROSS )? JOIN
dataSource = databaseName ( ( AS | _ )? databaseAlias )?
constraint ( ON expression )?
Arguments
- The join clause starts with a
JOIN
operator followed by the data source. - Five
JOIN
operators are supported:
JOIN
,LEFT JOIN
,LEFT OUTER JOIN
,INNER JOIN
, andCROSS JOIN
. Note:JOIN
andINNER JOIN
are the same,LEFT JOIN
andLEFT OUTER JOIN
are the same. - The join constraint starts with the
ON
keyword followed by the expression that defines the joining constraints.
Example
SELECT db.prop1, other.prop2 FROM db JOIN db AS other ON db.key = other.key
SELECT db.prop1, other.prop2 FROM db LEFT JOIN db other ON db.key = other.key
SELECT * FROM route r JOIN airline a ON r.airlineid = meta(a).id WHERE a.country = "France"
Example 6. Using JOIN to Combine Document Details
This example JOINS the document of type route
with documents of type airline
using the document ID (_id
) on
the airline document and airlineid
on the route document.
WHERE statement
Purpose
Specifies the selection criteria used to filter results.
As with SQL, use the WHERE
statement to choose which documents are returned by your query.
Syntax
Arguments
WHERE
evaluates expression
to a BOOLEAN
value. You can chain any number of expressions in order to implement
sophisticated filtering capabilities.
See also — Operators for more on building expressions and Query Parameters for more on parameterized queries.
Examples
GROUP BY statement
Purpose
Use GROUP BY
to arrange values in groups of one or more properties.
Syntax
groupBy = grouping _( having )?
grouping = GROUP BY expression( _ ',' _ expression )*
having = HAVING expression
Arguments
- The group by clause starts with the
GROUP BY
keyword followed by one or more expressions. grouping
— the group by clause is normally used together with the aggregate functions (e.g.COUNT
,MAX
,MIN
,SUM
,AVG
).having
— allows you to filter the result based on aggregate functions — for example,HAVING count(empnum)>100
.
Examples
SELECT COUNT(empno), city FROM db GROUP BY city
SELECT COUNT(empno), city FROM db GROUP BY city HAVING COUNT(empno) > 100
SELECT COUNT(empno), city FROM db GROUP BY city HAVING COUNT(empno) > 100 WHERE state = 'CA'
ORDER BY statement
Purpose
Sort query results based on a given expression result.
Syntax
orderBy = ORDER BY ordering ( _ ',' _ ordering )*
ordering = expression ( _ order )?
order = ( ASC / DESC )
Arguments
orderBy
— The order by clause starts with theORDER BY
keyword followed by the ordering clause.ordering
— The ordering clause specifies the properties or expressions to use for ordering the results.order
— In each ordering clause, the sorting direction is specified using the optionalASC
(ascending) orDESC
(descending) directives. Default isASC
.
Examples
Example 7. Simple usage
LIMIT statement
Purpose
Specifies the maximum number of results to be returned by the query.
Syntax
Arguments
The limit clause starts with the LIMIT
keyword followed by an expression that will be evaluated as a number.
Examples
OFFSET statement
Purpose
Specifies the number of results to be skipped by the query.
Syntax
Arguments
The offset clause starts with the OFFSET
keyword followed by an expression that will be evaluated as a number that
represents the number of results ignored before the query begins returning results.
Examples
- Ignore first 10 results
- Ignore first 10 results then return the next 10 results
Expressions
In this section
Literals | Identifiers | Property Expressions | Any and Every
Expressions | Parameter Expressions | Parenthesis
Expressions
Expressions are references to identifiers that resolve to values. Categories of expression comprise the elements covered in this section (see above), together with Operators and Functions, which are covered in their own sections.
Literals
Boolean | Numeric | String | NULL | MISSING | Array | Dictionary
Boolean
Purpose
Represents a true or false value.
Syntax
TRUE
| FALSE
Example
Numeric
Purpose
Represents a numeric value. Numbers may be signed or unsigned digits. They have optional fractional and exponent components.
Syntax
Example
SELECT value FROM db WHERE value = 10
SELECT value FROM db WHERE value = 0
SELECT value FROM db WHERE value = -10
SELECT value FROM db WHERE value = 10.25
SELECT value FROM db WHERE value = 10.25e2
SELECT value FROM db WHERE value = 10.25E2
SELECT value FROM db WHERE value = 10.25E+2
SELECT value FROM db WHERE value = 10.25E-2
String
Purpose
The string literal represents a string or sequence of characters.
Syntax
The string literal can be double-quoted as well as single-quoted.
Example
SELECT firstName, lastName FROM db WHERE middleName = "middle"
SELECT firstName, lastName FROM db WHERE middleName = 'middle'
NULL
Purpose
The literal NULL
represents an empty value.
Syntax
Example
MISSING
Purpose
The MISSING
literal represents a missing name-value pair in a document.
Syntax
Example
Array
Purpose
Represents an Array.
Syntax
Example
Dictionary
Purpose
Represents a dictionary literal.
Syntax
dictionaryLiteral = '{' _ ( STRING_LITERAL ':' e:expression
( _ ',' _ STRING_LITERAL ':' _ expression )* )?
'}'
Example
SELECT { 'name': 'James', 'department': 10 } FROM db
SELECT { 'name': 'James', 'department': dept } FROM db
SELECT { 'name': 'James', 'phones': ['650-100-1000', '650-100-2000'] } FROM db
Identifiers
Purpose
Identifiers provide symbolic references. Use them for example to identify: column alias names, database names, database alias names, property names, parameter names, function names, and FTS index names.
Syntax
The identifier allows a-z, A-Z, 0-9, _ (underscore), and $ character.
The identifier is case-sensitive.
Tip
To use other characters in the identifier, surround the identifier with the backtick ` character.
Example
Example 10. Identifiers
SELECT * FROM _
SELECT * FROM `db-1`
SELECT key FROM db
SELECT key$1 FROM db_1
SELECT `key-1` FROM db
Use of backticks allows a hyphen as part of the identifier name.
Property Expressions
Purpose
The property expression is used to reference a property in a document.
Syntax
property = '*'| dataSourceName '.' _ '*' | propertyPath
propertyPath = propertyName (
('.' _ propertyName ) |
('[' _ INT_LITERAL _ ']' _ )
)*
propertyName = IDENTIFIER
- Prefix the property expression with the data source name or alias to indicate its origin.
- Use dot syntax to refer to nested properties in the propertyPath.
- Use bracket (
[index]
) syntax to refer to an item in an array. - Use the asterisk (
*
) character to represents all properties. This can only be used in the result list of theSELECT
clause.
Example
Example 11. Property Expressions
SELECT *
FROM db
WHERE contact.name = "daniel"
SELECT db.*
FROM db
WHERE collection.contact.name = "daniel"
SELECT collection.contact.address.city
FROM scope.collection
WHERE collection.contact.name = "daniel"
SELECT contact.address.city
FROM scope.collection
WHERE contact.name = "daniel"
SELECT contact.address.city, contact.phones[0]
FROM db
WHERE contact.name = "daniel"
Any and Every Expressions
Purpose
Evaluates expressions over items in an array object.
Syntax
arrayExpression =
anyEvery _ variableName
_ IN _ expression
_ SATISFIES _ expression
END
anyEvery = anyOrSome AND EVERY | anyOrSome | EVERY
anyOrSome = ANY | SOME
- The array expression starts with
ANY/SOME
,EVERY
, orANY/SOME AND EVERY
, each of which has a different function as described below, and is terminated byEND
ANY/SOME
: ReturnsTRUE
if at least one item in the array satisfies the expression, otherwise returnsFALSE
.
NOTE:ANY
andSOME
are interchangeable.EVERY
: ReturnsTRUE
if all items in the array satisfies the expression, otherwise returnFALSE
. If the array is empty, returnsTRUE
.ANY/SOME AND EVERY
: Same asEVERY
but returnsFALSE
if the array is empty.
- The variable name represents each item in the array.
- The
IN
keyword is used for specifying the array to be evaluated. - The
SATISFIES
keyword is used for evaluating each item in the array. END
terminates the array expression.
Example
Example 12. ALL and Every Expressions
Parameter Expressions
Purpose
Parameter expressions specify a value to be assigned from the parameter map presented when executing the query.
Note
If parameters are specified in the query string, but the parameter and value mapping is not specified in the query object, an error will be thrown when executing the query.
Syntax
Examples
Example 14. Using a Parameter
val query = database.createQuery("SELECT name WHERE department = \$department")
query.parameters = Parameters().setValue("department", "E001")
val result = query.execute()
The query resolves to SELECT name WHERE department = "E001"
Parenthesis Expressions
Purpose
Use parentheses to group expressions together to make them more readable or to establish operator precedences.
Example
Example 15. Parenthesis Expression
Operators
In this section
Binary Operators | Unary Operators | COLLATE Operators |
CONDITIONAL Operator
Binary Operators
Maths | Comparison Operators | Logical Operators | String Operator
Maths
Table 2. Maths Operators
Op | Desc | Example |
---|---|---|
+ |
Add | WHERE v1 + v2 = 10 |
- |
Subtract | WHERE v1 - v2 = 10 |
* |
Multiply | WHERE v1 * v2 = 10 |
/ |
Divide — see note ¹ | WHERE v1 / v2 = 10 |
% |
Modulo | WHERE v1 % v2 = 0 |
¹ If both operands are integers, integer division is used, but if one is a floating number, then float division is used. This differs from Server SQL++, which performs float division regardless. Use DIV(x, y) to force float division in CBL SQL++.
Comparison Operators
Purpose
The comparison operators are used in the WHERE
statement to specify the condition on which to match documents.
Table 3. Comparison Operators
Op | Desc | Example |
---|---|---|
= or == |
Equals | WHERE v1 = v2 WHERE v1 == v2 |
!= or <> |
Not Equal to | WHERE v1 != v2 WHERE v1 <> v2 |
> |
Greater than | WHERE v1 > v2 |
>= |
Greater than or equal to | WHERE v1 >= v2 |
> |
Less than | WHERE v1 < v2 |
>= |
Less than or equal to | WHERE v1 ⇐ v2 |
IN |
Returns TRUE if the value is in the list or array of values specified by the right hand side expression; Otherwise returns FALSE . |
WHERE "James" IN contactsList |
LIKE |
String wildcard pattern matching ² comparison. Two wildcards are supported:
|
WHERE name LIKE 'a%' WHERE name LIKE '%a' WHERE name LIKE '%or%' WHERE name LIKE 'a%o%' WHERE name LIKE '%_r%' WHERE name LIKE '%a_%' WHERE name LIKE '%a__%' WHERE name LIKE 'aldo' |
MATCH |
String matching using FTS see Full Text Search Functions | WHERE v1-index MATCH "value" |
BETWEEN |
Logically equivalent to v1>=X and v1<=Y |
WHERE v1 BETWEEN 10 and 100 |
IS NULL ³ |
Equal to NULL |
WHERE v1 IS NULL |
IS NOT NULL |
Not equal to NULL |
WHERE v1 IS NOT NULL |
IS MISSING |
Equal to MISSING |
WHERE v1 IS MISSING |
IS NOT MISSING |
Not equal to MISSING |
WHERE v1 IS NOT MISSING |
IS VALUED |
IS NOT NULL AND MISSING |
WHERE v1 IS VALUED |
IS NOT VALUED |
IS NULL OR MISSING |
WHERE v1 IS NOT VALUED |
² Matching is case-insensitive for ASCII characters, case-sensitive for non-ASCII.
³ Use of IS
and IS NOT
is limited to comparing NULL
and MISSING
values (this encompasses VALUED
). This is
different from QueryBuilder
, in which they operate as equivalents of ==
and !=
.
Table 4. Comparing NULL and MISSING values using IS
OP | NON-NULL Value | NULL | MISSING |
---|---|---|---|
IS NULL | FALSE | TRUE | MISSING |
IS NOT NULL | TRUE | FALSE | MISSING |
IS MISSING | FALSE | FALSE | TRUE |
IS NOT MISSING | TRUE | TRUE | FALSE |
IS VALUED | TRUE | FALSE | FALSE |
IS NOT VALUED | FALSE | TRUE | TRUE |
Logical Operators
Purpose
Logical operators combine expressions using the following Boolean Logic Rules:
- TRUE is TRUE, and FALSE is FALSE
- Numbers 0 or 0.0 are FALSE
- Arrays and dictionaries are FALSE
- String and Blob are TRUE if the values are casted as a non-zero or FALSE if the values are casted as 0 or 0.0
- NULL is FALSE
- MISSING is MISSING
Note
This is different from Server SQL++, where:
- MISSING, NULL and FALSE are FALSE
- Numbers 0 is FALSE
- Empty strings, arrays, and objects are FALSE
- All other values are TRUE
Tip
Use TOBOOLEAN(expr) function to convert a value based on Server SQL++ boolean value rules.
Table 5. Logical Operators
Op | Description | Example |
---|---|---|
AND |
Returns TRUE if the operand expressions evaluate to TRUE ; otherwise FALSE .If an operand is MISSING and the other is TRUE returns MISSING , if the other operand is FALSE it returns FALSE .If an operand is NULL and the other is TRUE returns NULL , if the other operand is FALSE it returns FALSE . |
WHERE city = "San Francisco" AND status = true |
OR |
Returns TRUE if one of the operand expressions is evaluated to TRUE ; otherwise returns FALSE .If an operand is MISSING , the operation will result in MISSING if the other operand is FALSE or TRUE if the other operand is TRUE .If an operand is NULL , the operation will result in NULL if the other operand is FALSE or TRUE if the other operand is TRUE . |
WHERE city = “San Francisco” OR city = "Santa Clara" |
Table 6. Logical Operation Table
a | b | a AND b | a OR b |
---|---|---|---|
TRUE | TRUE | TRUE | TRUE |
FALSE | FALSE | TRUE | |
NULL | FALSE ⁵⁻¹ | TRUE | |
MISSING | MISSING | TRUE | |
FALSE | TRUE | FALSE | TRUE |
FALSE | FALSE | FALSE | |
NULL | FALSE | FALSE ⁵⁻¹ | |
MISSING | FALSE | MISSING | |
NULL | TRUE | FALSE ⁵⁻¹ | TRUE |
FALSE | FALSE | FALSE ⁵⁻¹ | |
NULL | FALSE ⁵⁻¹ | FALSE ⁵⁻¹ | |
MISSING | FALSE ⁵⁻² | MISSING ⁵⁻³ | |
MISSING | TRUE | MISSING | TRUE |
FALSE | FALSE | MISSING | |
NULL | FALSE ⁵⁻² | MISSING ⁵⁻³ | |
MISSING | MISSING | MISSING |
Note
This differs from Server SQL++ in the following instances:
⁵⁻¹ Server will return: NULL instead of FALSE
⁵⁻² Server will return: MISSING instead of FALSE
⁵⁻³ Server will return: NULL instead of MISSING
String Operator
Purpose
A single string operator is provided. It enables string concatenation.
Table 7. String Operators
Op | Description | Example |
---|---|---|
|| |
Concatenating | SELECT firstnm || lastnm AS fullname FROM db |
Unary Operators
Purpose
Three unary operators are provided. They operate by modifying an expression, making it numerically positive or negative,
or by logically negating its value (TRUE
becomes FALSE
).
Syntax
Table 8. Unary Operators
Op | Description | Example |
---|---|---|
+ |
Positive value | WHERE v1 = +10 |
- |
Negative value | WHERE v1 = -10 |
NOT |
Logical Negate operator * | WHERE "James" NOT IN contactsList |
* The NOT
operator is often used in conjunction with operators such as IN
, LIKE
, MATCH
, and BETWEEN
operators.
NOT
operation on NULL
value returns NULL
.
NOT
operation on MISSING
value returns MISSING
.
Table 9. NOT Operation TABLE
a | NOT a |
---|---|
TRUE | FALSE |
FALSE | TRUE |
NULL | FALSE |
MISSING | MISSING |
COLLATE Operators
Purpose
Collate operators specify how the string comparison is conducted.
Usage
The collate operator is used in conjunction with string comparison expressions and ORDER BY
clauses. It allows for one
or more collations.
If multiple collations are used, the collations need to be specified in a parenthesis. When only one collation is used, the parenthesis is optional.
Note
Collate is not supported by Server SQL++
Syntax
collate = COLLATE collation | '(' collation (_ collation )* ')'
collation = NO? (UNICODE | CASE | DIACRITICS) WB
Arguments
The available collation options are:
UNICODE
: Conduct a Unicode comparison; the default is to do ASCII comparison.CASE
: Conduct case-sensitive comparison.DIACRITIC
: Take account of accents and diacritics in the comparison; on by default.NO
: This can be used as a prefix to the other collations, to disable them (for example:NOCASE
to enable case-insensitive comparison)
Example
CONDITIONAL Operator
Purpose
The Conditional (or CASE
) operator evaluates conditional logic in a similar way to the IF
/ELSE
operator.
Syntax
CASE (expression) (WHEN expression THEN expression)+ (ELSE expression)? END
CASE (expression)? (!WHEN expression)?
(WHEN expression THEN expression)+ (ELSE expression)? END
Both Simple Case and Searched Case expressions are supported. The syntactic difference being that the Simple Case
expression has an expression after the CASE
keyword.
- Simple Case Expression
- If the
CASE
expression is equal to the firstWHEN
expression, the result is theTHEN
expression. - Otherwise, any subsequent
WHEN
clauses are evaluated in the same way. - If no match is found, the result of the
CASE
expression is theELSE
expression,NULL
if noELSE
expression was provided.
- If the
- Searched Case Expression
- If the first
WHEN
expression isTRUE
, the result of this expression is itsTHEN
expression. - Otherwise, subsequent
WHEN
clauses are evaluated in the same way. If noWHEN
clause evaluate toTRUE
, then the result of the expression is theELSE
expression, orNULL
if noELSE
expression was provided.
- If the first
Example
Example 17. Searched Case
Functions
In this section
Aggregation Functions | Array Functions | Conditional
Functions | Date and Time Functions | Full Text Search
Functions | Maths Functions | Metadata
Functions | Pattern Searching Functions | String
Functions | Type Checking Functions | Type Conversion
Functions
Purpose
Functions are also expressions.
Syntax
The function syntax is the same as Java’s method syntax. It starts with the function name, followed by optional arguments inside parentheses.
function = functionName parenExprs
functionName = IDENTIFIER
parenExprs = '(' ( expression (_ ',' _ expression )* )? ')'
Aggregation Functions
Table 10. Aggregation Functions
Function | Description |
---|---|
AVG(expr) |
Returns average value of the number values in the group |
COUNT(expr) |
Returns a count of all values in the group |
MIN(expr) |
Returns the minimum value in the group |
MAX(expr) |
Returns the maximum value in the group |
SUM(expr) |
Returns the sum of all number values in the group |
Array Functions
Table 11. Array Functions
Function | Description |
---|---|
ARRAY_AGG(expr) |
Returns an array of the non-MISSING group values in the input expression, including NULL values. |
ARRAY_AVG(expr) |
Returns the average of all non-NULL number values in the array; or NULL if there are none |
ARRAY_CONTAINS(expr) |
Returns TRUE if the value exists in the array; otherwise FALSE |
ARRAY_COUNT(expr) |
Returns the number of non-null values in the array |
ARRAY_IFNULL(expr) |
Returns the first non-null value in the array |
ARRAY_MAX(expr) |
Returns the largest non-NULL, non_MISSING value in the array |
ARRAY_MIN(expr) |
Returns the smallest non-NULL, non_MISSING value in the array |
ARRAY_LENGTH(expr) |
Returns the length of the array |
ARRAY_SUM(expr) |
Returns the sum of all non-NULL numeric value in the array |
Conditional Functions
Table 12. Conditional Functions
Function |
Description |
---|---|
IFMISSING(expr1, expr2, …) |
Returns the first non-MISSING value, or NULL if all values are MISSING |
IFMISSINGRONULL(expr1, expr2, …) |
Returns the first non-NULL and non-MISSING value, or NULL if all values are NULL or MISSING |
IFNULL(expr1, expr2, …) |
Returns the first non-NULL, or NULL if all values are NULL |
MISSINGIF(expr1, expr2) |
Returns MISSING when expr1 = expr2; otherwise returns expr1. Returns MISSING if either or both expressions are MISSING. Returns NULL if either or both expressions are NULL.+ |
NULLF(expr1, expr2) |
Returns NULL when expr1 = expr2; otherwise returns expr1. Returns MISSING if either or both expressions are MISSING. Returns NULL if either or both expressions are NULL.+ |
Date and Time Functions
Table 13. Date and Time Functions
Function |
Description |
---|---|
STR_TO_MILLIS(expr) |
Returns the number of milliseconds since the unix epoch of the given ISO 8601 date input string. |
STR_TO_UTC(expr) |
Returns the ISO 8601 UTC date time string of the given ISO 8601 date input string. |
MILLIS_TO_STR(expr) |
Returns a ISO 8601 date time string in device local timezone of the given number of milliseconds since the unix epoch expression. |
MILLIS_TO_UTC(expr) |
Returns the UTC ISO 8601 date time string of the given number of milliseconds since the unix epoch expression. |
Full Text Search Functions
Table 14. FTS Functions
Function |
Description | Example |
---|---|---|
MATCH(indexName, term) |
Returns TRUE if term expression matches the FTS indexed term. indexName identifies the FTS index, term expression to search for matching. |
WHERE MATCH (description, “couchbase”) |
RANK(indexName) |
Returns a numeric value indicating how well the current query result matches the full-text query when performing the MATCH . indexName is an IDENTIFIER for the FTS index. |
WHERE MATCH (description, “couchbase”) ORDER BY RANK(description) |
Maths Functions
Table 15. Maths Functions
Function | Description |
---|---|
ABS(expr) |
Returns the absolute value of a number. |
ACOS(expr) |
Returns the arc cosine in radians. |
ASIN(expr) |
Returns the arcsine in radians. |
ATAN(expr) |
Returns the arctangent in radians. |
ATAN2(expr1,expr2) |
Returns the arctangent of expr1/expr2. |
CEIL(expr) |
Returns the smallest integer not less than the number. |
COS(expr) |
Returns the cosine value of the expression. |
DIV(expr1, expr2) |
Returns float division of expr1 and expr2. Both expr1 and expr2 are cast to a double number before division. The returned result is always a double. |
DEGREES(expr) |
Converts radians to degrees. |
E() |
Returns base of natural logarithms. |
EXP(expr) |
Returns expr value |
FLOOR(expr) |
Returns largest integer not greater than the number. |
IDIV(expr1, expr2) |
Returns integer division of expr1 and expr2. |
LN(expr) |
Returns log base e value. |
LOG(expr) |
Returns log base 10 value. |
PI() |
Return PI value. |
POWER(expr1, expr2) |
Returns expr1expr2 value. |
RADIANS(expr) |
Returns degrees to radians. |
ROUND(expr (, digits_expr)?) |
Returns the rounded value to the given number of integer digits to the right of the decimal point (left if digits is negative). Digits are 0 if not given. The function uses Rounding Away From Zero convention to round midpoint values to the next number away from zero (so, for example, ROUND(1.75) returns 1.8 but ROUND(1.85) returns 1.9. * |
ROUND_EVEN(expr (, digits_expr)?) |
Returns rounded value to the given number of integer digits to the right of the decimal point (left if digits is negative). Digits are 0 if not given. The function uses Rounding to Nearest Even (Banker’s Rounding) convention which rounds midpoint values to the nearest even number (for example, both ROUND_EVEN(1.75) and ROUND_EVEN(1.85) return 1.8). |
SIGN(expr) |
Returns -1 for negative, 0 for zero, and 1 for positive numbers. |
SIN(expr) |
Returns sine value. |
SQRT(expr) |
Returns square root value. |
TAN(expr) |
Returns tangent value. |
TRUNC (expr (, digits, expr)?) |
Returns a truncated number to the given number of integer digits to the right of the decimal point (left if digits is negative). Digits are 0 if not given. |
* The behavior of the ROUND()
function is different from Server SQL++ ROUND()
, which rounds the midpoint
values using Rounding to Nearest Even convention.
Metadata Functions
Table 16. Metadata Functions
Function | Description | Example |
---|---|---|
META(dataSourceName?) |
Returns a dictionary containing metadata properties including:
|
SELECT META() FROM db SELECT META().id, META().sequence, META().deleted, META().expiration FROM db SELECT p.name, r.rating FROM product as p INNER JOIN reviews AS r ON META(r).id IN p.reviewList WHERE META(p).id = "product320" |
Pattern Searching Functions
Table 17. Pattern Searching Functions
Function | Description |
---|---|
REGEXP_CONTAINS(expr, pattern) |
Returns TRUE if the string value contains any sequence that matches the regular expression pattern. |
REGEXP_LIKE(expr, pattern) |
Return TRUE if the string value exactly matches the regular expression pattern. |
REGEXP_POSITION(expr, pattern) |
Returns the first position of the occurrence of the regular expression pattern within the input string expression. Return -1 if no match is found. Position counting starts from zero. |
REGEXP_REPLACE(expr, pattern, repl [, n]) |
Returns new string with occurrences of pattern replaced with repl. If n is given, at the most n replacements are performed. If n is not given, all matching occurrences are replaced. |
String Functions
Table 18. String Functions
Function | Description |
---|---|
CONTAINS(expr, substring_expr) |
Returns true if the substring exists within the input string, otherwise returns false. |
LENGTH(expr) |
Returns the length of a string. The length is defined as the number of characters within the string. |
LOWER(expr) |
Returns the lowercase string of the input string. |
LTRIM(expr) |
Returns the string with all leading whitespace characters removed. |
RTRIM(expr) |
Returns the string with all trailing whitespace characters removed. |
TRIM(expr) |
Returns the string with all leading and trailing whitespace characters removed. |
UPPER(expr) |
Returns the uppercase string of the input string. |
Type Checking Functions
Table 19. Type Checking Functions
Function | Description |
---|---|
ISARRAY(expr) |
Returns TRUE if expression is an array, otherwise returns MISSING, NULL or FALSE. |
ISATOM(expr) |
Returns TRUE if expression is a Boolean, number, or string, otherwise returns MISSING, NULL or FALSE. |
ISBOOLEAN(expr) |
Returns TRUE if expression is a Boolean, otherwise returns MISSING, NULL or FALSE. |
ISNUMBER(expr) |
Returns TRUE if expression is a number, otherwise returns MISSING, NULL or FALSE. |
ISOBJECT(expr) |
Returns TRUE if expression is an object (dictionary), otherwise returns MISSING, NULL or FALSE. |
ISSTRING(expr) |
Returns TRUE if expression is a string, otherwise returns MISSING, NULL or FALSE. |
TYPE(expr) |
Returns one of the following strings, based on the value of expression:
|
Type Conversion Functions
Table 20. Type Conversion Functions
Function | Description |
---|---|
TOARRAY(expr) |
Returns MISSING if the value is MISSING. Returns NULL if the value is NULL. Returns the array itself. Returns all other values wrapped in an array. |
TOATOM(expr) |
Returns MISSING if the value is MISSING. Returns NULL if the value is NULL. Returns an array of a single item if the value is an array. Returns an object of a single key/value pair if the value is an object. Returns boolean, numbers, or strings Returns NULL for all other values. |
TOBOOLEAN(expr) |
Returns MISSING if the value is MISSING. Returns NULL if the value is NULL. Returns FALSE if the value is FALSE. Returns FALSE if the value is 0 or NaN. Returns FALSE if the value is an empty string, array, and object. Return TRUE for all other values. |
TONUMBER(expr) |
Returns MISSING if the value is MISSING. Returns NULL if the value is NULL. Returns 0 if the value is FALSE. Returns 1 if the value is TRUE. Returns NUMBER if the value is NUMBER. Returns NUMBER parsed from the string value. Returns NULL for all other values. |
TOOBJECT(expr) |
Returns MISSING if the value is MISSING. Returns NULL if the value is NULL. Returns the object if the value is an object. Returns an empty object for all other values. |
TOSTRING(expr) |
Returns MISSING if the value is MISSING. Returns NULL if the value is NULL. Returns “false” if the value is FALSE. Returns “true” if the value is TRUE. Returns NUMBER in String if the value is NUMBER. Returns the string value if the value is a string. Returns NULL for all other values. |
QueryBuilder Differences
Couchbase Lite SQL++ Query supports all QueryBuilder
features, except Predictive Query and Index. See Table
21 for the features supported by SQL++ but not by QueryBuilder
.
Table 21. QueryBuilder Differences
Category | Components |
---|---|
Conditional Operator | CASE(WHEN … THEN … ELSE ..) |
Array Functions | ARRAY_AGG ARRAY_AVG ARRAY_COUNT ARRAY_IFNULL ARRAY_MAX ARRAY_MIN ARRAY_SUM |
Conditional Functions | IFMISSING IFMISSINGORNULL IFNULL MISSINGIF NULLIF |
Math Functions | DIV IDIV ROUND_EVEN |
Pattern Matching Functions | REGEXP_CONTAINS REGEXP_LIKE REGEXP_POSITION REGEXP_REPLACE |
Type Checking Functions | ISARRAY ISATOM ISBOOLEAN ISNUMBER ISOBJECT ISSTRING TYPE |
Type Conversion Functions | TOARRAY TOATOM TOBOOLEAN TONUMBER TOOBJECT TOSTRING |
Query Parameters
You can provide runtime parameters to your SQL++ query to make it more flexible.
To specify substitutable parameters within your query string prefix the name with $
, $type
— see Example
18.
Example 18. Running a SQL++ Query
- Define a parameter placeholder
$type
- Set the value of the
$type
parameter