Selecting Data

Selecting (i.e. retrieving) data from CrateDB is done by using a SQL SELECT statement. The response to a SELECT query contains the column names of the result, the actual result rows as a two-dimensional array of values, the row count and the duration.

Table of Contents

Introduction

A simple select:

  1. cr> select name, position from locations order by id limit 2;
  2. +-------------------+----------+
  3. | name | position |
  4. +-------------------+----------+
  5. | North West Ripple | 1 |
  6. | Arkintoofle Minor | 3 |
  7. +-------------------+----------+
  8. SELECT 2 rows in set (... sec)

If the ‘*’ operator is used, all columns defined in the schema are returned for each row:

  1. cr> select * from locations order by id limit 1 offset 1;
  2. +----...-+--------------...-+----+-------------+--...-+--...-+----------+------------------...-+
  3. | date | description | id | information | kind | name | position | race |
  4. +----...-+--------------...-+----+-------------+--...-+--...-+----------+------------------...-+
  5. | 308... | Motivated by ... | 10 | NULL | P... | A... | 3 | {"description": ...} |
  6. +----...-+--------------...-+----+-------------+--...-+--...-+----------+------------------...-+
  7. SELECT 1 row in set (... sec)

Aliases can be used to change the output name of the columns:

  1. cr> select name as n
  2. ... from locations
  3. ... where name = 'North West Ripple';
  4. +-------------------+
  5. | n |
  6. +-------------------+
  7. | North West Ripple |
  8. +-------------------+
  9. SELECT 1 row in set (... sec)

FROM Clause

The FROM clause is used to reference the relation this select query is based upon. Can be a single table, many tables, a view, a JOIN or another SELECT statement. See SELECT Reference

Tables and views are referenced by schema and table name and can optionally be aliased. If the relation t is only referenced by name, CrateDB assumes the relation doc.t was meant. Schemas that were newly created using CREATE TABLE must be referenced explicitly.

The two following queries are equivalent:

  1. cr> select name, position from locations
  2. ... order by name desc nulls last limit 2;
  3. +-------------------+----------+
  4. | name | position |
  5. +-------------------+----------+
  6. | Outer Eastern Rim | 2 |
  7. | North West Ripple | 1 |
  8. +-------------------+----------+
  9. SELECT 2 rows in set (... sec)
  1. cr> select doc.locations.name as n, position from doc.locations
  2. ... order by name desc nulls last limit 2;
  3. +-------------------+----------+
  4. | n | position |
  5. +-------------------+----------+
  6. | Outer Eastern Rim | 2 |
  7. | North West Ripple | 1 |
  8. +-------------------+----------+
  9. SELECT 2 rows in set (... sec)

A table can be aliased for the sake of brevity too:

  1. cr> select name from doc.locations as l
  2. ... where l.name = 'Outer Eastern Rim';
  3. +-------------------+
  4. | name |
  5. +-------------------+
  6. | Outer Eastern Rim |
  7. +-------------------+
  8. SELECT 1 row in set (... sec)

Joins

Note

CrateDB currently supports only a limited set of JOINs.

See the Joins for current state.

DISTINCT Clause

If DISTINCT is specified, one unique row is kept. All other duplicate rows are removed from the result set:

  1. cr> select distinct date from locations order by date;
  2. +---------------+
  3. | date |
  4. +---------------+
  5. | 308534400000 |
  6. | 1367366400000 |
  7. | 1373932800000 |
  8. +---------------+
  9. SELECT 3 rows in set (... sec)

Note

Using DISTINCT is only supported on Primitive Types.

WHERE Clause

A simple where clause example using an equality operator:

  1. cr> select description from locations where id = '1';
  2. +---------------------------------------...--------------------------------------+
  3. | description |
  4. +---------------------------------------...--------------------------------------+
  5. | Relative to life on NowWhat, living on... a factor of about seventeen million. |
  6. +---------------------------------------...--------------------------------------+
  7. SELECT 1 row in set (... sec)

Comparison Operators

These Comparison Operators are supported and can be used for all simple data types.

For strings a lexicographical comparison is performed based on the Lucene TermRangeQuery:

  1. cr> select name from locations where name > 'Argabuthon' order by name;
  2. +------------------------------------+
  3. | name |
  4. +------------------------------------+
  5. | Arkintoofle Minor |
  6. | Bartledan |
  7. | Galactic Sector QQ7 Active J Gamma |
  8. | North West Ripple |
  9. | Outer Eastern Rim |
  10. +------------------------------------+
  11. SELECT 5 rows in set (... sec)

