<p>For certain types of sql queries, an auxiliary table of numbers can be very useful. It may be created as a table with as many rows as you need for a particular task or as a user defined function that returns the number of rows required in each query.</p>

<p>What is the optimal way to create such a function?</p>

[{'answer_id': 39122, 'author': 'mrdenny', 'author_id': 4197, 'author_profile': 'https://Stackoverflow.com/users/4197', 'pm_score': 4, 'selected': False, 'text': '<p>The most optimal function would be to use a table instead of a function.  Using a function causes extra CPU load to create the values for the data being returned, especially if the values being returned cover a very large range.</p>\n'}, {'answer_id': 1479258, 'author': 'Chadwick', 'author_id': 80714, 'author_profile': 'https://Stackoverflow.com/users/80714', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://web.archive.org/web/20120413120912/http://www.projectdmx.com:80/tsql/tblnumbers.aspx" rel="nofollow noreferrer">This article</a> gives 14 different possible solutions with discussion of each. The important point is that:</p>\n\n<blockquote>\n  <p>suggestions regarding efficiency and\n  performance are often subjective.\n  Regardless of how a query is being\n  used, the physical implementation\n  determines the efficiency of a query.\n  Therefore, rather than relying on\n  biased guidelines, it is imperative\n  that you test the query and determine\n  which one performs better.</p>\n</blockquote>\n\n<p>I personally liked:</p>\n\n<pre><code>WITH Nbrs ( n ) AS (\n    SELECT 1 UNION ALL\n    SELECT 1 + n FROM Nbrs WHERE n &lt; 500 )\nSELECT n FROM Nbrs\nOPTION ( MAXRECURSION 500 )\n</code></pre>\n'}, {'answer_id': 2663232, 'author': 'Jeff Moden', 'author_id': 313265, 'author_profile': 'https://Stackoverflow.com/users/313265', 'pm_score': 8, 'selected': True, 'text': '<p>Heh... sorry I\'m so late responding to an old post.  And, yeah, I had to respond because the most popular answer (at the time, the Recursive CTE answer with the link to 14 different methods) on this thread is, ummm... performance challenged at best.</p>\n\n<p>First, the article with the 14 different solutions is fine for seeing the different methods of creating a Numbers/Tally table on the fly but as pointed out in the article and in the cited thread, there\'s a <em>very</em> important quote...</p>\n\n<blockquote>\n  <p>"suggestions regarding efficiency and\n  performance are often subjective.\n  Regardless of how a query is being\n  used, the physical implementation\n  determines the efficiency of a query.\n  Therefore, rather than relying on\n  biased guidelines, it is imperative\n  that you test the query and determine\n  which one performs better."</p>\n</blockquote>\n\n<p>Ironically, the article itself contains many subjective statements and "biased guidelines" such as <em>"a recursive CTE can generate a number listing <strong>pretty efficiently</strong>"</em> and <em>"This is <strong>an efficient method</strong> of using WHILE loop from a newsgroup posting by Itzik Ben-Gen"</em> (which I\'m sure he posted just for comparison purposes).  C\'mon folks... Just mentioning Itzik\'s good name may lead some poor slob into actually using that horrible method.  The author should practice what (s)he preaches and should do a little performance testing before making such ridiculously incorrect statements especially in the face of any scalablility.</p>\n\n<p>With the thought of actually doing some testing before making any subjective claims about what any code does or what someone "likes", here\'s some code you can do your own testing with.  Setup profiler for the SPID you\'re running the test from and check it out for yourself... just do a "Search\'n\'Replace" of the number 1000000 for your "favorite" number and see...</p>\n\n<pre><code>--===== Test for 1000000 rows ==================================\nGO\n--===== Traditional RECURSIVE CTE method\n   WITH Tally (N) AS \n        ( \n         SELECT 1 UNION ALL \n         SELECT 1 + N FROM Tally WHERE N &lt; 1000000 \n        ) \n SELECT N \n   INTO #Tally1 \n   FROM Tally \n OPTION (MAXRECURSION 0);\nGO\n--===== Traditional WHILE LOOP method\n CREATE TABLE #Tally2 (N INT);\n    SET NOCOUNT ON;\nDECLARE @Index INT;\n    SET @Index = 1;\n  WHILE @Index &lt;= 1000000 \n  BEGIN \n         INSERT #Tally2 (N) \n         VALUES (@Index);\n            SET @Index = @Index + 1;\n    END;\nGO\n--===== Traditional CROSS JOIN table method\n SELECT TOP (1000000)\n        ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS N\n   INTO #Tally3\n   FROM Master.sys.All_Columns ac1\n  CROSS JOIN Master.sys.ALL_Columns ac2;\nGO\n--===== Itzik\'s CROSS JOINED CTE method\n   WITH E00(N) AS (SELECT 1 UNION ALL SELECT 1),\n        E02(N) AS (SELECT 1 FROM E00 a, E00 b),\n        E04(N) AS (SELECT 1 FROM E02 a, E02 b),\n        E08(N) AS (SELECT 1 FROM E04 a, E04 b),\n        E16(N) AS (SELECT 1 FROM E08 a, E08 b),\n        E32(N) AS (SELECT 1 FROM E16 a, E16 b),\n   cteTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY N) FROM E32)\n SELECT N\n   INTO #Tally4\n   FROM cteTally\n  WHERE N &lt;= 1000000;\nGO\n--===== Housekeeping\n   DROP TABLE #Tally1, #Tally2, #Tally3, #Tally4;\nGO\n</code></pre>\n\n<p>While we\'re at it, here\'s the numbers I get from SQL Profiler for the values of 100, 1000, 10000, 100000, and 1000000...</p>\n\n<pre><code>SPID TextData                                 Dur(ms) CPU   Reads   Writes\n---- ---------------------------------------- ------- ----- ------- ------\n  51 --===== Test for 100 rows ==============       8     0       0      0\n  51 --===== Traditional RECURSIVE CTE method      16     0     868      0\n  51 --===== Traditional WHILE LOOP method CR      73    16     175      2\n  51 --===== Traditional CROSS JOIN table met      11     0      80      0\n  51 --===== Itzik\'s CROSS JOINED CTE method        6     0      63      0\n  51 --===== Housekeeping   DROP TABLE #Tally      35    31     401      0\n\n  51 --===== Test for 1000 rows =============       0     0       0      0\n  51 --===== Traditional RECURSIVE CTE method      47    47    8074      0\n  51 --===== Traditional WHILE LOOP method CR      80    78    1085      0\n  51 --===== Traditional CROSS JOIN table met       5     0      98      0\n  51 --===== Itzik\'s CROSS JOINED CTE method        2     0      83      0\n  51 --===== Housekeeping   DROP TABLE #Tally       6    15     426      0\n\n  51 --===== Test for 10000 rows ============       0     0       0      0\n  51 --===== Traditional RECURSIVE CTE method     434   344   80230     10\n  51 --===== Traditional WHILE LOOP method CR     671   563   10240      9\n  51 --===== Traditional CROSS JOIN table met      25    31     302     15\n  51 --===== Itzik\'s CROSS JOINED CTE method       24     0     192     15\n  51 --===== Housekeeping   DROP TABLE #Tally       7    15     531      0\n\n  51 --===== Test for 100000 rows ===========       0     0       0      0\n  51 --===== Traditional RECURSIVE CTE method    4143  3813  800260    154\n  51 --===== Traditional WHILE LOOP method CR    5820  5547  101380    161\n  51 --===== Traditional CROSS JOIN table met     160   140     479    211\n  51 --===== Itzik\'s CROSS JOINED CTE method      153   141     276    204\n  51 --===== Housekeeping   DROP TABLE #Tally      10    15     761      0\n\n  51 --===== Test for 1000000 rows ==========       0     0       0      0\n  51 --===== Traditional RECURSIVE CTE method   41349 37437 8001048   1601\n  51 --===== Traditional WHILE LOOP method CR   59138 56141 1012785   1682\n  51 --===== Traditional CROSS JOIN table met    1224  1219    2429   2101\n  51 --===== Itzik\'s CROSS JOINED CTE method     1448  1328    1217   2095\n  51 --===== Housekeeping   DROP TABLE #Tally       8     0     415      0\n</code></pre>\n\n<p>As you can see, <strong>the Recursive CTE method is the second worst only to the While Loop for Duration and CPU and has 8 times the memory pressure in the form of logical reads than the While Loop</strong>. It\'s RBAR on steroids and should be avoided, at all cost, for any single row calculations just as a While Loop should be avoided.  <strong>There are places where recursion is quite valuable but this ISN\'T one of them</strong>.</p>\n\n<p>As a side bar, Mr. Denny is absolutely spot on... a correctly sized permanent Numbers or Tally table is the way to go for most things.  What does correctly sized mean?  Well, most people use a Tally table to generate dates or to do splits on VARCHAR(8000).  If you create an 11,000 row Tally table with the correct clustered index on "N", you\'ll have enough rows to create more than 30 years worth of dates (I work with mortgages a fair bit so 30 years is a key number for me) and certainly enough to handle a VARCHAR(8000) split.  Why is "right sizing" so important?  If the Tally table is used a lot, it easily fits in cache which makes it blazingly fast without much pressure on memory at all.</p>\n\n<p>Last but not least, every one knows that if you create a permanent Tally table, it doesn\'t much matter which method you use to build it because 1) it\'s only going to be made once and 2) if it\'s something like an 11,000 row table, all of the methods are going to run "good enough".  <strong>So why all the indigination on my part about which method to use???</strong></p>\n\n<p>The answer is that some poor guy/gal who doesn\'t know any better and just needs to get his or her job done might see something like the Recursive CTE method and decide to use it for something much larger and much more frequently used than building a permanent Tally table and I\'m trying to <strong>protect those people, the servers their code runs on, and the company that owns the data on those servers</strong>.  Yeah... it\'s that big a deal. It should be for everyone else, as well.  Teach the right way to do things instead of "good enough".  Do some testing before posting or using something from a post or book... the life you save may, in fact, be your own especially if you think a recursive CTE is the way to go for something like this. ;-)</p>\n\n<p>Thanks for listening...</p>\n'}, {'answer_id': 4745368, 'author': 'Ruskin', 'author_id': 581414, 'author_profile': 'https://Stackoverflow.com/users/581414', 'pm_score': 0, 'selected': False, 'text': '<p>edit: see Conrad\'s comment below.</p>\n\n<p>Jeff Moden\'s answer is great ... but I find on Postgres that the Itzik method fails unless you remove the E32 row.</p>\n\n<p>Slightly faster on postgres (40ms vs 100ms) is another method I found on <a href="http://www.sqlservercentral.com/articles/T-SQL/67899/" rel="nofollow">here</a> adapted for postgres:</p>\n\n<pre><code>WITH \n    E00 (N) AS ( \n        SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL \n        SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 ),\n    E01 (N) AS (SELECT a.N FROM E00 a CROSS JOIN E00 b),\n    E02 (N) AS (SELECT a.N FROM E01 a CROSS JOIN E01 b ),\n    E03 (N) AS (SELECT a.N FROM E02 a CROSS JOIN E02 b \n        LIMIT 11000  -- end record  11,000 good for 30 yrs dates\n    ), -- max is 100,000,000, starts slowing e.g. 1 million 1.5 secs, 2 mil 2.5 secs, 3 mill 4 secs\n    Tally (N) as (SELECT row_number() OVER (ORDER BY a.N) FROM E03 a)\n\nSELECT N\nFROM Tally\n</code></pre>\n\n<p>As I am moving from SQL Server to Postgres world, may have missed a better way to do tally tables on that platform ... INTEGER()? SEQUENCE()?</p>\n'}, {'answer_id': 6571438, 'author': 'Anthony Faull', 'author_id': 63264, 'author_profile': 'https://Stackoverflow.com/users/63264', 'pm_score': 2, 'selected': False, 'text': '<p>This view is super fast and contains all positive <code>int</code> values.</p>\n\n<pre><code>CREATE VIEW dbo.Numbers\nWITH SCHEMABINDING\nAS\n    WITH Int1(z) AS (SELECT 0 UNION ALL SELECT 0)\n    , Int2(z) AS (SELECT 0 FROM Int1 a CROSS JOIN Int1 b)\n    , Int4(z) AS (SELECT 0 FROM Int2 a CROSS JOIN Int2 b)\n    , Int8(z) AS (SELECT 0 FROM Int4 a CROSS JOIN Int4 b)\n    , Int16(z) AS (SELECT 0 FROM Int8 a CROSS JOIN Int8 b)\n    , Int32(z) AS (SELECT TOP 2147483647 0 FROM Int16 a CROSS JOIN Int16 b)\n    SELECT ROW_NUMBER() OVER (ORDER BY z) AS n\n    FROM Int32\nGO\n</code></pre>\n'}, {'answer_id': 26505041, 'author': 'HansLindgren', 'author_id': 1202332, 'author_profile': 'https://Stackoverflow.com/users/1202332', 'pm_score': 0, 'selected': False, 'text': "<p>Still much later, I'd like to contribute a slightly different 'traditional' CTE (does not touch base tables to get the volume of rows):</p>\n\n<pre><code>--===== Hans CROSS JOINED CTE method\nWITH Numbers_CTE (Digit)\nAS\n(SELECT 0 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)\nSELECT HundredThousand.Digit * 100000 + TenThousand.Digit * 10000 + Thousand.Digit * 1000 + Hundred.Digit * 100 + Ten.Digit * 10 + One.Digit AS Number\nINTO #Tally5\nFROM Numbers_CTE AS One CROSS JOIN Numbers_CTE AS Ten CROSS JOIN Numbers_CTE AS Hundred CROSS JOIN Numbers_CTE AS Thousand CROSS JOIN Numbers_CTE AS TenThousand CROSS JOIN Numbers_CTE AS HundredThousand\n</code></pre>\n\n<p>This CTE performs more READs then Itzik's CTE but less then the Traditional CTE.\n<strong>However, it consistently performs less WRITES then the other queries.</strong>\nAs you know, Writes are consistently quite much more expensive then Reads.</p>\n\n<p>The duration depends heavily on the number of cores (MAXDOP) but, on my 8core, performs consistently quicker (less duration in ms) then the other queries.</p>\n\n<p>I am using:</p>\n\n<pre><code>Microsoft SQL Server 2012 - 11.0.5058.0 (X64) \nMay 14 2014 18:34:29 \nCopyright (c) Microsoft Corporation\nEnterprise Edition (64-bit) on Windows NT 6.3 &lt;X64&gt; (Build 9600: )\n</code></pre>\n\n<p>on Windows Server 2012 R2, 32 GB, Xeon X3450 @2.67Ghz, 4 cores HT enabled.</p>\n"}, {'answer_id': 36987175, 'author': 'Lukasz Szozda', 'author_id': 5070879, 'author_profile': 'https://Stackoverflow.com/users/5070879', 'pm_score': 1, 'selected': False, 'text': '<p>Using <code>SQL Server 2016+</code> to generate numbers table you could use <code>OPENJSON</code> :</p>\n\n<pre><code>-- range from 0 to @max - 1\nDECLARE @max INT = 40000;\n\nSELECT rn = CAST([key] AS INT) \nFROM OPENJSON(CONCAT(\'[1\', REPLICATE(CAST(\',1\' AS VARCHAR(MAX)),@max-1),\']\'));\n</code></pre>\n\n<p><kbd><strong><a href="https://data.stackexchange.com/stackoverflow/query/481961" rel="nofollow"><code>LiveDemo</code></a></strong></kbd></p>\n\n<p><hr>\nIdea taken from <a href="https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/generate-serie-of-numbers-in-sql-server-2016-using-openjson/" rel="nofollow">How can we use OPENJSON to generate series of numbers?</a></p>\n'}, {'answer_id': 71426969, 'author': 'Martin Smith', 'author_id': 73226, 'author_profile': 'https://Stackoverflow.com/users/73226', 'pm_score': 2, 'selected': False, 'text': '<p>From SQL Server 2022 <a href="https://learn.microsoft.com/en-us/sql/t-sql/functions/generate-series-transact-sql" rel="nofollow noreferrer">you will be able to do</a></p>\n<pre><code>SELECT Value\nFROM GENERATE_SERIES(START = 1, STOP = 100, STEP=1)\n</code></pre>\n<p>In the public preview of SQL Server 2022 (CTP2.0) there are some very promising elements and other less so. Hopefully the negative aspects can be addressed before the actual release.</p>\n<p>✅ <strong>Execution time for number generation</strong>\nThe below generates 10,000,000 numbers in 700 ms in my test VM (the assigning to a variable removes any overhead from sending results to the client)</p>\n<pre><code>DECLARE @Value INT \n\nSELECT @Value =[value]\nFROM GENERATE_SERIES(START=1, STOP=10000000)\n</code></pre>\n<p>✅ <strong>Cardinality estimates</strong></p>\n<p>It is simple to calculate how many numbers will be returned from the operator and SQL Server takes advantage of this as shown below.</p>\n<p><a href="https://i.stack.imgur.com/k9IOk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k9IOk.png" alt="enter image description here" /></a></p>\n<p>❌  <strong>Unnecessary <a href="https://en.wikipedia.org/wiki/Halloween_Problem" rel="nofollow noreferrer">Halloween Protection</a></strong></p>\n<p>The plan for the below insert has a completely unnecessary spool - presumably as SQL Server does not currently have logic to determine the source of the rows is not potentially the destination.</p>\n<pre><code>CREATE TABLE dbo.NumberHeap(Number INT);\n\nINSERT INTO dbo.Numbers\nSELECT [value]\nFROM GENERATE_SERIES(START=1, STOP=10);\n</code></pre>\n<p>When inserting into a table with a clustered index on Number the spool may be replaced by a sort instead (that also provides the phase separation)</p>\n<p><a href="https://i.stack.imgur.com/wsj5n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wsj5n.png" alt="enter image description here" /></a></p>\n<p>❌  <strong>Unnecessary sorts</strong></p>\n<p>The below will return the rows in order anyway but SQL Server apparently does not yet have the properties set to guarantee this and take advantage of it in the execution plan.</p>\n<pre><code>SELECT [value]\nFROM GENERATE_SERIES(START=1, STOP=10)\nORDER BY [value] \n</code></pre>\n<p><a href="https://i.stack.imgur.com/WWQ0O.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WWQ0O.png" alt="enter image description here" /></a></p>\n<p>RE: This last point <a href="https://www.mssqltips.com/sqlservertip/7265/sql-server-2022-t-sql-enhancements/" rel="nofollow noreferrer">Aaron Bertrand indicates</a> that this is not a box currently ticked but that this may be forthcoming.</p>\n'}]
['https://Stackoverflow.com/questions/10819', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/224/']