Selecting data

Selecting (i.e., retrieving) data from CrateDB can be done by using an SQL SELECT statement. The response to a SELECT query includes the column names of the result, the result rows as a two-dimensional array of values, the row count, and the execution time.

Introduction

A simple select:

  1. cr> select id, name from locations order by id limit 2;
  2. +----+-------------------+
  3. | id | name |
  4. +----+-------------------+
  5. | 1 | North West Ripple |
  6. | 2 | Outer Eastern Rim |
  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 2;
  2. +----+-------------------+--------------+--------+----------+-------------...-+-----------+
  3. | id | name | date | kind | position | description ... | landmarks |
  4. +----+-------------------+--------------+--------+----------+-------------...-+-----------+
  5. | 1 | North West Ripple | 308534400000 | Galaxy | 1 | Relative to ... | NULL |
  6. | 2 | Outer Eastern Rim | 308534400000 | Galaxy | 2 | The Outer Ea... | NULL |
  7. +----+-------------------+--------------+--------+----------+-------------...-+-----------+
  8. SELECT 2 rows 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.

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

Here is a simple WHERE clause 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

CrateDB supports a variety of comparison operators (including basic operators such as =, <, >, and so on).

Regular expressions

Comparison operators for matching using regular expressions:

Operator

Description

Example

~

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 (ILIKE)

CrateDB supports the LIKE and ILIKE operators. These operators can be used to query for rows where only part of a columns value should match something. The only difference is that, in the case of ILIKE, the matching is case insensitive.

For example to get all locations where the name starts with Ar the following queries 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)
  1. cr> select name from locations where name ilike '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

LIKE and ILIKE clauses can slow a query down, especially when used in combination with wildcard characters. This is because CrateDB has to iterate over all rows for the comparison and cannot utilize the index.

For better performance, consider using fulltext search.

NOT

NOT negates a boolean expression:

  1. [ NOT ] boolean_expression

The result type is boolean.

expression

result

true

false

false

true

null

null

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 inhabitants is null order by name;
  2. +------------------------------------+
  3. | name |
  4. +------------------------------------+
  5. | |
  6. | Aldebaran |
  7. | Algol |
  8. | Allosimanius Syneca |
  9. | Alpha Centauri |
  10. | Altair |
  11. | Galactic Sector QQ7 Active J Gamma |
  12. | North West Ripple |
  13. | Outer Eastern Rim |
  14. | NULL |
  15. +------------------------------------+
  16. SELECT 10 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 inhabitants['interests'] is not null;
  2. +-------------------+
  3. | name |
  4. +-------------------+
  5. | Arkintoofle Minor |
  6. | Bartledan |
  7. | Argabuthon |
  8. +-------------------+
  9. SELECT 3 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)

Array comparisons

CrateDB supports a variety of array comparisons.

IN

CrateDB supports the operator IN which allows you to verify the membership of the left-hand operator 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.

ANY (array)

The ANY (or SOME) operator allows you to query elements within arrays.

For example, this query returns any row where the array inhabitants['interests'] contains a netball element:

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

This query combines the ANY operator with the LIKE operator:

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

This query passes a literal array value to the ANY operator:

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

This query selects any locations with at least one (i.e., ANY) population figure above 100:

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

Note

It is possible to use ANY to compare values directly against the properties of object arrays, as above. However, this usage is discouraged as it cannot utilize the table index and requires the equivalent of a table scan.

The ANY operator can be used in subquery expressions and array comparisons.

Negating ANY

Negating the ANY operator does not behave like other comparison operators.

The following query negates ANY using != to return all rows where inhabitants['interests'] has at least one array element that is not netball:

  1. cr> select inhabitants['name'], inhabitants['interests'] from locations
  2. ... where 'netball' != ANY(inhabitants['interests']);
  3. +---------------------+------------------------------+
  4. | inhabitants['name'] | inhabitants['interests'] |
  5. +---------------------+------------------------------+
  6. | Minories | ["netball", "short stories"] |
  7. | Argabuthonians | ["science", "reason"] |
  8. +---------------------+------------------------------+
  9. SELECT 2 rows in set (... sec)

Note

When using the != ANY(<array_col>)) syntax, the default maximum size of the array can be 8192. To use larger arrays, you must configure the indices.query.bool.max_clause_count setting as appropriate on each node.

Negating the same query with a preceding not returns all rows where inhabitants['interests'] has no netball element:

  1. cr> select inhabitants['name'], inhabitants['interests'] from locations
  2. ... where not 'netball' = ANY(inhabitants['interests']);
  3. +---------------------+--------------------------+
  4. | inhabitants['name'] | inhabitants['interests'] |
  5. +---------------------+--------------------------+
  6. | Argabuthonians | ["science", "reason"] |
  7. +---------------------+--------------------------+
  8. SELECT 1 row in set (... sec)

This behaviour applies to:

  • LIKE and NOT LIKE

  • All other comparison operators (excluding IS NULL and IS NOT NULL)