For details please refer to the Apache Lucene site.

Number and date field comparison behave as expected from standard SQL.

The following example uses one of the supported ISO date formats:

  1. cr> select date, position from locations where date <= '1979-10-12' and
  2. ... position < 3 order by position;
  3. +--------------+----------+
  4. | date | position |
  5. +--------------+----------+
  6. | 308534400000 | 1 |
  7. | 308534400000 | 2 |
  8. +--------------+----------+
  9. SELECT 2 rows in set (... sec)

For a detailed explanation of the supported ISO date formats please refer to the joda date_optional_time site.

For custom date types, or defined date formats in the object mapping the corresponding format should be used for a comparison. Otherwise the operation may fail.

Regular Expressions

Operators for matching using regular expressions.

OperatorDescriptionExample
~Matches regular expression, case sensitive
  1. foo ~ ‘.foo.
~Matches regular expression, case insensitive
  1. Foo ~ ‘.foo.
!~Does not match regular expression, case sensitive
  1. Foo !~ ‘.foo.
!~Does not match regular expression, case insensitive
  1. foo !~ ‘.bar.

The ~ operator can be used to match a string against a regular expression. It returns true if the string matches the pattern, false if not, and NULL if string is NULL.

To negate the matching, use the optional ! prefix. The operator returns true if the string does not match the pattern, false otherwise.

The regular expression pattern is implicitly anchored, that means that the whole string must match, not a single subsequence. All unicode characters are allowed.

If using PCRE features in the regular expression pattern, the operator uses the regular expression engine of the Java standard library java.util.regex.

If not using PCRE features in the regular expression pattern, the operator uses Lucene Regular Expressions, which are optimized for fast regular expression matching on Lucene terms.

Lucene Regular Expressions are basically POSIX Extended Regular Expressions without the character classes and with some extensions, like a metacharacter # for the empty string or ~ for negation and others. By default all Lucene extensions are enabled. See the Lucene documentation for more details.

Note

Since case-insensitive matching using ~* or !~* implicitly uses the regular expression engine of the Java standard library, features of Lucene Regular Expressions do not work there.

Examples:

  1. cr> select name from locations where name ~ '([A-Z][a-z0-9]+)+'
  2. ... order by name;
  3. +------------+
  4. | name |
  5. +------------+
  6. | Aldebaran |
  7. | Algol |
  8. | Altair |
  9. | Argabuthon |
  10. | Bartledan |
  11. +------------+
  12. SELECT 5 rows in set (... sec)
  1. cr> select 'matches' from sys.cluster where
  2. ... 'gcc --std=c99 -Wall source.c' ~ '[A-Za-z0-9]+( (-|--)[A-Za-z0-9]+)*( [^ ]+)*';
  3. +-----------+
  4. | 'matches' |
  5. +-----------+
  6. | matches |
  7. +-----------+
  8. SELECT 1 row in set (... sec)
  1. cr> select 'no_match' from sys.cluster where 'foobaz' !~ '(foo)?(bar)$';
  2. +------------+
  3. | 'no_match' |
  4. +------------+
  5. | no_match |
  6. +------------+
  7. SELECT 1 row in set (... sec)

LIKE

CrateDB supports the LIKE operator. This operator can be used to query for rows where only part of a columns value should match something. For example to get all locations where the name starts with ‘Ar’ the following query can be used:

  1. cr> select name from locations where name like 'Ar%' order by name asc;
  2. +-------------------+
  3. | name |
  4. +-------------------+
  5. | Argabuthon |
  6. | Arkintoofle Minor |
  7. +-------------------+
  8. SELECT 2 rows in set (... sec)

The following wildcard operators are available:

%A substitute for zero or more characters
_A substitute for a single character

The wildcard operators may be used at any point in the string literal. For example a more complicated like clause could look like this:

  1. cr> select name from locations where name like '_r%a%' order by name asc;
  2. +------------+
  3. | name |
  4. +------------+
  5. | Argabuthon |
  6. +------------+
  7. SELECT 1 row in set (... sec)

