Table of Contents
Use generate_series() in PostgreSQL
Use a recursive CTE in SQL Server or MySQL
Use a numbers table or calendar table
Watch out for performance and limits
Home Database SQL How to generate a series of numbers or dates in SQL?

How to generate a series of numbers or dates in SQL?

Jul 30, 2025 am 03:24 AM

There are three main ways to generate a number or date sequence in SQL. 1. Use the generate_series() function in PostgreSQL to quickly generate numeric and date sequences, such as SELECT generate_series(1, 10) to generate numeric numbers from 1 to 10, or use date parameters to generate a specified range of dates; 2. Use recursive CTE in SQL Server or MySQL to manually build numeric or date ranges through recursive methods, such as using WITH statements to generate numeric sequences from 1 to 10 or consecutive dates; 3. Use pre-built numeric tables or calendar tables, suitable for all databases, use existing Numbers tables to generate required ranges from DATEADD and other functions, or directly query the calendar table to improve performance and facilitate analysis. In addition, you need to pay attention to performance and limitations, such as recursive depth limitation, avoiding excessive inline generation, and filtering as early as possible to reduce overhead.

How to generate a series of numbers or dates in SQL?

In SQL, generating a series of numbers or dates is something you might need for populating test data, reporting purposes, or joining with existing tables. While SQL doesn't have a built-in range() function like Python, there are several practical ways to accomplish this depending on your database system.

How to generate a series of numbers or dates in SQL?

Use generate_series() in PostgreSQL

If you're working with PostgreSQL , the easiest and most powerful method is using the built-in generate_series() function. It can generate sequences of both numbers and dates.

For example, to generate a list of numbers from 1 to 10:

How to generate a series of numbers or dates in SQL?
 SELECT generate_series(1, 10);

To generate a sequence of dates — say, every day in January 2024:

 SELECT generate_series('2024-01-01'::date, '2024-01-31'::date, '1 day');

This function is fast and flexible, especially when used in joins or subqueries.

How to generate a series of numbers or dates in SQL?

Use a recursive CTE in SQL Server or MySQL

If your database doesn't support generate_series() , such as SQL Server or MySQL , you can use a recursive Common Table Expression (CTE) to build number or date ranges manually.

Here's how to create a number series from 1 to 10 in SQL Server:

 WITH Numbers AS (
    SELECT 1 AS num
    UNION ALL
    SELECT num 1 FROM Numbers WHERE num < 10
)
SELECT num FROM Numbers;

