Home > Database > Mysql Tutorial > How to Efficiently Generate a Date Range in SQL?

How to Efficiently Generate a Date Range in SQL?

Linda Hamilton
Release: 2025-01-23 17:22:13
Original
181 people have browsed it

How to Efficiently Generate a Date Range in SQL?

SQL date range generation skills

There are many ways to generate a list of dates within a specified range in SQL. This article takes generating the date sequence from '2010-01-20' to '2010-01-24' as an example to introduce an efficient solution.

This method uses a subquery to generate a complete date collection. Through the combination of four nested loops, the subquery can efficiently generate date sequences up to 10,000 days and can be easily extended to longer date ranges.

<code class="language-sql">select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a) + (1000 * d.a) ) DAY as Date
from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as d</code>
Copy after login

We then filter the generated date list to extract dates within the target range:

<code class="language-sql">select a.Date
from (
select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a) + (1000 * d.a) ) DAY as Date
from (...) as a
) a
where a.Date between '2010-01-20' and '2010-01-24'</code>
Copy after login

The advantages of this approach are: no loops, stored procedures or temporary tables required, efficient and portable to multiple database platforms. Generating 10,000 days of dates takes less than 0.01 seconds, and the performance is still excellent even when generating dates of about 100,000 days.

The above is the detailed content of How to Efficiently Generate a Date Range in SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template