In order so search for the wildcard characters themselves it is possible to escape them using a backslash:

  1. cr> select description from locations
  2. ... where description like '%\%' order by description asc;
  3. +-------------------------+
  4. | description |
  5. +-------------------------+
  6. | The end of the Galaxy.% |
  7. +-------------------------+
  8. SELECT 1 row in set (... sec)

Caution

Queries with a like clause can be quite slow. Especially if the like clause starts with a wildcard character. Because in that case CrateDB has to iterate over all rows and can’t utilize the index. For better performance consider using a fulltext index.

NOT

NOT negates a boolean expression:

  1. [ NOT ] boolean_expression

The result type is boolean.

expressionresult
truefalse
falsetrue
nullnull

Warning

CrateDB handles the case of NOT (NULL) inconsistently. The above is only true when the NOT appears in a SELECT clause or a WHERE clause that operates on system tables. The result of NOT (NULL) in a WHERE clause that operates on user tables will produce inconsistent but deterministic results (NULL or TRUE) depending on the specifics of the clause. This does not adhere to standard SQL three-valued-logic and will be fixed in a future release.

IN

CrateDB also supports the binary operator IN, which allows you to verify the membership of left-hand operand in a right-hand set of expressions. Returns true if any evaluated expression value from a right-hand set equals left-hand operand. Returns false otherwise:

  1. cr> select name, kind from locations
  2. ... where (kind in ('Star System', 'Planet')) order by name asc;
  3. +---------------------+-------------+
  4. | name | kind |
  5. +---------------------+-------------+
  6. | | Planet |
  7. | Aldebaran | Star System |
  8. | Algol | Star System |
  9. | Allosimanius Syneca | Planet |
  10. | Alpha Centauri | Star System |
  11. | Altair | Star System |
  12. | Argabuthon | Planet |
  13. | Arkintoofle Minor | Planet |
  14. | Bartledan | Planet |
  15. +---------------------+-------------+
  16. SELECT 9 rows in set (... sec)

The IN construct can be used in Subquery Expressions or Array Comparisons.

IS NULL

Returns TRUE if expr evaluates to NULL. Given a column reference it returns TRUE if the field contains NULL or is missing.

Use this predicate to check for NULL values as SQL’s three-valued logic does always return NULL when comparing NULL.

expr:Expression of one of the supported Data Types supported by CrateDB.
  1. cr> select name from locations where race is null order by name;
  2. +------------------------------------+
  3. | name |
  4. +------------------------------------+
  5. | |
  6. | Aldebaran |
  7. | Algol |
  8. | Allosimanius Syneca |
  9. | Alpha Centauri |
  10. | Altair |
  11. | Argabuthon |
  12. | Galactic Sector QQ7 Active J Gamma |
  13. | North West Ripple |
  14. | Outer Eastern Rim |
  15. | NULL |
  16. +------------------------------------+
  17. SELECT 11 rows in set (... sec)
  1. cr> select count(*) from locations where name is null;
  2. +----------+
  3. | count(*) |
  4. +----------+
  5. | 1 |
  6. +----------+
  7. SELECT 1 row in set (... sec)

IS NOT NULL

Returns TRUE if expr does not evaluate to NULL. Additionally, for column references it returns FALSE if the column does not exist.

Use this predicate to check for non-NULL values as SQL’s three-valued logic does always return NULL when comparing NULL.

expr:Expression of one of the supported Data Types supported by CrateDB.
  1. cr> select name from locations where race['interests'] is not null;
  2. +-------------------+
  3. | name |
  4. +-------------------+
  5. | Arkintoofle Minor |
  6. | Bartledan |
  7. +-------------------+
  8. SELECT 2 rows in set (... sec)
  1. cr> select count(*) from locations where name is not null;
  2. +----------+
  3. | count(*) |
  4. +----------+
  5. | 12 |
  6. +----------+
  7. SELECT 1 row in set (... sec)

ANY (array)

The ANY (or SOME) operator allows to search for elements within arrays. This allows to query for rows where an element of an array is, for example, equal to or greater than some expression.

