[Solved] Represent an event occurence on a time chart
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

Represent an event occurence on a time chart

Database type:

I want to represent the time occurrence of an event on a chart. I'm not familiar with javascript. Based on the zoom, it could be the number of occurrence for each seconds, or minutes, or hours, or days, ...

I'm using a nodeJS express website, an mySQL database where I have the timestamp of all my events. A sample of the database:
List of events from database

The Start and Stop period could be severals days/weeks.

I would like to represent the number of disconnection on a chart. With no zoom, I might get the number of disconnection for each day, by zooming, I might get the number of disconnection for each hours, more each minutes and more each seconds. 0 should be displayed when there is no events.
In the same way as:

Before, for a solution which is not dynamic, I've used a mysql query to get the count for every minutes:

select DATE_FORMAT(time, '%Y-%m-%d %H:%i') as date, count(*) as Count    
from db    
WHERE event = "disconnected"    
group by date

But the result is:

2019-09-18 00:36    4
2019-09-18 18:14    2
2019-10-02 11:43    2
2019-10-02 11:44    1

I would need to get every minutes with 0 when there is not events to get a correct barchart.
Right now, I have this display:

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. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
  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'.
Optimal indexes for this query:
ALTER TABLE `db` ADD INDEX `db_idx_event` (`event`);
The optimized query:
        '%Y-%m-%d %H:%i') AS date,
        count(*) AS Count 
        db.event = 'disconnected' 

Related Articles

* original question posted on StackOverflow here.