Note

When using the NOT with ANY, the performance of the query may be poor because special handling is required to implement the 3-valued logic#Comparisonswith_NULL_and_the_three-valued_logic(3VL)). For better performance, consider using the ignore3vl function.

Additionally, When using NOT with LIKE ANY or NOT LIKE ANY, the default maximum size of the array can be 8192. To use larger arrays, you must configure the indices.query.bool.max_clause_count setting as appropriate on each node.

Container data types

Arrays

CrateDB supports arrays. It is possible to select and query array elements.

For example, you might insert an array like so:

  1. cr> insert into locations (id, name, position, kind, landmarks)
  2. ... values (14, 'Frogstar', 4, 'Star System',
  3. ... ['Total Perspective Vortex', 'Milliways']
  4. ... );
  5. INSERT OK, 1 row affected (... sec)

The result:

  1. cr> select name, landmarks from locations
  2. ... where name = 'Frogstar';
  3. +----------+-------------------------------------------+
  4. | name | landmarks |
  5. +----------+-------------------------------------------+
  6. | Frogstar | ["Total Perspective Vortex", "Milliways"] |
  7. +----------+-------------------------------------------+
  8. SELECT 1 row in set (... sec)

The individual array elements can be selected from the landmarks column with landmarks[n], where n is the integer array index, like so:

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

Note

The first index value is 1. The maximum array index is 2147483648. Using an index greater than the array size results in a NULL value.

Individual array elements can also be addressed in the where clause, like so:

  1. cr> select name, landmarks from locations
  2. ... where landmarks[2] = 'Milliways';
  3. +----------+-------------------------------------------+
  4. | name | landmarks |
  5. +----------+-------------------------------------------+
  6. | Frogstar | ["Total Perspective Vortex", "Milliways"] |
  7. +----------+-------------------------------------------+
  8. SELECT 1 row in set (... sec)

When using the = operator, as above, the value of the array element at index n is compared. To compare against any array element, see ANY (array).

Objects

CrateDB supports objects. It is possible to select and query object properties.

For example, you might insert an object like so:

  1. cr> insert into locations (id, name, position, kind, inhabitants)
  2. ... values (15, 'Betelgeuse', 2, 'Star System',
  3. ... {name = 'Betelgeuseans',
  4. ... description = 'Humanoids with two heads'}
  5. ... );
  6. INSERT OK, 1 row affected (... sec)

The result:

  1. cr> select name, inhabitants from locations
  2. ... where name = 'Betelgeuse';
  3. +------------+----------------------------------------------------------------------+
  4. | name | inhabitants |
  5. +------------+----------------------------------------------------------------------+
  6. | Betelgeuse | {"description": "Humanoids with two heads", "name": "Betelgeuseans"} |
  7. +------------+----------------------------------------------------------------------+
  8. SELECT 1 row in set (... sec)

The object properties can be selected from the inhabitants column with inhabitants['property'], where property is the property name, like so:

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

Object property can also be addressed in the where clause, like so:

  1. cr> select name, inhabitants from locations
  2. ... where inhabitants['name'] = 'Betelgeuseans';
  3. +------------+----------------------------------------------------------------------+
  4. | name | inhabitants |
  5. +------------+----------------------------------------------------------------------+
  6. | Betelgeuse | {"description": "Humanoids with two heads", "name": "Betelgeuseans"} |
  7. +------------+----------------------------------------------------------------------+
  8. SELECT 1 row in set (... sec)

Nested structures

Objects may contain arrays and arrays may contain objects. These nested structures can be selected and queried.

For example, you might insert something like this:

  1. cr> insert into locations (id, name, position, kind, inhabitants, information)
  2. ... values (16, 'Folfanga', 4, 'Star System',
  3. ... {name = 'A-Rth-Urp-Hil-Ipdenu',
  4. ... description = 'A species of small slug',
  5. ... interests = ['lettuce', 'slime']},
  6. ... [{evolution_level=42, population=1},
  7. ... {evolution_level=6, population=3600001}]
  8. ... );
  9. INSERT OK, 1 row affected (... sec)

The query above includes:

  • An array nested within an object. Specifically, the inhabitants column contains an parent object with an interests property set to a child array of strings (e.g., lettuce).

  • Objects nested within an array. Specifically, the information column contains a parent array with two child objects (e.g., {evolution_level=42, population=1}).

Arrays within objects

The child array (above) can be selected as a property of the parent object:

  1. cr> select name, inhabitants['interests'] from locations
  2. ... where name = 'Folfanga';
  3. +----------+--------------------------+
  4. | name | inhabitants['interests'] |
  5. +----------+--------------------------+
  6. | Folfanga | ["lettuce", "slime"] |
  7. +----------+--------------------------+
  8. SELECT 1 row in set (... sec)

Individual elements of the child array can be selected by combining the array index syntax with the object property name syntax, like so:

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

Caution

The example above might surprise you because the child array index comes before the parent object property name, which doesn’t follow the usual left-to-right convention for addressing the contents of a nested structure.

Due to an implementation quirk in early versions of CrateDB, the array index always comes first (see the next subsection for more information). Support for a more traditional left-to-right syntax may be added in the future.

Limitations

There are two limitations to be aware of:

  • You cannot directly nest an array within an array (i.e., array(array(...) is not a valid column definition). You can, however, nest multiple arrays as long as an object comes between them (e.g., array(object as (array(...))) is a valid).

  • Using the standard syntax, you can only address the elements of one array in a single expression. If you do address the elements of an array, the array index must appear before any object property names (see the previous admonition for more information).

Tip

If you want to address the elements of more than one array in a single expression, you can use the following non-standard syntax:

  1. select foo[n1]['bar']::text[][n2] from my_table;

Here, n1 is the index of the first array (column foo) and n2 is the index of the second array (object property bar).

This works by:

  1. Type casting the second array (i.e., foo[n1]['bar']) to a string using the <expression>::text syntax, which is equivalent to cast(<expression> as text)

  2. Creating a temporary array (in-memory and addressable) from that string using the <expression>[] syntax, which is equivalent to array(expression)

Note: Because this syntax effectively circumvents the index, it may considerably degrade query performance.

Objects within arrays

An individual child object (above) can be selected from a parent array as an array element using the array index syntax:

  1. cr> select name, information[1] from locations
  2. ... where name = 'Outer Eastern Rim';
  3. +-------------------+--------------------------------------------------+
  4. | name | information[1] |
  5. +-------------------+--------------------------------------------------+
  6. | Outer Eastern Rim | {"evolution_level": 2, "population": 5673745846} |
  7. +-------------------+--------------------------------------------------+
  8. SELECT 1 row in set (... sec)

Properties of individual child objects can be selected by combining the array index syntax with the object property name syntax, like so:

  1. cr> select name, information[1]['population'] from locations
  2. ... where name = 'Outer Eastern Rim';
  3. +-------------------+------------------------------+
  4. | name | information[1]['population'] |
  5. +-------------------+------------------------------+
  6. | Outer Eastern Rim | 5673745846 |
  7. +-------------------+------------------------------+
  8. SELECT 1 row in set (... sec)

Additionally, consider this data:

  1. cr> select name, information from locations
  2. ... where information['population'] is not null;
  3. +-------------------+-------------------------------------------------------------------------------------------+
  4. | name | information |
  5. +-------------------+-------------------------------------------------------------------------------------------+
  6. | North West Ripple | [{"evolution_level": 4, "population": 12}, {"evolution_level": 42, "population": 163}] |
  7. | Outer Eastern Rim | [{"evolution_level": 2, "population": 5673745846}] |
  8. | Folfanga | [{"evolution_level": 42, "population": 1}, {"evolution_level": 6, "population": 3600001}] |
  9. +-------------------+-------------------------------------------------------------------------------------------+
  10. SELECT 3 rows in set (... sec)

If you’re only interested in one property of each object (e.g., population), you can select a virtual array containing all of the values for that property, like so:

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

Aggregation

CrateDB provides built-in aggregation functions that allow you to calculate a single summary value for one or more columns:

  1. cr> select count(*) from locations;
  2. +----------+
  3. | count(*) |
  4. +----------+
  5. | 16 |
  6. +----------+
  7. SELECT 1 row in set (... sec)

Window functions

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

  1. cr> select sum(position) OVER() AS pos_sum, name from locations order by name;
  2. +---------+------------------------------------+
  3. | pos_sum | name |
  4. +---------+------------------------------------+
  5. | 48 | |
  6. | 48 | Aldebaran |
  7. | 48 | Algol |
  8. | 48 | Allosimanius Syneca |
  9. | 48 | Alpha Centauri |
  10. | 48 | Altair |
  11. | 48 | Argabuthon |
  12. | 48 | Arkintoofle Minor |
  13. | 48 | Bartledan |
  14. | 48 | Betelgeuse |
  15. | 48 | Folfanga |
  16. | 48 | Frogstar |
  17. | 48 | Galactic Sector QQ7 Active J Gamma |
  18. | 48 | North West Ripple |
  19. | 48 | Outer Eastern Rim |
  20. | 48 | NULL |
  21. +---------+------------------------------------+
  22. SELECT 16 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.

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. | 7 | Star System |
  7. | 5 | Planet |
  8. | 4 | Galaxy |
  9. +----------+-------------+
  10. SELECT 3 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 array columns doesn’t work, but arrays can be unnested in a subquery using unnest. It is then possible to use GROUP BY on the subquery.

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. +----------+--------+
  8. SELECT 1 row 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 aggregate functions in the HAVING clause, like in the result columns:

  1. cr> select count(*), kind from locations
  2. ... group by kind having min(name) = 'Aldebaran';
  3. +----------+-------------+
  4. | count(*) | kind |
  5. +----------+-------------+
  6. | 7 | Star System |
  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.