Home > Database > Mysql Tutorial > How Can I Generate a Range of Numbers in SQL Using Only Queries?

How Can I Generate a Range of Numbers in SQL Using Only Queries?

Barbara Streisand
Release: 2025-01-20 03:16:13
Original
553 people have browsed it

How Can I Generate a Range of Numbers in SQL Using Only Queries?

Pure SQL query to generate numeric sequence

In SQL, using non-persistent values ​​(VALUES keyword) and JOIN operations, you can generate a sequence of numbers within a specified range.

Simple 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

This scheme generates a number range by creating a Cartesian product of four values ​​representing units, tens, hundreds, and thousands. The ROW_NUMBER() function assigns unique row numbers in the desired order.

Detailed plan:

<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

This scheme calculates numerical values ​​explicitly by adding values ​​in units, tens, hundreds and thousands places. Both scenarios can be expanded with a WHERE clause to specify a range of numbers. For larger scopes, table-valued functions can be created to reuse code.

The above is the detailed content of How Can I Generate a Range of Numbers in SQL Using Only Queries?. 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