The following example returns any row where the array race['interests'] contains an element ‘netball’:

  1. cr> select race['name'], race['interests'] from locations
  2. ... where 'netball' = ANY(race['interests']);
  3. +----------------+-----------------------------------------+
  4. | race['name'] | race['interests'] |
  5. +----------------+-----------------------------------------+
  6. | Bartledannians | ["netball", "books with 100.000 words"] |
  7. +----------------+-----------------------------------------+
  8. SELECT 1 row in set (... sec)
  1. cr> select race['name'], race['interests'] from locations
  2. ... where 'books%' LIKE ANY(race['interests']);
  3. +----------------+-----------------------------------------+
  4. | race['name'] | race['interests'] |
  5. +----------------+-----------------------------------------+
  6. | Bartledannians | ["netball", "books with 100.000 words"] |
  7. +----------------+-----------------------------------------+
  8. SELECT 1 row in set (... sec)

It can also be used on arrays:

  1. cr> select name, race['interests'] from locations
  2. ... where name = ANY(ARRAY['Bartledan', 'Algol'])
  3. ... order by name asc;
  4. +-----------+-----------------------------------------+
  5. | name | race['interests'] |
  6. +-----------+-----------------------------------------+
  7. | Algol | NULL |
  8. | Bartledan | ["netball", "books with 100.000 words"] |
  9. +-----------+-----------------------------------------+
  10. SELECT 2 rows in set (... sec)

This way it can be used as a shortcut for name = 'Bartledan' OR name = 'Algol' or any other ANY comparison.

The ANY construct can be used in Subquery Expressions or Array Comparisons.

Negating ANY

One important thing to notice when using ANY is that negating the ANY operator does not behave as negating normal comparison operators.

The following query can be translated to get all rows where race[‘interests’] has at least one element that equals ‘netball’:

  1. cr> select race['name'], race['interests'] from locations
  2. ... where 'netball' = ANY(race['interests']);
  3. +----------------+-----------------------------------------+
  4. | race['name'] | race['interests'] |
  5. +----------------+-----------------------------------------+
  6. | Bartledannians | ["netball", "books with 100.000 words"] |
  7. +----------------+-----------------------------------------+
  8. SELECT 1 row in set (... sec)

The following query using the negated operator != can be translated to get all rows where race[‘interests’] has at least one element that does not equal ‘netball’. As you see, the result is the same in this case:

  1. cr> select race['name'], race['interests'] from locations
  2. ... where 'netball' != ANY(race['interests']);
  3. +----------------+-----------------------------------------+
  4. | race['name'] | race['interests'] |
  5. +----------------+-----------------------------------------+
  6. | Minories | ["baseball", "short stories"] |
  7. | Bartledannians | ["netball", "books with 100.000 words"] |
  8. +----------------+-----------------------------------------+
  9. SELECT 2 rows in set (... sec)

Note

When using the negated operator != ANY by default the maximum size of the array to operate on is 8192. To be able to use larger arrays the indices.query.bool.max_clause_count setting must be changed appropriately on each node.

Negating the = query from above is totally different. It can be translated to get all rows where race[‘interests’] has no value that equals ‘netball’:

  1. cr> select race['name'], race['interests'] from locations
  2. ... where not 'netball' = ANY(race['interests']) order by race['name'];
  3. +--------------+-------------------------------+
  4. | race['name'] | race['interests'] |
  5. +--------------+-------------------------------+
  6. | Minories | ["baseball", "short stories"] |
  7. +--------------+-------------------------------+
  8. SELECT 1 row in set (... sec)

Tip

When using NOT <value> = ANY(<array_col>) the performance of the query could be quite bad, because special handling is required to implement the 3-valued logic#Comparisonswith_NULL_and_the_three-valued_logic(3VL)). To achieve better performance, consider using the ignore3vl function.

The same behaviour (though different comparison operations involved) holds true for operators

  • LIKE and NOT LIKE
  • all other comparison operators (excluding IS NULL and IS NOT NULL)

Note

When using the operators LIKE ANY and NOT LIKE ANY by default the maximum size of the array to operate on is 8192. To be able to use larger arrays the indices.query.bool.max_clause_count setting must be changed appropriately on each node.

Limits

As unlimited SELECT queries could break your cluster if the matching rows exceed your node’s RAM, SELECT statements are limited by default to 10000 rows.

You can expand this limit by using an explicit LIMIT-clause.

But you are encouraged to make use of a windowing using LIMIT and OFFSET to iterate through all the results of a potentially large resultset instead of expanding the default limit.

