Skip to content
Advertisement

SQL not returning a value if no row exist for time queried

I’m writing this SQL query which returns the number of records created in an hour in last 24 hours. I’m getting the result for only those hours that have a non zero value. If no records were created, it doesn’t return anything at all.

Here’s my query:

The output of current Query:

But i’m expecting 0 for hours in which no records were created. Where am I going wrong?

Advertisement

Answer

One solution is to generate a table of numbers from 0 to 23 and left join it with your original table.

Here is a query that uses a recursive query to generate the list of hours (if you are running MySQL, this requires version 8.0):

If your RDBMS does not support recursive CTEs, then one option is to use an explicit derived table:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement