SQL SELECT to get the first N positive integers

A possible solution (admittedly not very elegant) is to use any table with a sufficiently large number of records.

For the first 10 integers (using the mysql.help_relation, but any table would do), you could use the following query:

SELECT  @N := @N +1 AS integers 
FROM mysql.help_relation , (SELECT @N:=0) dum LIMIT 10;

This could also be placed in a function taking Min and Max.


Seems that what you want is a dummy rowset.

In MySQL, it's impossible without having a table.

Most major systems provide a way to do it:

  • In Oracle:

    SELECT  level
    FROM    dual
    CONNECT BY
            level <= 10
    
  • In SQL Server:

    WITH    q AS
            (
            SELECT  1 AS num
            UNION ALL
            SELECT  num + 1
            FROM    q
            WHERE   num < 10
            )
    SELECT  *
    FROM    q
    
  • In PostgreSQL:

    SELECT  num
    FROM    generate_series(1, 10) num
    

MySQL lacks something like this and this is a serious drawback.

I wrote a simple script to generate test data for the sample tables in my blog posts, maybe it will be of use:

CREATE TABLE filler (
        id INT NOT NULL PRIMARY KEY AUTO_INCREMENT
) ENGINE=Memory;

CREATE PROCEDURE prc_filler(cnt INT)
BEGIN
        DECLARE _cnt INT;
        SET _cnt = 1;
        WHILE _cnt <= cnt DO
                INSERT
                INTO    filler
                SELECT  _cnt;
                SET _cnt = _cnt + 1;
        END WHILE;
END
$$

You call the procedure and the table gets filled with the numbers.

You can reuse it during the duration of the session.

Tags:

Mysql

Sql