When using the PostgreSQL wire protocol, there is no implicit 10000 row limit on SELECT statements.

Note

The sum of LIMIT and OFFSET may not exceed 2147483630 (which is Lucene’s MAX_ARRAY_LENGTH).

Inner Objects and Nested Objects

CrateDB supports an object data type, used for simple storing a whole object into a column and it’s even possible to select and query for properties of such objects.

Select a property of an inner object:

  1. cr> select name, race['name'] from locations where name = 'Bartledan';
  2. +-----------+----------------+
  3. | name | race['name'] |
  4. +-----------+----------------+
  5. | Bartledan | Bartledannians |
  6. +-----------+----------------+
  7. SELECT 1 row in set (... sec)

Query for a property of an inner object:

  1. cr> select name, race['name'] from locations
  2. ... where race['name'] = 'Bartledannians';
  3. +-----------+----------------+
  4. | name | race['name'] |
  5. +-----------+----------------+
  6. | Bartledan | Bartledannians |
  7. +-----------+----------------+
  8. SELECT 1 row in set (... sec)

Inserting objects:

  1. cr> insert into locations (id, name, position, kind, race)
  2. ... values ('DO', 'Dornbirn', 14, 'City', {name='Vorarlberger',
  3. ... description = 'Very nice people with a strange accent',
  4. ... interests = ['mountains', 'cheese', 'enzian']}
  5. ... );
  6. INSERT OK, 1 row affected (... sec)

Object Arrays

Arrays in CrateDB can be queried for containment using the ANY (array) operator.

It is possible to access fields of Inner Objects and Nested Objects using subscript expressions. If the parent is an object array, you’ll get an array of the selected field.

Examples:

  1. cr> select name, information['population'] from locations
  2. ... where information['population'] is not null
  3. ... order by name;
  4. +-------------------+---------------------------+
  5. | name | information['population'] |
  6. +-------------------+---------------------------+
  7. | North West Ripple | [12, 42] |
  8. | Outer Eastern Rim | [5673745846] |
  9. +-------------------+---------------------------+
  10. SELECT 2 rows in set (... sec)
  1. cr> select information from locations
  2. ... where information['population'] is not null
  3. ... order by name;
  4. +----------------------------------------------------...-----------------------+
  5. | information |
  6. +----------------------------------------------------...-----------------------+
  7. | [{"evolution_level": 4, "population": 12}, {"evolu...": 42, "popul...": 42}] |
  8. | [{"evolution_level": 2, "population": 5673745846}] |
  9. +---------------------------------------------------...------------------------+
  10. SELECT 2 rows in set (... sec)
  1. cr> insert into locations (id, name, position, kind, information)
  2. ... values (
  3. ... 'B', 'Berlin', 15, 'City',
  4. ... [{evolution_level=6, population=3600001},
  5. ... {evolution_level=42, population=1}]
  6. ... );
  7. INSERT OK, 1 row affected (... sec)
  1. cr> refresh table locations;
  2. REFRESH OK, 1 row affected (... sec)
  1. cr> select name from locations where 4 < ANY (information['evolution_level'])
  2. ... order by name;
  3. +-------------------+
  4. | name |
  5. +-------------------+
  6. | Berlin |
  7. | North West Ripple |
  8. +-------------------+
  9. SELECT 2 rows in set (... sec)

Note

Although it is possible to use ? = ANY (object_array) it’s usage is discouraged as it cannot utilize the index and has to do the equivalent of a table scan.

Selecting Array Elements

Array elements can be selected directly using a integer value greater than or equal to 1. The maximum supported array index is 2147483648. Using an index greater than the actual array size results in a NULL value.

  1. cr> select name, information[1]['population'] as population from locations
  2. ... where information['population'] is not null
  3. ... order by name;
  4. +-------------------+------------+
  5. | name | population |
  6. +-------------------+------------+
  7. | Berlin | 3600001 |
  8. | North West Ripple | 12 |
  9. | Outer Eastern Rim | 5673745846 |
  10. +-------------------+------------+
  11. SELECT 3 rows in set (... sec)

Note

Only 1 array notation inside a subscript expression is supported, e.g. following won’t work:

select information[1][tags][1] from locations;

Data Aggregation

CrateDB supports Aggregation via the following aggregation functions.

