


How Can I Efficiently Generate a Sequence of Dates Within a Specific Range in SQL?
Jan 23, 2025 pm 05:17 PMEfficient method to generate SQL date range
In database programming, generating a date sequence within a specific date range is a common task. For example, query the dates between January 20, 2010 and January 24, 2010:
SELECT ... AS days WHERE `date` BETWEEN '2010-01-20' AND '2010-01-24'
The expected result is:
<code>days ---------- 2010-01-20 2010-01-21 2010-01-22 2010-01-23 2010-01-24</code>
Efficient subquery solution
An efficient solution is to use a subquery to generate a date sequence:
SELECT a.Date FROM ( 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 ) a WHERE a.Date BETWEEN '2010-01-20' AND '2010-01-24'
Performance Considerations
This solution is extremely performant, with query execution time of only 0.0009 seconds. Even generating 100,000 dates (about 274 years), the query execution time is only 0.0458 seconds.
Portability
This technology is highly portable and can be adapted to most database systems with only minor adjustments.
The above is the detailed content of How Can I Efficiently Generate a Sequence of Dates Within a Specific Range in SQL?. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Reduce the use of MySQL memory in Docker

How do you alter a table in MySQL using the ALTER TABLE statement?

How to solve the problem of mysql cannot open shared library

Run MySQl in Linux (with/without podman container with phpmyadmin)

What is SQLite? Comprehensive overview

Running multiple MySQL versions on MacOS: A step-by-step guide

What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)?

How do I configure SSL/TLS encryption for MySQL connections?
