SQL++ for Mobile
Description - How to use SQL++ Query Strings to build effective queries with Couchbase Lite for React Native
Related Content - Live Queries | Indexes
N1QL is Couchbase's implementation of the developing SQL++ standard. As such the terms N1QL and SQL++ are used interchangeably in all Couchbase documentation unless explicitly stated otherwise.
Introduction
Developers using Couchbase Lite for React Native can provide SQL++ query strings using the SQL++ Query API. This API uses query statements of the form shown in Example 1. 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
Use Database.createQuery to define a query through an SQL++ string. Then run the query using the Query.execute() method.
Example 1. Running a SQL++ Query
const query = database.createQuery('SELECT META().id AS thisId FROM inventory.hotel WHERE city="Medway"');
const resultSet = await query.execute();
Query Format
The API uses query statements of the form shown in Example 2.
Example 2. Query Format
SELECT ____
FROM ____
JOIN ____
WHERE ____
GROUP BY ____
ORDER BY ____
LIMIT ____
OFFSET ____
Query Components
- The
SELECTclause specifies the data to be returned in the result set. - The
FROMclause specifies the collection to query the documents from. - The
JOINclause specifies the criteria for joining multiple documents. - The
WHEREclause specifies the query criteria. TheSELECTed properties of documents matching this criteria will be returned in the result set. - The
GROUP BYclause specifies the criteria used to group returned items in the result set. - The
ORDER BYclause specifies the criteria used to order the items in the result set. - The
LIMITclause specifies the maximum number of results to be returned. - The
OFFSETclause specifies the number of results to be skipped before starting to return results.
We recommend working through the SQL++ Tutorials as a good way to build your SQL++ skills.
SELECT Clause
Purpose
Projects the result returned by the query, identifying the columns it will contain.
Syntax
Example 3. SQL++ Select Syntax
select = SELECT _ ( ( DISTINCT | ALL ) _ )? selectResults
selectResults = selectResult ( _? ',' _? selectResult )*
selectResult = expression ( ( _ AS )? _ columnAlias )?
columnAlias = IDENTIFIER
Arguments
-
The select clause begins with the
SELECTkeyword.- The optional
ALLargument is used to specify that the query should returnALLresults (the default). - The optional
DISTINCTargument is used to specify that the query should return distinct results.
- The optional
-
selectResultsis a list of columns projected in the query result. Each column is an expression which could be a property expression or any expression or function. You can use the*expression, to select all columns. -
Use the optional
ASargument to provides an alias for a column. Each column can be aliased by putting the alias name after the column name.
SELECT Wildcard
When using the * expression, the column name 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 SQL++ for Server - 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 users | users |
SELECT * FROM users AS user | user |
Example
Example 4. SELECT Examples
SELECT * ...;
SELECT user.* AS data ...;
SELECT name fullName ...;
SELECT user.name ...;
SELECT DISTINCT address.city ...;
- Use the
*expression to select all columns. - Select all properties from the
userdata source. Give the object an alias ofdata. - Select a pair of properties.
- Select a specific property from the
userdata source. - Select the property
cityfrom theaddressdata source.
FROM Clause
Purpose
Specifies the data source and optionally applies an alias (AS). It is mandatory.
Syntax
Example 5. FROM Syntax
from = FROM _ dataSource
dataSource = collectionName ( ( _ AS )? _ collectionAlias )?
collectionName = IDENTIFIER
collectionAlias = IDENTIFIER
Here dataSource is the collection name against which the query is to run. Use AS to give the collection an alias you can use within the query. To use the default collection, without specifying a name, use _ as the data source.
Example
Example 6. FROM Examples
SELECT name FROM testScope.user;
SELECT user.name FROM testScope.users AS user;
SELECT user.name FROM testScope.users user;
-- These queries use the default scope and default collection (_default._default) in Couchbase.
SELECT name FROM _default._default;
SELECT user.name FROM _default._default AS user;
SELECT user.name FROM _default._default user;
JOIN Clause
Purpose
The JOIN clause enables you to select data from multiple data sources linked by criteria specified in the ON constraint. Currently only self-joins are supported. For example to combine airline details with route details, linked by the airline id - see Example 7.
Syntax
Example 7. JOIN Syntax
join = joinOperator _ dataSource ( _ constraint )?
joinOperator = ( ( LEFT ( _ OUTER )? | INNER | CROSS ) _ )? JOIN
dataSource = collectionName ( ( _ AS )? _ collectionAlias )?
constraint = ON _ expression
collectionName = IDENTIFIER
collectionAlias = IDENTIFIER
Arguments
- The
JOINclause starts with aJOINoperator followed by the data source. - Five
JOINoperators are supported:JOIN,LEFT JOIN,LEFT OUTER JOIN,INNER JOIN, andCROSS JOIN.- Note:
JOINandINNER JOINare the same, andLEFT JOINandLEFT OUTER JOINare the same.
- The
JOINconstraint starts with theONkeyword followed by the expression that defines the joining constraints.
Example
Example 8. JOIN Examples
SELECT users.prop1, other.prop2
FROM testScope.users
JOIN users AS other ON users.key = other.key;
SELECT users.prop1, other.prop2
FROM testScope.users
LEFT JOIN users AS other ON users.key = other.key;
Example 9. Using JOIN to Combine Document Details
This example joins the documents from the routes collections with documents from the airlines collection using the document ID (id) of the airline document and the airlineId property of the route document.
SELECT *
FROM inventory.routes r
JOIN airlines a ON r.airlineId = META(a).id
WHERE a.country = "France";
WHERE Clause
Purpose
Specifies the selection criteria used to filter results. As with SQL, use the WHERE clause to choose which results are returned by your query.
Syntax
Example 10. WHERE Syntax
where = WHERE _ expression
Arguments
WHEREevalates the expression to aBOOLEANvalue. You can combine any number of expressions through logical operators, in order to implement sophisticated filtering capabilities.
Example
Example 11. WHERE Examples
SELECT name
FROM testScope.employees
WHERE department = "engineer" AND group = "mobile"
GROUP BY Clause
Purpose
Use GROUP BY to group results for aggreation, based on one or more expressions.
Syntax
Example 12. GROUP BY Syntax
groupBy = grouping ( _ having )?
grouping = GROUP BY _ expression ( _? ',' _? expression )*
having = HAVING _ expression
Arguments
- The
GROUP BYclause starts with theGROUP BYkeyword followed by one or more expressions. - The
GROUP BYclause is normally used together with aggregate functions (e.g.COUNT,MAX,MIN,SUM,AVG). - The
HAVINGclause allows you to filter the results based on aggregate functions - for example,HAVING COUNT(airlineId) > 100.
Example
Example 13. GROUP BY Examples
SELECT COUNT(airlineId), destination
FROM inventory.routes
GROUP BY destination;
SELECT COUNT(airlineId), destination
FROM inventory.routes
GROUP BY destination
HAVING COUNT(airlineId) > 100;
SELECT COUNT(airlineId), destination
FROM inventory.routes
WHERE destinationState = "CA"
GROUP BY destination
HAVING COUNT(airlineId) > 100;
ORDER BY Clause
Purpose
Sort query results based on a expression.
Syntax
Example 14. ORDER BY Syntax
orderBy = ORDER BY _ ordering ( _? ',' _? ordering )*
ordering = expression ( _ order )?
order = ( ASC | DESC )
Arguments
- The
ORDER BYclause starts with theORDER BYkeyword followed by one or more ordering expressions. - An ordering expression specifies an expressions to use for ordering the results.
- For each ordering expression, the sorting direction can be specified using the optional
ASC(ascending) orDESC(descending) directives. Default isASC.
Example
Example 15. ORDER BY Examples
SELECT name
FROM testScope.users
ORDER BY name;
SELECT name
FROM testScope.users
ORDER BY name DESC;
SELECT name, score
FROM testScope.users
ORDER BY name ASC, score DESC;
LIMIT Clause
Purpose
Specifies the maximum number of results to be returned by the query.