Aggregation works across all the rows that match a query or on all matching rows in every distinct group of a GROUP BY statement. Aggregating SELECT statements without GROUP BY will always return one row.

NameArgumentsDescriptionReturn Type
ARBITRARYcolumn name of a primitive typed column (all but object)Returns an undefined value of all the values in the argument column. Can be NULL.the input column type or NULL if some value of the matching rows in that column is NULL
AVG / MEANcolumn name of a numeric or timestamp columnReturns the arithmetic mean of the values in the argument column. NULL-values are ignored.double or NULL if all values of all matching rows in that column are NULL
COUNT(*)star as parameter or as constantCounts the number of rows that match the query.long
COUNTcolumn nameCounts the number of rows that contain a non NULL value for the given column.long
COUNT(DISTINCT col)column nameCounts the number of distinct values for the given column that are not NULL.long
GEOMETRIC_MEANcolumn name of a numeric or timestamp columnComputes the geometric mean for positive numbers.double or NULL if all values of all matching rows in that are NULL or if a value is negative.
MINcolumn name of a numeric, timestamp or string columnReturns the smallest of the values in the argument column in case of strings this means the lexicographically smallest. NULL-values are ignoredthe input column type or NULL if all values in that matching rows in that column are NULL
MAXcolumn name of a numeric, timestamp or string columnReturns the biggest of the values in the argument column in case of strings this means the lexicographically biggest. NULL-values are ignoredthe input column type or NULL if all values of all matching rows in that column are NULL
STDDEVcolumn name of a numeric or timestamp columnReturns the standard deviation of the values in the argument column. NULL-values are ignored.double or NULL if all values are NULL or we got no value at all
SUMcolumn name of a numeric or timestamp columnReturns the sum of the values in the argument column. NULL-values are ignored.double or NULL if all values of all matching rows in that column are NULL
VARIANCEcolumn name of a numeric or timestamp columnReturns the variance of the values in the argument column. NULL-values are ignored.double or NULL if all values are NULL or we got no value at all

Some Examples:

  1. cr> select count(*) from locations;
  2. +----------+
  3. | count(*) |
  4. +----------+
  5. | 15 |
  6. +----------+
  7. SELECT 1 row in set (... sec)
  1. cr> select count(*) from locations where kind = 'Planet';
  2. +----------+
  3. | count(*) |
  4. +----------+
  5. | 5 |
  6. +----------+
  7. SELECT 1 row in set (... sec)
  1. cr> select count(name), count(*) from locations;
  2. +-------------+----------+
  3. | count(name) | count(*) |
  4. +-------------+----------+
  5. | 14 | 15 |
  6. +-------------+----------+
  7. SELECT 1 row in set (... sec)
  1. cr> select max(name) from locations;
  2. +-------------------+
  3. | max(name) |
  4. +-------------------+
  5. | Outer Eastern Rim |
  6. +-------------------+
  7. SELECT 1 row in set (... sec)
  1. cr> select min(date) from locations;
  2. +--------------+
  3. | min(date) |
  4. +--------------+
  5. | 308534400000 |
  6. +--------------+
  7. SELECT 1 row in set (... sec)
  1. cr> select count(*), kind from locations
  2. ... group by kind order by kind asc;
  3. +----------+-------------+
  4. | count(*) | kind |
  5. +----------+-------------+
  6. | 2 | City |
  7. | 4 | Galaxy |
  8. | 5 | Planet |
  9. | 4 | Star System |
  10. +----------+-------------+
  11. SELECT 4 rows in set (... sec)
  1. cr> select max(position), kind from locations
  2. ... group by kind order by max(position) desc;
  3. +---------------+-------------+
  4. | max(position) | kind |
  5. +---------------+-------------+
  6. | 15 | City |
  7. | 6 | Galaxy |
  8. | 5 | Planet |
  9. | 4 | Star System |
  10. +---------------+-------------+
  11. SELECT 4 rows in set (... sec)
  1. cr> select min(name), kind from locations
  2. ... group by kind order by min(name) asc;
  3. +------------------------------------+-------------+
  4. | min(name) | kind |
  5. +------------------------------------+-------------+
  6. | | Planet |
  7. | Aldebaran | Star System |
  8. | Berlin | City |
  9. | Galactic Sector QQ7 Active J Gamma | Galaxy |
  10. +------------------------------------+-------------+
  11. SELECT 4 rows in set (... sec)
  1. cr> select count(*), min(name), kind from locations
  2. ... group by kind order by kind;
  3. +----------+------------------------------------+-------------+
  4. | count(*) | min(name) | kind |
  5. +----------+------------------------------------+-------------+
  6. | 2 | Berlin | City |
  7. | 4 | Galactic Sector QQ7 Active J Gamma | Galaxy |
  8. | 5 | | Planet |
  9. | 4 | Aldebaran | Star System |
  10. +----------+------------------------------------+-------------+
  11. SELECT 4 rows in set (... sec)
  1. cr> select sum(position) as sum_positions, kind from locations
  2. ... group by kind order by sum_positions;
  3. +---------------+-------------+
  4. | sum_positions | kind |
  5. +---------------+-------------+
  6. | 10 | Star System |
  7. | 13 | Galaxy |
  8. | 15 | Planet |
  9. | 29 | City |
  10. +---------------+-------------+
  11. SELECT 4 rows in set (... sec)

