2.1 - Table Basics
How to create and remove tables
Though Genji stores its data in tables, there is no concept of rows or columns. A Genji table is simply a collection of documents.
Each document is assigned to a primary key, which is a unique identifier.
The order in which documents are returned when reading a table is not guaranteed unless sorted explicitly.
Unlike relational databases, tables are schemaless, there is no need to specify a schema when creating one.
This means that, by default, documents stored in a table can be completely different from one another.
Optionally, it is possible to define constraints on a list of fields, to control their type, if they are required or not, if they can be null, etc. for every document of a table.
To create a table with no constraints, use the CREATE TABLE
command.
This will create a table teams
that can hold any document. An auto-incrementing primary key will be generated every time a document is inserted.
Creating a table with constraints uses a notation that is close to other relational databases.
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
address.zipCode TEXT
)
This will create a table users
with the following constraints:
- All documents must have a non-empty
id
field, whose type can be converted to an integer. This field will be used as the primary key of the table and will be stored as an integer.
- All documents must have a non-empty
name
field that can be converted to TEXT
.
- If a document has an
age
field, it will be converted to an integer.
- If a document has an
address
field and its value is a document with a zipCode
field, then its value will be converted to TEXT
. Note that this constraint uses field references.
Unlike relational databases though, a document doesn’t have to contain only the fields described in the constraint list. A constraint only applies to its associated field.
CREATE TABLE
will return an error if the table already exists.
To remove a table and all of its content, use the DROP TABLE
command:
This will remove the users
table and all of its documents. If DROP TABLE
is called on a non-existing table, it will return an error.
2.2 - Documents
Description of documents
Genji stores records as documents. A document is an object that contains pairs that associate a string field to a value of any type.
Genji SQL represents documents as JSON objects, though they support far more types.
Here is a JSON representation of the structure of a document:
{
field1: value1,
field2: value2,
field3: value3,
...
}
Example of a document using Genji SQL syntax:
{
name: "Nintendo Switch",
price: {
base: 379.99,
vat: 20,
total: base + base * vat / 100
},
brand: "Nintendo",
"top-selling-games": [
"Mario Odyssey",
"Zelda Breath of the Wild"
]
}
Each field name must be a string, but values can be of any type, including another document, an array or an expression.
Any JSON object is a valid document and can be inserted as-is.
Field names
Field names can be any string, with only one exception: they cannot be empty.
Paths
A path is a way to refer to fields of a document or elements of an array.
Given the following document:
{
"name": "Foo",
"address": {
"city": "Lyon",
"zipcode": "69001"
},
"friends": [
{
"name": "Bar",
"address": {
"city": "Paris",
"zipcode": "75001"
}
},
{
"name": "Baz",
"address": {
"city": "Ajaccio",
"zipcode": "20000"
},
"favorite game": "FF IX"
}
]
}
Accessing a top-level field can be achieved by simply referring to its name.
Example: name
will evaluate to "Foo"
.
To access a nested field, concatenate all the fields with the .
character.
Examples: address.city
will evaluate to "Lyon"
To access an element of an array, use the index of the element
Examples:
friends[0]
will evaluate to {"name": "Bar","address": {"city":"Paris","zipcode": "75001"}}
friends[1].name
will evaluate to "Baz"
friends[1]."favorite game"
will evaluate to "ffix"
2.4 - Expressions
How expression are evaluated, compared, etc.
Expressions are components that can be evaluated to a value.
Example:
1 + 1 # expression
-> 2 # result
An expression can be found in two forms:
- unary: meaning it contains only one component
- binary: meaning it contains two expressions, or operands, and one operator. i.e.
<expr> <operator> <expr>
Example:
/* Unary expressions */
1
name
"foo"
/* Binary expressions */
age >= 18
1 AND 0
Here is a list of all supported expressions:
Diagram(
Choice(
0,
Link("literal-value"),
Link("parameter"),
Link("field-path"),
Sequence("NOT", Link("expr")),
Sequence(Link("expr"), Link("binary-operator", "#operators"), Link("expr")),
Sequence(
Link("expr"),
Optional("NOT"),
Choice(
0,
Link("IN", "#comparison-operators"),
Link("LIKE", "#comparison-operators")
),
Link("expr")
),
Sequence(
Link("expr"),
Link("IS", "#comparison-operators"),
Optional("NOT"),
Link("expr")
),
Sequence(
Link("expr"),
Optional("NOT"),
Link("BETWEEN", "#comparison-operators"),
Link("expr"),
"AND",
Link("expr")
),
Sequence(
Link("function", "#functions"),
"(",
OneOrMore(Link("expr"), ","),
")"
),
Sequence("CAST", "(", Link("expr"), "AS", "type-name", ")"),
Sequence("NEXT", "VALUE", "FOR", "sequence-name"),
Sequence("(", Link("expr"), ")")
)
);
Literal value
Any literal evaluates to the closest compatible type.
Diagram(
Choice(
0,
Link("integer-literal"),
Link("number-literal"),
Link("string-literal"),
Link("blob-literal"),
Link("bool-literal"),
Link("array-literal"),
Link("document-literal"),
"NULL"
)
);
Integer literal
Diagram(Sequence(Optional(Choice(0, "+", "-")), OneOrMore("digit")));
An integer literal is a sequence of characters that only contain digits. They may start with a +
or -
sign.
Integer literals are evaluated into the INTEGER
type.
If an integer is bigger than the maximum value of a 64 bit integer or smaller than the minimum 64 bit integer value, it will be evaluated as a DOUBLE
.
Number literal
Diagram(
Sequence(
Choice(
0,
Sequence(OneOrMore("digit")),
Sequence(OneOrMore("digit"), ".", OneOrMore("digit")),
Sequence(".", OneOrMore("digit"))
),
Optional(
Sequence(
Choice(0, "e", "E"),
Optional(Choice(0, "+", "-")),
OneOrMore("digit")
)
)
)
);
A number literal is a sequence of characters that contains three parts:
- a sequence of digits
- a decimal point (i.e.
.
)
- a sequence of digits
They may start with a +
or a -
sign.
Number literals are evaluated to the DOUBLE
type.
String literal
Diagram(
Choice(
0,
Sequence('"', ZeroOrMore("unicode-character"), '"'),
Sequence("'", ZeroOrMore("unicode-character"), "'")
)
);
A string literal is a sequence of utf-8 encoded characters surrounded by double or single quotes. They may contain any unicode character or escaped single or double quotes (i.e \'
or \"
).
"l'école des fans"
'(╯ಠ_ಠ)╯︵ ┳━┳'
'foo \''
String literals are evaluated to the TEXT
type.
Blob literal
Diagram(
Choice(
0,
Sequence('"\\x', ZeroOrMore("hexadecimal-character"), '"'),
Sequence("'\\x", ZeroOrMore("hexadecimal-character"), "'")
)
);
A blob literal starts with \x
followed by a list of hexadecimal characters which is then decoded into raw bytes by Genji.
Blob literals are evaluated to the BLOB
type.
Bool literal
Diagram(Choice(0, "TRUE", "FALSE"));
A boolean literal is any sequence of character that is written as true
or false
, regardless of the case.
true
false
TRUE
FALSE
tRUe
FALse
Boolean literals are evaluated into the BOOL
type.
Array literal
Diagram(
Choice(
0,
Sequence("[", OneOrMore(Link("expr"), ","), "]"),
Sequence("(", OneOrMore(Link("expr"), ","), ")")
)
);
An array literal is any sequence of character that starts and ends with either:
and that contains a coma-separated list of expressions.
[1.5, "hello", 1 > 10, [true, -10], {foo: "bar"}]
Array literals are evaluated into the ARRAY
type.
Document literal
Diagram(
"{",
OneOrMore(
Sequence(Choice(0, "identifier", "string"), ":", Link("expr")),
","
),
"}"
);
A document is any sequence of character that starts and ends with {
and }
and that contains a list of pairs.
Each pair associates an identifier with an expression, both separated by a colon. Each pair must be separated by a coma.
{
foo: 1,
bar: "hello",
baz: true AND false,
"long field": {
a: 10
}
}
In a document, the identifiers are referred to as fields.
In the example above, the document has four top-level fields (foo
, bar
, baz
and long field
) and one nested field a
.
Note that any JSON object is a valid document.
Document literals are evaluated into the DOCUMENT
type.
Identifier
Diagram(
Choice(
0,
OneOrMore(Choice(0, "ascii-letter", "digit", "_")),
Sequence("`", OneOrMore("unicode-character"), "`")
)
);
Identifiers are a sequence of characters that refer to table names, field names and index names.
Identifiers may be unquoted or surrounded by backquotes. Depending on that, different rules may apply.
Unquoted identifiers |
Identifiers surrounded by backquotes |
Must begin with an uppercase or lowercase ASCII character or an underscore |
May contain any unicode character, other than the new line character (i.e. \n ) |
May contain only ASCII letters, digits and underscore |
May contain escaped " character (i.e. \" ) |
foo
_foo_123_
`頂きます (*`▽´)_旦~~`
`foo \` bar`
Field path
Diagram(
Sequence(
"identifier",
Optional(
OneOrMore(
Choice(
0,
Sequence(".", "identifier"),
Sequence("[", "integer-literal", "]"),
Sequence("[", "string-literal", "]")
),
","
),
"skip"
)
)
);
A field path is any sequence of characters that contains one or more identifiers separated by dots or square brackets.
foo
foo.bar[10]
foo["long field"][0].bat.`other long field`
Depending on the context, a single identifier with no dot or square bracket will be parsed as an identifier or as a field path.
Field paths are evaluated into the value they refer to.
They are used to select a value from a document.
Their type will depend on the type of the value extracted from the document.
Given the following document:
{
"recipes": 10,
"cooking-time": {
"eggs": [3, 6, 9]
},
}
Here are examples on how field paths are evaluated:
recipes
-> 10
`cooking-time`
-> {
"eggs": [
3,
6,
9
]
}
`cooking-time`.eggs[2]
-> 9
`cooking-time`.eggs[10]
-> NULL
Parameter
Diagram(Choice(0, "?", "$identifier"));
A parameters is an expressions used to represent a value passed when the query is evaluated.
Genji supports two types of parameters:
- Positional parameters:
?
- Named parameters:
$
followed by an identifier
Functions
Diagram(
Sequence(
"identifier",
Optional(Sequence(".", "identifier"), "skip"),
"(",
ZeroOrMore(Link("expr"), ","),
")"
)
);
A function name is an expression that represent a builtin function.
It can either represent a global function or a function within a package.
count()
typeof("hello")
math.atan2(1.1, 1.1)
Operators
Diagram(
Choice(
0,
"||",
"*",
"/",
"%",
"+",
"-",
"|",
"&",
"^",
">",
">=",
"<",
"<=",
"=",
"!=",
"IS",
"IN",
"LIKE",
"AND",
"OR"
)
);
Genji provides a list of operators that can be used to compute operations with expressions.
Operators are binary expressions, meaning they always take exactly two operands.
It is possible though to combine multiple operators to create an evaluation tree.
Logical operators
Logical operators are operators that return a boolean under certain conditions.
Name |
Description |
AND |
Evaluates to true if both operands are truthy |
OR |
Evaluates to true if either the left operand or the right are truthy |
An expression is truthy if it evaluates to a non zero-value of its type.
Comparison operators
These operators are used to compare values and evaluate to a boolean.
Name |
Description |
= |
Evaluates to true if operands are equal, otherwise returns false |
!= |
Evaluates to true if operands are not equal, otherwise returns false |
> |
Evaluates to true if the left-side expression is greater than the right-side expression, otherwise returns false |
>= |
Evaluates to true if the left-side expression is greater than or equal to the right-side expression, otherwise returns false |
< |
Evaluates to true if the left-side expression is less than the right-side expression, otherwise returns false |
<= |
Evaluates to true if the left-side expression is less than or equal to the right-side expression, otherwise returns false |
IN |
Evaluates to true if the left-side expression is equal to one of the values of the right-side array |
NOT IN |
Evaluates to false if the left-side expression is equal to one of the values of the right-side array |
IS |
Has the same behaviour as = except that it returns true if both operands are NULL |
IS NOT |
Has the same behaviour as != except that it supports comparing with NULL |
BETWEEN |
Evaluates to true if the left-side expression is between the two boundaries |
Examples:
1 = 1
-> true
1 > 2.5
-> false
3 IN [1, 2, 3]
-> true
5 BETWEEN 2 AND 10
-> true
Conversion during comparison
Prior to comparison, an implicit conversion is operated for the operands to be of the same type.
Not all types can be compared together. When two incompatible types are compared, the comparison always returns false
,
except if one of the operands is NULL, in that case it returns NULL.
Example:
The comparison follows a list of rules that are executed in order:
- If one of the operands is NULL, return
NULL
.
- If both operands are documents, use the Comparing documents rule
- If both operands are arrays, use the Comparing arrays rule
- If both operands are numbers (INTEGER or DOUBLE), cast the integer to DOUBLE then compare them together.
- If both operands have the same type, compare them together.
In any other case, return false
.
Comparing documents
The fields of each document are sorted, then they are compared one by one, until they are found not equal. The comparison is then determined by the result of the comparison between these two values.
If both keys are equal, compare the values.
{a: 1, b: 2} = {b: 2, a: 1}
-> true
{} = {}
-> true
{a: 1, b: 3} > {a: 1, b: 2}
-> true
{a: 100} > {aa: 1}
-> false
Comparing arrays
Each elements of both arrays are compared one by one, index by index, until they are found not equal. The comparison is then determined by the result of the comparison between these two values.
[1, 2, 3] > [1, 1 + 1, 1]
-> true
Let’s break down the example above:
- Index 0:
1
and 1
are equal, the comparison continues
- Index 1:
2
and 1 + 1
are equal, the comparison continues
- Index 2:
3
is greater then 1
, the comparison stops and the first array is considered greater than the second one
Two empty arrays are considered equal:
The size of arrays doesn’t matter, unless all the elements of the smallest one are equal to the other one. In that case the biggest array is considered greater.
[3] > [1, 100000]
-> true
[1, 2] < [1, 2, 3]
-> true
Arithmetic operators
Name |
Description |
+ |
Adding two values |
- |
Substracting two values |
* |
Multiplying two values |
/ |
Dividing two values |
% |
Find the remainder after division of one number by another |
& |
Bitwise AND |
| |
Bitwise OR |
^ |
Bitwise XOR |
Arithmetic operations are supported only for the following types:
Note that INTEGER
and DOUBLE
types can be calculated together, in that case INTEGER
values will be converted to DOUBLE
prior the operation.
Any usage of these operators on incompatible types will return NULL
.
3 + 3.5
-> 6.5
3 + '1'
-> NULL
The case of NULL
Any arithmetic operation with one of the operand being NULL
returns NULL
.
NULL + 1
-> NULL
5 * 10 - NULL
-> NULL
Division rules
The division obeys a few rules depending on the types of the operands:
- Dividing two integers, always results in an integer
- Dividing by zero, returns
NULL
Return type and overflow
The type of the result of an operation doesn’t necessarily match the type of the operands.
- The result of a DOUBLE operation will always return a DOUBLE
- The result of an INTEGER operation will return an INTEGER, unless the return value is bigger than the maximum value of 64-bit integer. In that case, the return type will be a DOUBLE
Other operators
Name |
Description |
|| |
Concatenation of two TEXT values |
Evaluation tree and precedence
When parsed, an expression is turned into an evaluation tree so it is possible to combine operators to form complex expressions.
The order in which these expressions are executed depends on the priority of the operator.
Here is the list of operators ordered by ascending precedence. Operators with higher precedence are executed before the ones with lower precedence
OR
AND
=
, !=
, <
, <=
, >
, >=
+
, -
, |
, ^
*
, /
, %
, &
||
Example:
3 + 4 * 2 > 10 AND 2 - 2 = false
-> true
This expression can be represented as the following tree:
.
└── AND
├── >
│ ├── +
│ │ ├── 3
│ │ └── *
│ │ ├── 4
│ │ └── 2
│ └── 10
└── -
├── 2
└── 2
The deepest branches will be executed first, recursively until reaching the root.
2.5 - Inserting Documents
How to use the INSERT statement to insert documents in a table
When a table is created, it contains no documents. The INSERT
statement can be used to add one or more new documents to the table.
Inserting documents in tables with no field constraints
Consider a table created with the following statement:
This table doesn’t have any constraint and thus can contain any kind of documents.
Let’s insert a document:
INSERT INTO users (name, age) VALUES ("Gon", 13);
Let’s break it down:
INSERT INTO users
: tells Genji to run the statement on the users
table
(name, age)
: lists the fields of the document we wish to create
VALUES ("Gon", 13)
: list the respective values of these fields in order
Here is the JSON representation of the document created by this statement:
{
"name": "Gon",
"age": 13
}
It is possible to create multiple documents in the same statement:
INSERT INTO users (name, age) VALUES ("Gon", 13), ("Kirua", 14);
This will create two documents in the users
table:
{
"name": "Gon",
"age": 13
}
{
"name": "Kirua",
"age": 14
}
Until now, we created documents with the same shape, but nothing prevents us from inserting documents with different fields:
INSERT INTO users (name, address) VALUES ("Kurapika", {city: "York Shin City", "region": "Yorubian"});
INSERT INTO users (first_name, `last name`, skills) VALUES ("Zeno", 'Zoldik', ["Dragon Dive", "Dragon Head"] );
It is also possible to omit the list of fields and use a document literal:
INSERT INTO users VALUES {name: "Hisoka", "age": "unknown"}
Note that in this example, the age
field type is TEXT
. It’s because field types don’t have to match those of the documents created previously, documents are independent and self-contained.
Inserting documents in tables with field constraints
Now, let’s consider having the following table:
CREATE TABLE users (
id INTEGER PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
age INTEGER
)
Only documents satisfying the following field constraints can be inserted in the users
table:
- the document must have a non-null
id
field. It must be convertible to an INTEGER
. Since this field will be used as the primary key of the table, each id
must be unique.
- the document must have a non-null
name
field. It must be convertible to a TEXT
.
- the document may have an
age
field. If it exists, it must be convertible to an INTEGER
.
- the document may have any other fields.
The conversion compatible table can be found in the data types page.
To see how it works, let’s try inserting invalid documents:
/* totally different fields */
INSERT INTO users (first_name, alias) VALUES ('Genthru', 'The Bomber');
Error:
field “id” is required and must be not null
Let’s add an id
:
INSERT INTO users (id, first_name, alias) VALUES (1, 'Genthru', 'The Bomber');
Error:
field “name” is required and must be not null
This time, it complains about the name
field which is absent. Let’s change that:
INSERT INTO users (id, name, alias) VALUES (1, 'Genthru', 'The Bomber');
It works!
Since age
doesn’t have a NOT NULL
clause, it didn’t complain.
Also, the document contains an alias
field and Genji didn’t complain. Field constraints only apply on the field they are associated with, they don’t care about the other ones. That’s what makes Genji different from “schemaful” databases, where the schema describes exactly the number of columns a row must always have.
Let’s add another one with an age field:
INSERT INTO users (id, name, age) VALUES (1, 'Biscuit', 57);
Error:
duplicate document
This time we used the same id
as before. Since 1
is already used by Genthru, let’s pick another one:
INSERT INTO users (id, name, age) VALUES (1, 'Biscuit', 57);
It works!
Inserting documents from another table
It is also possible to insert documents selected from another table, using the INSERT ... SELECT
notation.
-- create a new table to store the list of all of our users names
CREATE TABLE names(name TEXT);
-- select all non-null names and store them in that new table.
INSERT INTO names SELECT name FROM users WHERE name IS NOT NULL;
2.8 - Selecting Documents
How to use the SELECT statement to query documents in a table
Querying documents from a table can be achieved by using the SELECT
statement.
In the Genji database, a query does two things:
- it reads documents from a table
- it uses the arguments of the query to transform, filter and project that data to create a result, which is a stream of documents.
This stream of documents can be consumed by the caller one by one, and each document will contain the fields the user chose.
Consider the following table:
CREATE TABLE users;
INSERT INTO users (name, age, nen, parents, abilities) VALUES
('Gon', 13, 'Enhancement', {'father': 'Ging Freecs'}, ['Jajanken']),
(
'Kirua', 14, 'Transmutation',
{'father': 'Silva Zoldyck', 'mother': 'Kikyo Zoldyck'},
['Lighning Palm', 'Thunderbolt', 'Godspeed']
);
INSERT INTO users (name, nen, abilities) VALUES
('Hisoka', 'Transmutation', ['Bungee Gum', 'Texture Surprise']);
Querying all the documents
Selecting all users goes like this:
{
"name": "Gon",
"age": 13,
"nen": "Enhancement",
"parents": {
"father": "Ging Freecs"
},
"abilities": ["Jajanken"]
}
{
"name": "Kirua",
"age": 14,
"nen": "Transmutation",
"parents": {
"father": "Silva Zoldyck",
"mother": "Kikyo Zoldyck"
},
"abilities": ["Lighning Palm", "Thunderbolt", "Godspeed"]
}
{
"name": "Hisoka",
"nen": "Transmutation",
"abilities": ["Bungee Gum", "Texture Surprise"]
}
Let’s break it down:
SELECT
: Run the SELECT command
*
: This is the projection, it indicates how to build the documents returned by the result of the query. Here, we are using a special projection called the wildcard, which is a way to tell Genji to simply project all of the fields of each document.
FROM users
: Indicates from which table we want to query the data.
Understanding projections
Now, let’s query only the name and age of each user:
SELECT name, age FROM users;
{
"name": "Gon",
"age": 13,
}
{
"name": "Kirua",
"age": 14,
}
{
"name": "Hisoka",
"age": null
}
The result contains three documents, all of them have a name
and age
fields.
A projection guarantees that all the documents returned by the query will contain the selected fields, even if the original documents don’t have that information. In our example, the Hisoka
document doesn’t have an age
field, so its projected value is null
.
The only exception is for the *
wildcard, which projects all the fields of the original document.
Querying nested fields
Let’s determine who is the father of our users:
SELECT name, parents.father FROM users;
{
"name": "Gon",
"parents.father": "Ging Freecs"
}
{
"name": "Kirua",
"parents.father": "Silva Zoldyck"
}
{
"name": "Hisoka",
"parents.father": null
}
In this example, we used a field reference to select the parents.father
field of our users.
Let’s add the information about the first ability they master:
SELECT name, parents.father, abilities[0] FROM users;
{
"name": "Gon",
"parents.father": "Ging Freecs",
"abilities[0]": "Jajanken"
}
{
"name": "Kirua",
"parents.father": "Silva Zoldyck",
"abilities[0]": "Lighning Palm"
}
{
"name": "Hisoka",
"parents.father": null,
"abilities[0]": "Bungee Gum"
}
abilities[0]
is a dot notation that indicates to select the element at index 0
of the abilities
array.
Controlling the name of projected fields
The result of the query above contains fields named parents.father
and abilities[0]
, which isn’t that great. Let’s rename them to more clean names:
SELECT name, parents.father AS father, abilities[0] AS main_skill FROM users;
{
"name": "Gon",
"father": "Ging Freecs",
"main_skill": "Jajanken"
}
{
"name": "Kirua",
"father": "Silva Zoldyck",
"main_skill": "Lighning Palm"
}
{
"name": "Hisoka",
"father": null,
"main_skill": "Bungee Gum"
}
The AS
clause allows creating aliases to rename projected fields.
Filter documents
Until now, we always performed our queries on every document of the table.
Let’s only query those whose nen
field is Transmutation
.
SELECT name FROM users WHERE nen = 'Transmutation';
{
"name": "Kirua"
}
{
"name": "Hisoka"
}
This time, the result contains only two documents.
The WHERE
clause allows filtering the documents returned. To do that, it evaluates an expression on every document:
- if the result of the evaluation is truthy, the document is selected
- if the result of the evaluation is falsy, the document is filtered out
SELECT name, age FROM users WHERE age < 14;
{
"name": "Gon",
"age": 13
}
In this example, only Gon satisfies the query:
- Kirua’s age is greater 14 which is not
< 14
- Hisoka’s age is
null
, which is also not < 14
Filtering on values in nested objects
We can filter on values in nested arrays using the IN
operator:
SELECT * FROM users WHERE 'Bungee Gum' IN abilities;
{
"name": "Hisoka",
"nen": "Transmutation",
"abilities": ["Bungee Gum", "Texture Surprise"]
}
And values in nested documents using dot notation:
SELECT * FROM users WHERE parents.father = 'Silva Zoldyck';
{
"name": "Kirua",
"age": 14,
"nen": "Transmutation",
"parents": {
"father": "Silva Zoldyck",
"mother": "Kikyo Zoldyck"
},
"abilities": ["Lighning Palm", "Thunderbolt", "Godspeed"]
}
Ordering results
The order in which results are returned can be controlled, using the ORDER BY
clause
SELECT name, age FROM users ORDER BY age;
{
"name": "Hisoka",
"age": null
}
{
"name": "Gon",
"age": 13
}
{
"name": "Kirua",
"age": 14
}
The order in which documents will appear depends on three factors:
- the direction or the order
- the type of the field used for ordering
- the value of the field used for ordering
By default, the direction is ascending, from the smallest value to the highest.
When it comes to ordering, there is a hierarchy between types:
NULL
< BOOLEAN
< numbers < TEXT
or BLOB
In the example above, the age
field of Hisoka doesn’t exist, so it is treated as null
, and then appears first in the result.
Then, Gon and Kirua have an age
field which is an INTEGER
, there are compared with each other and returned in ascending order.
The direction can be controlled by using ASC
or DESC
clauses.
SELECT name, age FROM users ORDER BY age ASC;
// returns the same results as above
SELECT name, age FROM users ORDER BY age DESC;
{
"name": "Kirua",
"age": 14
}
{
"name": "Gon",
"age": 13
}
{
"name": "Hisoka",
"age": null
}
Limiting and skipping results
The LIMIT
clause is executed after WHERE
and ORDER BY
and allows controlling the number of final results.
SELECT name FROM users WHERE nen = 'Transmutation' ORDER BY age DESC LIMIT 1;
LIMIT
must be followed by the number of maximum results. In this example, we limited the results to 1.
It is also possible to skip results, using the OFFSET
clause. It is executed after the WHERE
and ORDER BY
clauses, but right before LIMIT
.
SELECT name FROM users ORDER BY name LIMIT 2 OFFSET 1;
{
"name": "Hisoka"
}
{
"name": "Kirua"
}
Using functions
Projections can also use functions to add more power to the queries.
Select the primary key
Every document has a primary key, which is a unique value identifying it.
When a document is inserted without an explicit primary key, an implicit one is created automatically. Implicit primary key don’t appear in the results though, even when using SELECT *
.
To select them, we can use the pk()
function.
SELECT pk(), name FROM users;
{
"name": "Gon",
"pk()": 1
}
{
"name": "Kirua",
"pk()": 2
}
{
"name": "Hisoka",
"pk()": 3
}
3.5 - CREATE TABLE
Define a new table
Synopsis
CREATE TABLE statement
Diagram(
Stack(
Sequence(
"CREATE",
"TABLE",
Optional(Sequence("IF", "NOT", "EXISTS"), "skip"),
Sequence(Link("table-name"))
),
Choice(
0,
Sequence(
OneOrMore(Link("field-definition"), ","),
Optional(
Sequence(",", OneOrMore(Link("table-constraint"), ",")),
"skip"
)
),
Sequence(OneOrMore(Link("table-constraint"), ","))
)
)
);
Parameters
IF NOT EXISTS
Do not throw an error if a table with the same name already exists.
table-name
The name of the table to be created.
Field definition
Diagram(
Link("field-path", "/docs/essentials/expressions/#field-path"),
OptionalSequence(
Link("type-name", "/docs/essentials/data-types"),
OneOrMore(Link("field-constraint"))
)
);
table-name
The name of the table to be created.
Field constraint
Diagram(
Choice(
0,
Sequence("PRIMARY", "KEY"),
Sequence("UNIQUE"),
Sequence("NOT", "NULL"),
Sequence(
"DEFAULT",
Choice(
0,
Sequence("(", Link("expr", "/docs/essentials/expressions"), ")"),
Sequence(Link("expr", "/docs/essentials/expressions"))
)
),
Sequence("CHECK", "(", Link("expr", "/docs/essentials/expressions"), ")")
)
);
Table constraint
Diagram(
Choice(
0,
Sequence(
"PRIMARY",
"KEY",
"(",
Link("field-path", "/docs/essentials/expressions/#field-path"),
")"
),
Sequence(
"UNIQUE",
"KEY",
"(",
Link("field-path", "/docs/essentials/expressions/#field-path"),
")"
),
Sequence("CHECK", "(", Link("expr", "/docs/essentials/expressions"), ")")
)
);