Home > Database > Mysql Tutorial > How Can I Generate a Sequence of Numbers Between Two Given Values Using SQL?

How Can I Generate a Sequence of Numbers Between Two Given Values Using SQL?

DDD
Release: 2025-01-20 03:06:10
Original
552 people have browsed it

How Can I Generate a Sequence of Numbers Between Two Given Values Using SQL?

Generating Number Ranges with SQL

Need to create a sequence of numbers between two specified values (e.g., 1000 and 1050) within a SQL database? This article demonstrates efficient methods using VALUES and JOIN operations.

The core idea is to generate a set of numbers using VALUES and then use JOIN to combine these into a larger range. This approach easily scales to generate hundreds of thousands of rows by expanding the query.

Here's a compact solution:

<code class="language-sql">WITH x AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) v(n))
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM x ones, x tens, x hundreds, x thousands
ORDER BY 1</code>
Copy after login

A more explicit method is:

<code class="language-sql">SELECT ones.n + 10*tens.n + 100*hundreds.n + 1000*thousands.n
FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n),
     (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) tens(n),
     (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) hundreds(n),
     (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) thousands(n)
ORDER BY 1</code>
Copy after login

Both examples can be customized to generate specific ranges by adding a WHERE clause. For frequent use, consider creating a table-valued function for reusability.

The above is the detailed content of How Can I Generate a Sequence of Numbers Between Two Given Values Using 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template