Skip to content
Advertisement

Best way to run a SQL query for different dates

I have a PHP application that records the sessions of various devices connected to a server. The database has a table session, with the columns device_id, start_date, end_date. To know the number of devices connected on a given date, I can use the request :

SELECT COUNT(DISTINCT device_id)
FROM session
WHERE :date >= start_date AND (:date <= end_date OR end_date IS NULL)

where :date is passed as a parameter to the prepared statement.

This works fine, but if I want to know the number of devices for every days of the year, that makes 365 queries to run, and I’m afraid things could get very slow. It doesn’t feel right to be iterating on the date in PHP, it seems to me that there should be a more optimal way to do this, with a single query to the database.

  1. Is it possible do this with a single query?

  2. Would it actually be faster than to iterate on the date in PHP an running multiple queries?


EDIT to answer the comments :

  • I do want the number for each separate day (to draw a graph for example), not just the sum

  • the datatype is DATE

Advertisement

Answer

If I understand correctly then you first need a table of dates, something like:

create table dates(dt date);
insert into dates(dt) values
('2001-01-01'),
('2001-01-02'),
...
('2100-12-31')

And use a query like so:

select dates.dt, count(session.device_id)
from dates
join session on start_date <= dates.dt and (dates.dt <= end_date or end_date is null)
-- change to left join to include zero counts
where dates.dt >= :date1 and dates.dt <= :date2
group by dates.dt

PS: since you mentioned charts I might add that it is possible to avoid the table of dates. However, the result will only contain dates on which the count of devices changed. Chart APIs usually accept this kind of data but still create data points for all dates in between.

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