Scalar Functions

Scalar functions return a single data value (not a table).

Note

Crate can currently only execute scalar functions if used together with the GROUP BY clause or if querying tables inside a system schema (either “sys” or “information_schema”)

See below for a list of available scalar functions.

date_trunc(‘interval’, [‘timezone’,] timestamp) returns timestamp

The date_trunc function truncates a timestamp to a given interval for a specific timezone.

Valid intervals are:

  • second
  • minute
  • hour
  • day
  • week
  • month
  • quarter
  • year

Valid values for timezone are either the name of a time zone (for example ‘Europe/Vienna’) or the UTC offset of a time zone (for example ‘+01:00’). To get a complete overview of all possible values take a look at the available time zones supported by Joda-Time.

The following example shows how to use the date_trunc function to generate a day based histogram in the Europe/Moscow timezone:

cr> select
... date_trunc('day', 'Europe/Moscow', date) as day,
... count(*) as num_locations
... from locations
... group by date_trunc('day', 'Europe/Moscow', date)
... order by date_trunc('day', 'Europe/Moscow', date);
+---------------+---------------+
| day           | num_locations |
+---------------+---------------+
| 308523600000  | 4             |
| 1367352000000 | 1             |
| 1373918400000 | 8             |
+---------------+---------------+
SELECT 3 rows in set (... sec)

If the time zone is not specified, truncation is based on UTC time:

cr> select date_trunc('day', date) as day, count(*) as num_locations
... from locations
... group by date_trunc('day', date)
... order by date_trunc('day', date);
+---------------+---------------+
| day           | num_locations |
+---------------+---------------+
| 308534400000  | 4             |
| 1367366400000 | 1             |
| 1373932800000 | 8             |
+---------------+---------------+
SELECT 3 rows in set (... sec)

format(‘format_string’, parameter, [ parameter , ... ]) returns string

The format function takes a format string and a variable number of arguments and returns a formatted string:

cr> select format('%s.%s', schema_name, table_name) from sys.shards
... where table_name = 'locations'
... limit 1;
+------------------------------------------+
| format('%s.%s', schema_name, table_name) |
+------------------------------------------+
| doc.locations                            |
+------------------------------------------+
SELECT 1 row in set (... sec)

cr> select format('%tY', date) from locations group by format('%tY', date);
+---------------------+
| format('%tY', date) |
+---------------------+
| 2013                |
| 1979                |
+---------------------+
SELECT 2 rows in set (... sec)

For details about the format string syntax see formatter