mysqlsqlsql-functiongeneratemysql-function

Generate a sequence of square numbers till 10


How to generate a sequence of SQUARE numbers till 10 in MYSQL? (1^2,2^2, etc)

I was only able to generate a numerical sequence from 1 to 10.

WITH RECURSIVE cte (n) AS
(
  SELECT 1
  UNION ALL
  SELECT (n + 1) FROM cte WHERE n < 10
)
SELECT n FROM cte;

But if I add the POW() function, the result will be

WITH RECURSIVE cte (n) AS
(
  SELECT 1
  UNION ALL
  SELECT POW((n + 1),2) FROM cte WHERE n < 10
)
SELECT n FROM cte;

RESULT: 1 4 25


Solution

  • you need to square the resul of the cte

    WITH RECURSIVE cte (n) AS
    (
      SELECT 1
      UNION ALL
      SELECT (n + 1) FROM cte WHERE n < 10
    )
    SELECT POW(n,2) FROM cte;
    
    POW(n,2)
    1
    4
    9
    16
    25
    36
    49
    64
    81
    100

    fiddle