[Solved] Group by day from nanosecond timestamp

EverSQL Database Performance Knowledge Base

Group by day from nanosecond timestamp

I have a table column transaction_timestamp storing timestamps as epochs with nanosecond resolution.

How do I group and/or count by day? I guess I have to convert the nanosecond timestamp to milliseconds first. How can I do that?

I tried:

SELECT DATE_TRUNC('day', CAST((transaction_timestamp /pow(10,6))as bigint)), COUNT(*)
FROM transaction
GROUP BY DATE_TRUNC('day', transaction_timestamp)

which is does not work:

error: function date_trunc(unknown, bigint) does not exist

I also tried this:

SELECT DATE_TRUNC('day', to_timestamp(transaction_timestamp / 1000000000.0)),
 COUNT(*)
FROM transaction
GROUP BY DATE_TRUNC('day', transaction_timestamp)

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Calling Functions With Indexed Columns (query line: 9): When a function is used directly on an indexed column, the database's optimizer won’t be able to use the index. For example, if the column `transaction_timestamp` is indexed, the index won’t be used as it’s wrapped with the function `DATE_TRUNC`. If you can’t find an alternative condition that won’t use a function call, a possible solution is to store the required value in a new indexed column.
  2. Explicitly ORDER BY After GROUP BY (modified query below): By default, the database sorts all 'GROUP BY col1, col2, ...' queries as if you specified 'ORDER BY col1, col2, ...' in the query as well. If a query includes a GROUP BY clause but you want to avoid the overhead of sorting the result, you can suppress sorting by specifying 'ORDER BY NULL'.
The optimized query:
SELECT
        DATE_TRUNC('day',
        CAST((transaction.transaction_timestamp / pow(10,
        6)) AS bigint)),
        COUNT(*) 
    FROM
        transaction 
    GROUP BY
        DATE_TRUNC('day',
        transaction.transaction_timestamp) 
    ORDER BY
        NULL

Related Articles



* original question posted on StackOverflow here.