Window Functions

CrateDB supports the OVER clause to enable the execution of window functions:

  1. cr> select sum(position) OVER(), name from locations order by name;
  2. +-----------------------+------------------------------------+
  3. | sum(position) OVER () | name |
  4. +-----------------------+------------------------------------+
  5. | 67 | |
  6. | 67 | Aldebaran |
  7. | 67 | Algol |
  8. | 67 | Allosimanius Syneca |
  9. | 67 | Alpha Centauri |
  10. | 67 | Altair |
  11. | 67 | Argabuthon |
  12. | 67 | Arkintoofle Minor |
  13. | 67 | Bartledan |
  14. | 67 | Berlin |
  15. | 67 | Dornbirn |
  16. | 67 | Galactic Sector QQ7 Active J Gamma |
  17. | 67 | North West Ripple |
  18. | 67 | Outer Eastern Rim |
  19. | 67 | NULL |
  20. +-----------------------+------------------------------------+
  21. SELECT 15 rows in set (... sec)

GROUP BY

CrateDB supports the group by clause. This clause can be used to group the resulting rows by the value(s) of one or more columns. That means that rows that contain duplicate values will be merged together.

This is useful if used in conjunction with aggregation functions:

  1. cr> select count(*), kind from locations
  2. ... group by kind order by count(*) desc, kind asc;
  3. +----------+-------------+
  4. | count(*) | kind |
  5. +----------+-------------+
  6. | 5 | Planet |
  7. | 4 | Galaxy |
  8. | 4 | Star System |
  9. | 2 | City |
  10. +----------+-------------+
  11. SELECT 4 rows in set (... sec)

Note

All columns that are used either as result column or in the order by clause have to be used within the group by clause. Otherwise the statement won’t execute.

Grouping will be executed against the real table column when aliases that shadow the table columns are used.

Grouping on multi-value fields doesn’t work. If such a field is encountered during a group by operation an error is thrown.

Additionally, grouping can only be applied to columns with a plain index, which is the default for all columns.

For more information, refer to Plain index (Default).

HAVING

The having clause is the equivalent to the where clause for the resulting rows of a group by clause.

A simple having clause example using an equality operator:

  1. cr> select count(*), kind from locations
  2. ... group by kind having count(*) = 4 order by kind;
  3. +----------+-------------+
  4. | count(*) | kind |
  5. +----------+-------------+
  6. | 4 | Galaxy |
  7. | 4 | Star System |
  8. +----------+-------------+
  9. SELECT 2 rows in set (... sec)

The condition of the having clause can refer to the resulting columns of the group by clause.

It is also possible to use aggregates in the having clause just like in the result columns:

  1. cr> select count(*), kind from locations
  2. ... group by kind having min(name) = 'Berlin';
  3. +----------+------+
  4. | count(*) | kind |
  5. +----------+------+
  6. | 2 | City |
  7. +----------+------+
  8. SELECT 1 row in set (... sec)
  1. cr> select count(*), kind from locations
  2. ... group by kind having count(*) = 4 and kind like 'Gal%';
  3. +----------+--------+
  4. | count(*) | kind |
  5. +----------+--------+
  6. | 4 | Galaxy |
  7. +----------+--------+
  8. SELECT 1 row in set (... sec)

Note

Aliases are not supported in the having clause.