Sql to generate a list of numbers from 1 to 100
Generate a sequence from 1 to 100 in SQL using a Recursive CTE:
This concise script creates an on-the-fly number table using recursion, perfect for quick data sets.
Oracle-specific methods
Hierarchical method: CONNECT BY LEVEL
Oracle SQL provides an efficient method of generating series of numbers using CONNECT BY LEVEL
.
Here, Oracle's in-build pseudo column LEVEL
auto-increments for each iteration of our dummy table DUAL.
Recursive subquery: WITH clause
A powerful alternative in Oracle is the recursive WITH clause.
It achieves the same as the CTE in our fast answer but is specialized for Oracle.
Special mentions
XMLTABLE: A distinctive approach
A distinctive method involves XMLTABLE
:
This method uses the implied COLUMN_VALUE along with XML to create a number series anytime, anyplace!
MODEL clause: Structuring your numbers
With Oracle's MODEL clause, a series of numbers have never looked this good:
The clause iterates to populate N
with consecutive numbers from 1 to 100.
Dealing with different databases
PostgreSQL: The built-in saviour
In PostgreSQL, the built-in generate_series
function makes it trivial:
MySQL: DUAL, the unsung hero
In MySQL, we can simulate a series using variables and good old DUAL:
SQL Server: Back to the basics
SQL Server, as demonstrated in our fast answer, can leverage Recursive CTEs to perfection. Just watch the MAXRECURSION!
Best practices for safeguarding your queries
Remember to:
- Order your numbers with
ORDER BY
clause. Numbers love to stay in line! - Understand resource limits and performance trade-offs. Bigger isn't always better.
- Always look for specific optimization techniques in your specific RDBMS. When in Rome...
Was this article helpful?