Make a table of sequential ints

from the Artful Common Queries page


For example, a table of 1,000 ints starting from 0 with interval=1...

drop table if exists ints;
create table ints(i tinyint);
insert into ints values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9);

drop table if exists temp;
create table temp
select 100*c.i+10*b.i+a.i as iseq 
from ints a,ints b, ints c order by iseq;

Suppose you need a table of 4,000 sequential ints starting at 1 with interval=4. Each term = 1 + a multiple of 4, so ...

drop table if exists temp;
create table temp
select iseq from (
  select 1 + (10000*e.i + 1000*d.i + 100*c.i + 10*b.i + a.i) as iseq  
  from ints a, ints b, ints c, ints d, ints e 
  order by iseq
) x
where iseq%4 = 1 and iseq < 16000;

You need to save the numbers as 4-byte binary strings?

create table temp 
select lpad( conv(iseq, 10, 16), 4, 0 ) as ibin
from ( 
  select 1 + (10000*e.i + 1000*d.i + 100*c.i + 10*b.i + a.i) as iseq   
  from ints a, ints b, ints c, ints d, ints e  
  order by iseq 
) x 
where x.iseq%4 = 1 and iseq < 16000; 

Such tables are useful for building all kinds of sequences, for example sequential dates, and for replacing iterative loops that would otherwise require procedural code. In the SQL Server world, they're known as "tally tables".

Return to the Artful Common Queries page