For dates, just add a starting date and increment by one day:

 WITH Dates AS (
    SELECT CAST(&#39;2024-01-01&#39; AS DATE) AS dt
    UNION ALL
    SELECT DATEADD(day, 1, dt) FROM Dates WHERE dt < &#39;2024-01-10&#39;
)
SELECT dt FROM Dates;

You'll want to be careful with recursion limits — some systems cap the number of iterations unless you adjust settings.


Use a numbers table or calendar table

Another approach that works across all databases is having a prebuilt numbers table or calendar table in your database. These are especially useful if you frequently need to generate ranges.

A simple numbers table might look like this:

 CREATE TABLE Numbers (
    num INT PRIMARY KEY
);

Then fill it with values from 1 to 10000 or more. Once you have that, selecting a range becomes easy:

 SELECT num FROM Numbers WHERE num BETWEEN 1 AND 50;

For dates, you can either calculate based on a start date:

 SELECT DATEADD(day, num - 1, &#39;2024-01-01&#39;) AS dt
FROM Numbers
WHERE num <= DATEDIFF(day, &#39;2024-01-01&#39;, &#39;2024-01-31&#39;) 1;

Or better yet, maintain a full calendar table with precomputed dates, which is great for reporting and time-based analysis.


Watch out for performance and limits

When generating large series, especially with recursive CTEs, performance can degrade if not handled carefully. Some things to keep in mind:

  • Recursive depth is limited in many databases unless explicitly configured.
  • Avoid generating huge ranges inline; consider storing them in a helper table instead.
  • If you're using these ranges for joins, make sure to filter early to reduce overhead.

Also, always check your specific database's documentation — functions and syntax may vary slightly between systems like Oracle, SQLite, etc.


That's about it. Depending on your SQL dialect and needs, you've got options ranged from quick one-liners to reusable structures. Not too bad once you know the right tools.

The above is the detailed content of How to generate a series of numbers or dates in SQL?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1503
276
When to use SQL subqueries versus joins for data retrieval. When to use SQL subqueries versus joins for data retrieval. Jul 14, 2025 am 02:29 AM

Whether to use subqueries or connections depends on the specific scenario. 1. When it is necessary to filter data in advance, subqueries are more effective, such as finding today's order customers; 2. When merging large-scale data sets, the connection efficiency is higher, such as obtaining customers and their recent orders; 3. When writing highly readable logic, the subqueries structure is clearer, such as finding hot-selling products; 4. When performing updates or deleting operations that depend on related data, subqueries are the preferred solution, such as deleting users that have not been logged in for a long time.

How to find the second highest salary in SQL How to find the second highest salary in SQL Jul 14, 2025 am 02:06 AM

There are three core methods to find the second highest salary: 1. Use LIMIT and OFFSET to skip the maximum salary and get the maximum, which is suitable for small systems; 2. Exclude the maximum value through subqueries and then find MAX, which is highly compatible and suitable for complex queries; 3. Use DENSE_RANK or ROW_NUMBER window function to process parallel rankings, which is highly scalable. In addition, it is necessary to combine IFNULL or COALESCE to deal with the absence of a second-highest salary.

How to filter for NULL values in a SQL WHERE clause? How to filter for NULL values in a SQL WHERE clause? Jul 09, 2025 am 02:43 AM

Filtering NULL value records in SQL cannot use =NULL or !=NULL, 1. ISNULL or ISNOTNULL must be used; 2. For example, users who look for email columns NULL should write SELECT*FROMusersWHEREemailISNULL; 3. Multiple fields can simultaneously determine that multiple ISNULL conditions can be combined, such as OR or AND connection; 4. COALESCE can replace NULL values ​​for display or default processing, but are not applicable to filtering. Because NULL represents an unknown value and does not participate in the comparison operation of equal or non-equal, =NULL will not return the result and will not report an error. The WHERE clause only accepts TRUE lines, ignores FALSE and UNK

How to create empty tables with the same structure as another table? How to create empty tables with the same structure as another table? Jul 11, 2025 am 01:51 AM

You can use SQL's CREATETABLE statement and SELECT clause to create a table with the same structure as another table. The specific steps are as follows: 1. Create an empty table using CREATETABLEnew_tableASSELECT*FROMexisting_tableWHERE1=0;. 2. Manually add indexes, foreign keys, triggers, etc. when necessary to ensure that the new table is intact and consistent with the original table structure.

Using Regular Expressions (Regex) in SQL Queries. Using Regular Expressions (Regex) in SQL Queries. Jul 10, 2025 pm 01:10 PM

MySQL supports REGEXP and RLIKE; PostgreSQL uses operators such as ~ and ~*; Oracle is implemented through REGEXP_LIKE; SQLServer requires CLR integration or simulation. 2. Regularly used to match mailboxes (such as WHEREemailREGEXP'^[A-Za-z0-9._% -] @[A-Za-z0-9.-] \.[A-Za-z]{2,}$'), extract area codes (such as SUBSTRING(phoneFROM'^(\d{3})')), filter usernames containing numbers (such as REGEXP_LIKE(username,'[0-9]')). 3. Pay attention to performance issues,

Calculating conditional sums or counts in SQL. Calculating conditional sums or counts in SQL. Jul 14, 2025 am 01:39 AM

Calculate the conditional sum or count in SQL, mainly using CASE expressions or aggregate functions with filtering. 1. Using CASE expressions nested in the aggregate function, you can count the results according to different conditions in a single line of query, such as COUNT(CASEWHENstatus='shipped'THEN1END) and SUM(CASEWHENstatus='shipped'THENamountELSE0END); 2. PostgreSQL supports FILTER syntax to make the code more concise, such as COUNT(*)FILTER(WHEREstatus='shipped'); 3. Multiple conditions can be processed in the same query,

SQL for Predictive Analytics SQL for Predictive Analytics Jul 20, 2025 am 02:02 AM

In predictive analysis, SQL can complete data preparation and feature extraction. The key is to clarify the requirements and use SQL functions reasonably. Specific steps include: 1. Data preparation requires extracting historical data from multiple tables and aggregating and cleaning, such as aggregating sales volume by day and associated promotional information; 2. The feature project can use window functions to calculate time intervals or lag features, such as obtaining the user's recent purchase interval through LAG(); 3. Data segmentation is recommended to divide the training set and test set based on time, such as sorting by date with ROW_NUMBER() and marking the collection type proportionally. These methods can efficiently build the data foundation required for predictive models.

What is the purpose of the HAVING COUNT(*) clause in a SQL query? What is the purpose of the HAVING COUNT(*) clause in a SQL query? Jul 09, 2025 am 01:23 AM

TheHAVINGCOUNT(*)clauseinSQLisusedtofiltergroupsofrowsbasedonthenumberofrecordsineachgroupaftergrouping.1.ItworksaftertheGROUPBYclauseandallowsfilteringbasedonaggregatedvalueslikerowcount.2.Forexample,itcanreturnonlycustomerswithmorethan10ordersbycou

See all articles