
.. _scalar:

================
Scalar Functions
================

.. _scalar-date-trunc:

date_trunc('interval', ['timezone',] 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)


.. Note::

    Currently scalar functions, such as ``date_trunc``, can only be used in
    the ``GROUP BY`` and ``ORDER BY`` clauses.

.. _`available time zones`: http://www.joda.org/joda-time/timezones.html

.. _`Joda-Time`: http://www.joda.org/joda-time/
